babylon.max.js 3.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var KeyboardEventTypes = (function () {
  20. function KeyboardEventTypes() {
  21. }
  22. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  23. get: function () {
  24. return KeyboardEventTypes._KEYDOWN;
  25. },
  26. enumerable: true,
  27. configurable: true
  28. });
  29. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  30. get: function () {
  31. return KeyboardEventTypes._KEYUP;
  32. },
  33. enumerable: true,
  34. configurable: true
  35. });
  36. KeyboardEventTypes._KEYDOWN = 0x01;
  37. KeyboardEventTypes._KEYUP = 0x02;
  38. return KeyboardEventTypes;
  39. }());
  40. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  41. var KeyboardInfo = (function () {
  42. function KeyboardInfo(type, event) {
  43. this.type = type;
  44. this.event = event;
  45. }
  46. return KeyboardInfo;
  47. }());
  48. BABYLON.KeyboardInfo = KeyboardInfo;
  49. /**
  50. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  51. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  52. */
  53. var KeyboardInfoPre = (function (_super) {
  54. __extends(KeyboardInfoPre, _super);
  55. function KeyboardInfoPre(type, event) {
  56. var _this = _super.call(this, type, event) || this;
  57. _this.skipOnPointerObservable = false;
  58. return _this;
  59. }
  60. return KeyboardInfoPre;
  61. }(KeyboardInfo));
  62. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  63. })(BABYLON || (BABYLON = {}));
  64. //# sourceMappingURL=babylon.keyboardEvents.js.map
  65. var BABYLON;
  66. (function (BABYLON) {
  67. var PointerEventTypes = (function () {
  68. function PointerEventTypes() {
  69. }
  70. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  71. get: function () {
  72. return PointerEventTypes._POINTERDOWN;
  73. },
  74. enumerable: true,
  75. configurable: true
  76. });
  77. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  78. get: function () {
  79. return PointerEventTypes._POINTERUP;
  80. },
  81. enumerable: true,
  82. configurable: true
  83. });
  84. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  85. get: function () {
  86. return PointerEventTypes._POINTERMOVE;
  87. },
  88. enumerable: true,
  89. configurable: true
  90. });
  91. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  92. get: function () {
  93. return PointerEventTypes._POINTERWHEEL;
  94. },
  95. enumerable: true,
  96. configurable: true
  97. });
  98. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  99. get: function () {
  100. return PointerEventTypes._POINTERPICK;
  101. },
  102. enumerable: true,
  103. configurable: true
  104. });
  105. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  106. get: function () {
  107. return PointerEventTypes._POINTERTAP;
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  113. get: function () {
  114. return PointerEventTypes._POINTERDOUBLETAP;
  115. },
  116. enumerable: true,
  117. configurable: true
  118. });
  119. PointerEventTypes._POINTERDOWN = 0x01;
  120. PointerEventTypes._POINTERUP = 0x02;
  121. PointerEventTypes._POINTERMOVE = 0x04;
  122. PointerEventTypes._POINTERWHEEL = 0x08;
  123. PointerEventTypes._POINTERPICK = 0x10;
  124. PointerEventTypes._POINTERTAP = 0x20;
  125. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  126. return PointerEventTypes;
  127. }());
  128. BABYLON.PointerEventTypes = PointerEventTypes;
  129. var PointerInfoBase = (function () {
  130. function PointerInfoBase(type, event) {
  131. this.type = type;
  132. this.event = event;
  133. }
  134. return PointerInfoBase;
  135. }());
  136. BABYLON.PointerInfoBase = PointerInfoBase;
  137. /**
  138. * This class is used to store pointer related info for the onPrePointerObservable event.
  139. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  140. */
  141. var PointerInfoPre = (function (_super) {
  142. __extends(PointerInfoPre, _super);
  143. function PointerInfoPre(type, event, localX, localY) {
  144. var _this = _super.call(this, type, event) || this;
  145. _this.skipOnPointerObservable = false;
  146. _this.localPosition = new BABYLON.Vector2(localX, localY);
  147. return _this;
  148. }
  149. return PointerInfoPre;
  150. }(PointerInfoBase));
  151. BABYLON.PointerInfoPre = PointerInfoPre;
  152. /**
  153. * This type contains all the data related to a pointer event in Babylon.js.
  154. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  155. */
  156. var PointerInfo = (function (_super) {
  157. __extends(PointerInfo, _super);
  158. function PointerInfo(type, event, pickInfo) {
  159. var _this = _super.call(this, type, event) || this;
  160. _this.pickInfo = pickInfo;
  161. return _this;
  162. }
  163. return PointerInfo;
  164. }(PointerInfoBase));
  165. BABYLON.PointerInfo = PointerInfo;
  166. })(BABYLON || (BABYLON = {}));
  167. //# sourceMappingURL=babylon.pointerEvents.js.map
  168. var BABYLON;
  169. (function (BABYLON) {
  170. BABYLON.ToGammaSpace = 1 / 2.2;
  171. BABYLON.ToLinearSpace = 2.2;
  172. BABYLON.Epsilon = 0.001;
  173. var Color3 = (function () {
  174. /**
  175. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  176. */
  177. function Color3(r, g, b) {
  178. if (r === void 0) { r = 0; }
  179. if (g === void 0) { g = 0; }
  180. if (b === void 0) { b = 0; }
  181. this.r = r;
  182. this.g = g;
  183. this.b = b;
  184. }
  185. /**
  186. * Returns a string with the Color3 current values.
  187. */
  188. Color3.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  190. };
  191. /**
  192. * Returns the string "Color3".
  193. */
  194. Color3.prototype.getClassName = function () {
  195. return "Color3";
  196. };
  197. /**
  198. * Returns the Color3 hash code.
  199. */
  200. Color3.prototype.getHashCode = function () {
  201. var hash = this.r || 0;
  202. hash = (hash * 397) ^ (this.g || 0);
  203. hash = (hash * 397) ^ (this.b || 0);
  204. return hash;
  205. };
  206. // Operators
  207. /**
  208. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  209. * Returns the Color3.
  210. */
  211. Color3.prototype.toArray = function (array, index) {
  212. if (index === undefined) {
  213. index = 0;
  214. }
  215. array[index] = this.r;
  216. array[index + 1] = this.g;
  217. array[index + 2] = this.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color4 object from the current Color3 and the passed alpha.
  222. */
  223. Color3.prototype.toColor4 = function (alpha) {
  224. if (alpha === void 0) { alpha = 1; }
  225. return new Color4(this.r, this.g, this.b, alpha);
  226. };
  227. /**
  228. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  229. */
  230. Color3.prototype.asArray = function () {
  231. var result = [];
  232. this.toArray(result, 0);
  233. return result;
  234. };
  235. /**
  236. * Returns the luminance value (float).
  237. */
  238. Color3.prototype.toLuminance = function () {
  239. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  240. };
  241. /**
  242. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  243. * Returns this new object.
  244. */
  245. Color3.prototype.multiply = function (otherColor) {
  246. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  247. };
  248. /**
  249. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  250. * Returns the current Color3.
  251. */
  252. Color3.prototype.multiplyToRef = function (otherColor, result) {
  253. result.r = this.r * otherColor.r;
  254. result.g = this.g * otherColor.g;
  255. result.b = this.b * otherColor.b;
  256. return this;
  257. };
  258. /**
  259. * Boolean : True if the rgb values are equal to the passed ones.
  260. */
  261. Color3.prototype.equals = function (otherColor) {
  262. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  263. };
  264. /**
  265. * Boolean : True if the rgb values are equal to the passed ones.
  266. */
  267. Color3.prototype.equalsFloats = function (r, g, b) {
  268. return this.r === r && this.g === g && this.b === b;
  269. };
  270. /**
  271. * Multiplies in place each rgb value by scale.
  272. * Returns the updated Color3.
  273. */
  274. Color3.prototype.scale = function (scale) {
  275. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  276. };
  277. /**
  278. * Multiplies the rgb values by scale and stores the result into "result".
  279. * Returns the unmodified current Color3.
  280. */
  281. Color3.prototype.scaleToRef = function (scale, result) {
  282. result.r = this.r * scale;
  283. result.g = this.g * scale;
  284. result.b = this.b * scale;
  285. return this;
  286. };
  287. /**
  288. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  289. */
  290. Color3.prototype.add = function (otherColor) {
  291. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  292. };
  293. /**
  294. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  295. * Returns the unmodified current Color3.
  296. */
  297. Color3.prototype.addToRef = function (otherColor, result) {
  298. result.r = this.r + otherColor.r;
  299. result.g = this.g + otherColor.g;
  300. result.b = this.b + otherColor.b;
  301. return this;
  302. };
  303. /**
  304. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  305. */
  306. Color3.prototype.subtract = function (otherColor) {
  307. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  308. };
  309. /**
  310. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  311. * Returns the unmodified current Color3.
  312. */
  313. Color3.prototype.subtractToRef = function (otherColor, result) {
  314. result.r = this.r - otherColor.r;
  315. result.g = this.g - otherColor.g;
  316. result.b = this.b - otherColor.b;
  317. return this;
  318. };
  319. /**
  320. * Returns a new Color3 copied the current one.
  321. */
  322. Color3.prototype.clone = function () {
  323. return new Color3(this.r, this.g, this.b);
  324. };
  325. /**
  326. * Copies the rgb values from the source in the current Color3.
  327. * Returns the updated Color3.
  328. */
  329. Color3.prototype.copyFrom = function (source) {
  330. this.r = source.r;
  331. this.g = source.g;
  332. this.b = source.b;
  333. return this;
  334. };
  335. /**
  336. * Updates the Color3 rgb values from the passed floats.
  337. * Returns the Color3.
  338. */
  339. Color3.prototype.copyFromFloats = function (r, g, b) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. return this;
  344. };
  345. /**
  346. * Updates the Color3 rgb values from the passed floats.
  347. * Returns the Color3.
  348. */
  349. Color3.prototype.set = function (r, g, b) {
  350. return this.copyFromFloats(r, g, b);
  351. };
  352. /**
  353. * Returns the Color3 hexadecimal code as a string.
  354. */
  355. Color3.prototype.toHexString = function () {
  356. var intR = (this.r * 255) | 0;
  357. var intG = (this.g * 255) | 0;
  358. var intB = (this.b * 255) | 0;
  359. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  360. };
  361. /**
  362. * Returns a new Color3 converted to linear space.
  363. */
  364. Color3.prototype.toLinearSpace = function () {
  365. var convertedColor = new Color3();
  366. this.toLinearSpaceToRef(convertedColor);
  367. return convertedColor;
  368. };
  369. /**
  370. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  371. * Returns the unmodified Color3.
  372. */
  373. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  374. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  375. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  376. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color3 converted to gamma space.
  381. */
  382. Color3.prototype.toGammaSpace = function () {
  383. var convertedColor = new Color3();
  384. this.toGammaSpaceToRef(convertedColor);
  385. return convertedColor;
  386. };
  387. /**
  388. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  389. * Returns the unmodified Color3.
  390. */
  391. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  392. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  393. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  394. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  395. return this;
  396. };
  397. // Statics
  398. /**
  399. * Creates a new Color3 from the string containing valid hexadecimal values.
  400. */
  401. Color3.FromHexString = function (hex) {
  402. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  403. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  404. return new Color3(0, 0, 0);
  405. }
  406. var r = parseInt(hex.substring(1, 3), 16);
  407. var g = parseInt(hex.substring(3, 5), 16);
  408. var b = parseInt(hex.substring(5, 7), 16);
  409. return Color3.FromInts(r, g, b);
  410. };
  411. /**
  412. * Creates a new Vector3 from the startind index of the passed array.
  413. */
  414. Color3.FromArray = function (array, offset) {
  415. if (offset === void 0) { offset = 0; }
  416. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  417. };
  418. /**
  419. * Creates a new Color3 from integer values ( < 256).
  420. */
  421. Color3.FromInts = function (r, g, b) {
  422. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  423. };
  424. /**
  425. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  426. */
  427. Color3.Lerp = function (start, end, amount) {
  428. var r = start.r + ((end.r - start.r) * amount);
  429. var g = start.g + ((end.g - start.g) * amount);
  430. var b = start.b + ((end.b - start.b) * amount);
  431. return new Color3(r, g, b);
  432. };
  433. Color3.Red = function () { return new Color3(1, 0, 0); };
  434. Color3.Green = function () { return new Color3(0, 1, 0); };
  435. Color3.Blue = function () { return new Color3(0, 0, 1); };
  436. Color3.Black = function () { return new Color3(0, 0, 0); };
  437. Color3.White = function () { return new Color3(1, 1, 1); };
  438. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  439. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  440. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  441. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  442. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  443. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  444. return Color3;
  445. }());
  446. BABYLON.Color3 = Color3;
  447. var Color4 = (function () {
  448. /**
  449. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  450. */
  451. function Color4(r, g, b, a) {
  452. if (r === void 0) { r = 0; }
  453. if (g === void 0) { g = 0; }
  454. if (b === void 0) { b = 0; }
  455. if (a === void 0) { a = 1; }
  456. this.r = r;
  457. this.g = g;
  458. this.b = b;
  459. this.a = a;
  460. }
  461. // Operators
  462. /**
  463. * Adds in place the passed Color4 values to the current Color4.
  464. * Returns the updated Color4.
  465. */
  466. Color4.prototype.addInPlace = function (right) {
  467. this.r += right.r;
  468. this.g += right.g;
  469. this.b += right.b;
  470. this.a += right.a;
  471. return this;
  472. };
  473. /**
  474. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  475. */
  476. Color4.prototype.asArray = function () {
  477. var result = [];
  478. this.toArray(result, 0);
  479. return result;
  480. };
  481. /**
  482. * Stores from the starting index in the passed array the Color4 successive values.
  483. * Returns the Color4.
  484. */
  485. Color4.prototype.toArray = function (array, index) {
  486. if (index === undefined) {
  487. index = 0;
  488. }
  489. array[index] = this.r;
  490. array[index + 1] = this.g;
  491. array[index + 2] = this.b;
  492. array[index + 3] = this.a;
  493. return this;
  494. };
  495. /**
  496. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  497. */
  498. Color4.prototype.add = function (right) {
  499. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  500. };
  501. /**
  502. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  503. */
  504. Color4.prototype.subtract = function (right) {
  505. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  506. };
  507. /**
  508. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  509. * Returns the Color4.
  510. */
  511. Color4.prototype.subtractToRef = function (right, result) {
  512. result.r = this.r - right.r;
  513. result.g = this.g - right.g;
  514. result.b = this.b - right.b;
  515. result.a = this.a - right.a;
  516. return this;
  517. };
  518. /**
  519. * Creates a new Color4 with the current Color4 values multiplied by scale.
  520. */
  521. Color4.prototype.scale = function (scale) {
  522. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  523. };
  524. /**
  525. * Multiplies the current Color4 values by scale and stores the result in "result".
  526. * Returns the Color4.
  527. */
  528. Color4.prototype.scaleToRef = function (scale, result) {
  529. result.r = this.r * scale;
  530. result.g = this.g * scale;
  531. result.b = this.b * scale;
  532. result.a = this.a * scale;
  533. return this;
  534. };
  535. /**
  536. * Multipy an RGBA Color4 value by another and return a new Color4 object
  537. * @param color The Color4 (RGBA) value to multiply by
  538. * @returns A new Color4.
  539. */
  540. Color4.prototype.multiply = function (color) {
  541. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  542. };
  543. /**
  544. * Multipy an RGBA Color4 value by another and push the result in a reference value
  545. * @param color The Color4 (RGBA) value to multiply by
  546. * @param result The Color4 (RGBA) to fill the result in
  547. * @returns the result Color4.
  548. */
  549. Color4.prototype.multiplyToRef = function (color, result) {
  550. result.r = this.r * color.r;
  551. result.g = this.g * color.g;
  552. result.b = this.b * color.b;
  553. result.a = this.a * color.a;
  554. return result;
  555. };
  556. /**
  557. * Returns a string with the Color4 values.
  558. */
  559. Color4.prototype.toString = function () {
  560. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  561. };
  562. /**
  563. * Returns the string "Color4"
  564. */
  565. Color4.prototype.getClassName = function () {
  566. return "Color4";
  567. };
  568. /**
  569. * Return the Color4 hash code as a number.
  570. */
  571. Color4.prototype.getHashCode = function () {
  572. var hash = this.r || 0;
  573. hash = (hash * 397) ^ (this.g || 0);
  574. hash = (hash * 397) ^ (this.b || 0);
  575. hash = (hash * 397) ^ (this.a || 0);
  576. return hash;
  577. };
  578. /**
  579. * Creates a new Color4 copied from the current one.
  580. */
  581. Color4.prototype.clone = function () {
  582. return new Color4(this.r, this.g, this.b, this.a);
  583. };
  584. /**
  585. * Copies the passed Color4 values into the current one.
  586. * Returns the updated Color4.
  587. */
  588. Color4.prototype.copyFrom = function (source) {
  589. this.r = source.r;
  590. this.g = source.g;
  591. this.b = source.b;
  592. this.a = source.a;
  593. return this;
  594. };
  595. /**
  596. * Copies the passed float values into the current one.
  597. * Returns the updated Color4.
  598. */
  599. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  600. this.r = r;
  601. this.g = g;
  602. this.b = b;
  603. this.a = a;
  604. return this;
  605. };
  606. /**
  607. * Copies the passed float values into the current one.
  608. * Returns the updated Color4.
  609. */
  610. Color4.prototype.set = function (r, g, b, a) {
  611. return this.copyFromFloats(r, g, b, a);
  612. };
  613. /**
  614. * Returns a string containing the hexadecimal Color4 code.
  615. */
  616. Color4.prototype.toHexString = function () {
  617. var intR = (this.r * 255) | 0;
  618. var intG = (this.g * 255) | 0;
  619. var intB = (this.b * 255) | 0;
  620. var intA = (this.a * 255) | 0;
  621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  622. };
  623. /**
  624. * Returns a new Color4 converted to linear space.
  625. */
  626. Color4.prototype.toLinearSpace = function () {
  627. var convertedColor = new Color4();
  628. this.toLinearSpaceToRef(convertedColor);
  629. return convertedColor;
  630. };
  631. /**
  632. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  633. * Returns the unmodified Color4.
  634. */
  635. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  636. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  637. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  638. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  639. convertedColor.a = this.a;
  640. return this;
  641. };
  642. /**
  643. * Returns a new Color4 converted to gamma space.
  644. */
  645. Color4.prototype.toGammaSpace = function () {
  646. var convertedColor = new Color4();
  647. this.toGammaSpaceToRef(convertedColor);
  648. return convertedColor;
  649. };
  650. /**
  651. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  652. * Returns the unmodified Color4.
  653. */
  654. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  655. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  656. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  657. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  658. convertedColor.a = this.a;
  659. return this;
  660. };
  661. // Statics
  662. /**
  663. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  664. */
  665. Color4.FromHexString = function (hex) {
  666. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  667. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  668. return new Color4(0.0, 0.0, 0.0, 0.0);
  669. }
  670. var r = parseInt(hex.substring(1, 3), 16);
  671. var g = parseInt(hex.substring(3, 5), 16);
  672. var b = parseInt(hex.substring(5, 7), 16);
  673. var a = parseInt(hex.substring(7, 9), 16);
  674. return Color4.FromInts(r, g, b, a);
  675. };
  676. /**
  677. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  678. */
  679. Color4.Lerp = function (left, right, amount) {
  680. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  681. Color4.LerpToRef(left, right, amount, result);
  682. return result;
  683. };
  684. /**
  685. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  686. */
  687. Color4.LerpToRef = function (left, right, amount, result) {
  688. result.r = left.r + (right.r - left.r) * amount;
  689. result.g = left.g + (right.g - left.g) * amount;
  690. result.b = left.b + (right.b - left.b) * amount;
  691. result.a = left.a + (right.a - left.a) * amount;
  692. };
  693. /**
  694. * Creates a new Color4 from the starting index element of the passed array.
  695. */
  696. Color4.FromArray = function (array, offset) {
  697. if (offset === void 0) { offset = 0; }
  698. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  699. };
  700. /**
  701. * Creates a new Color4 from the passed integers ( < 256 ).
  702. */
  703. Color4.FromInts = function (r, g, b, a) {
  704. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  705. };
  706. Color4.CheckColors4 = function (colors, count) {
  707. // Check if color3 was used
  708. if (colors.length === count * 3) {
  709. var colors4 = [];
  710. for (var index = 0; index < colors.length; index += 3) {
  711. var newIndex = (index / 3) * 4;
  712. colors4[newIndex] = colors[index];
  713. colors4[newIndex + 1] = colors[index + 1];
  714. colors4[newIndex + 2] = colors[index + 2];
  715. colors4[newIndex + 3] = 1.0;
  716. }
  717. return colors4;
  718. }
  719. return colors;
  720. };
  721. return Color4;
  722. }());
  723. BABYLON.Color4 = Color4;
  724. var Vector2 = (function () {
  725. /**
  726. * Creates a new Vector2 from the passed x and y coordinates.
  727. */
  728. function Vector2(x, y) {
  729. this.x = x;
  730. this.y = y;
  731. }
  732. /**
  733. * Returns a string with the Vector2 coordinates.
  734. */
  735. Vector2.prototype.toString = function () {
  736. return "{X: " + this.x + " Y:" + this.y + "}";
  737. };
  738. /**
  739. * Returns the string "Vector2"
  740. */
  741. Vector2.prototype.getClassName = function () {
  742. return "Vector2";
  743. };
  744. /**
  745. * Returns the Vector2 hash code as a number.
  746. */
  747. Vector2.prototype.getHashCode = function () {
  748. var hash = this.x || 0;
  749. hash = (hash * 397) ^ (this.y || 0);
  750. return hash;
  751. };
  752. // Operators
  753. /**
  754. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  755. * Returns the Vector2.
  756. */
  757. Vector2.prototype.toArray = function (array, index) {
  758. if (index === void 0) { index = 0; }
  759. array[index] = this.x;
  760. array[index + 1] = this.y;
  761. return this;
  762. };
  763. /**
  764. * Returns a new array with 2 elements : the Vector2 coordinates.
  765. */
  766. Vector2.prototype.asArray = function () {
  767. var result = [];
  768. this.toArray(result, 0);
  769. return result;
  770. };
  771. /**
  772. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  773. * Returns the updated Vector2.
  774. */
  775. Vector2.prototype.copyFrom = function (source) {
  776. this.x = source.x;
  777. this.y = source.y;
  778. return this;
  779. };
  780. /**
  781. * Sets the Vector2 coordinates with the passed floats.
  782. * Returns the updated Vector2.
  783. */
  784. Vector2.prototype.copyFromFloats = function (x, y) {
  785. this.x = x;
  786. this.y = y;
  787. return this;
  788. };
  789. /**
  790. * Sets the Vector2 coordinates with the passed floats.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.set = function (x, y) {
  794. return this.copyFromFloats(x, y);
  795. };
  796. /**
  797. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  798. */
  799. Vector2.prototype.add = function (otherVector) {
  800. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  801. };
  802. /**
  803. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  804. * Returns the Vector2.
  805. */
  806. Vector2.prototype.addToRef = function (otherVector, result) {
  807. result.x = this.x + otherVector.x;
  808. result.y = this.y + otherVector.y;
  809. return this;
  810. };
  811. /**
  812. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  813. * Returns the updated Vector2.
  814. */
  815. Vector2.prototype.addInPlace = function (otherVector) {
  816. this.x += otherVector.x;
  817. this.y += otherVector.y;
  818. return this;
  819. };
  820. /**
  821. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  822. */
  823. Vector2.prototype.addVector3 = function (otherVector) {
  824. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  825. };
  826. /**
  827. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  828. */
  829. Vector2.prototype.subtract = function (otherVector) {
  830. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  831. };
  832. /**
  833. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.subtractToRef = function (otherVector, result) {
  837. result.x = this.x - otherVector.x;
  838. result.y = this.y - otherVector.y;
  839. return this;
  840. };
  841. /**
  842. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  843. * Returns the updated Vector2.
  844. */
  845. Vector2.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. return this;
  849. };
  850. /**
  851. * Multiplies in place the current Vector2 coordinates by the passed ones.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.multiplyInPlace = function (otherVector) {
  855. this.x *= otherVector.x;
  856. this.y *= otherVector.y;
  857. return this;
  858. };
  859. /**
  860. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  861. */
  862. Vector2.prototype.multiply = function (otherVector) {
  863. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  864. };
  865. /**
  866. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  867. * Returns the Vector2.
  868. */
  869. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  870. result.x = this.x * otherVector.x;
  871. result.y = this.y * otherVector.y;
  872. return this;
  873. };
  874. /**
  875. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  876. */
  877. Vector2.prototype.multiplyByFloats = function (x, y) {
  878. return new Vector2(this.x * x, this.y * y);
  879. };
  880. /**
  881. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  882. */
  883. Vector2.prototype.divide = function (otherVector) {
  884. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  885. };
  886. /**
  887. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  888. * Returns the Vector2.
  889. */
  890. Vector2.prototype.divideToRef = function (otherVector, result) {
  891. result.x = this.x / otherVector.x;
  892. result.y = this.y / otherVector.y;
  893. return this;
  894. };
  895. /**
  896. * Returns a new Vector2 with current Vector2 negated coordinates.
  897. */
  898. Vector2.prototype.negate = function () {
  899. return new Vector2(-this.x, -this.y);
  900. };
  901. /**
  902. * Multiply the Vector2 coordinates by scale.
  903. * Returns the updated Vector2.
  904. */
  905. Vector2.prototype.scaleInPlace = function (scale) {
  906. this.x *= scale;
  907. this.y *= scale;
  908. return this;
  909. };
  910. /**
  911. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  912. */
  913. Vector2.prototype.scale = function (scale) {
  914. return new Vector2(this.x * scale, this.y * scale);
  915. };
  916. /**
  917. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  918. */
  919. Vector2.prototype.equals = function (otherVector) {
  920. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  921. };
  922. /**
  923. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  924. */
  925. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  928. };
  929. // Properties
  930. /**
  931. * Returns the vector length (float).
  932. */
  933. Vector2.prototype.length = function () {
  934. return Math.sqrt(this.x * this.x + this.y * this.y);
  935. };
  936. /**
  937. * Returns the vector squared length (float);
  938. */
  939. Vector2.prototype.lengthSquared = function () {
  940. return (this.x * this.x + this.y * this.y);
  941. };
  942. // Methods
  943. /**
  944. * Normalize the vector.
  945. * Returns the updated Vector2.
  946. */
  947. Vector2.prototype.normalize = function () {
  948. var len = this.length();
  949. if (len === 0)
  950. return this;
  951. var num = 1.0 / len;
  952. this.x *= num;
  953. this.y *= num;
  954. return this;
  955. };
  956. /**
  957. * Returns a new Vector2 copied from the Vector2.
  958. */
  959. Vector2.prototype.clone = function () {
  960. return new Vector2(this.x, this.y);
  961. };
  962. // Statics
  963. /**
  964. * Returns a new Vector2(0, 0)
  965. */
  966. Vector2.Zero = function () {
  967. return new Vector2(0, 0);
  968. };
  969. /**
  970. * Returns a new Vector2(1, 1)
  971. */
  972. Vector2.One = function () {
  973. return new Vector2(1, 1);
  974. };
  975. /**
  976. * Returns a new Vector2 set from the passed index element of the passed array.
  977. */
  978. Vector2.FromArray = function (array, offset) {
  979. if (offset === void 0) { offset = 0; }
  980. return new Vector2(array[offset], array[offset + 1]);
  981. };
  982. /**
  983. * Sets "result" from the passed index element of the passed array.
  984. */
  985. Vector2.FromArrayToRef = function (array, offset, result) {
  986. result.x = array[offset];
  987. result.y = array[offset + 1];
  988. };
  989. /**
  990. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  991. */
  992. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  993. var squared = amount * amount;
  994. var cubed = amount * squared;
  995. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  996. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  997. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  998. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  999. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1000. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1001. return new Vector2(x, y);
  1002. };
  1003. /**
  1004. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1005. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1006. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1007. */
  1008. Vector2.Clamp = function (value, min, max) {
  1009. var x = value.x;
  1010. x = (x > max.x) ? max.x : x;
  1011. x = (x < min.x) ? min.x : x;
  1012. var y = value.y;
  1013. y = (y > max.y) ? max.y : y;
  1014. y = (y < min.y) ? min.y : y;
  1015. return new Vector2(x, y);
  1016. };
  1017. /**
  1018. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1019. */
  1020. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1021. var squared = amount * amount;
  1022. var cubed = amount * squared;
  1023. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1024. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1025. var part3 = (cubed - (2.0 * squared)) + amount;
  1026. var part4 = cubed - squared;
  1027. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1028. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1029. return new Vector2(x, y);
  1030. };
  1031. /**
  1032. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1033. */
  1034. Vector2.Lerp = function (start, end, amount) {
  1035. var x = start.x + ((end.x - start.x) * amount);
  1036. var y = start.y + ((end.y - start.y) * amount);
  1037. return new Vector2(x, y);
  1038. };
  1039. /**
  1040. * Returns the dot product (float) of the vector "left" and the vector "right".
  1041. */
  1042. Vector2.Dot = function (left, right) {
  1043. return left.x * right.x + left.y * right.y;
  1044. };
  1045. /**
  1046. * Returns a new Vector2 equal to the normalized passed vector.
  1047. */
  1048. Vector2.Normalize = function (vector) {
  1049. var newVector = vector.clone();
  1050. newVector.normalize();
  1051. return newVector;
  1052. };
  1053. /**
  1054. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1055. */
  1056. Vector2.Minimize = function (left, right) {
  1057. var x = (left.x < right.x) ? left.x : right.x;
  1058. var y = (left.y < right.y) ? left.y : right.y;
  1059. return new Vector2(x, y);
  1060. };
  1061. /**
  1062. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1063. */
  1064. Vector2.Maximize = function (left, right) {
  1065. var x = (left.x > right.x) ? left.x : right.x;
  1066. var y = (left.y > right.y) ? left.y : right.y;
  1067. return new Vector2(x, y);
  1068. };
  1069. /**
  1070. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1071. */
  1072. Vector2.Transform = function (vector, transformation) {
  1073. var r = Vector2.Zero();
  1074. Vector2.TransformToRef(vector, transformation, r);
  1075. return r;
  1076. };
  1077. /**
  1078. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1079. */
  1080. Vector2.TransformToRef = function (vector, transformation, result) {
  1081. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1082. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1083. result.x = x;
  1084. result.y = y;
  1085. };
  1086. /**
  1087. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1088. */
  1089. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1090. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1091. var sign = a < 0 ? -1 : 1;
  1092. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1093. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1094. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1095. };
  1096. /**
  1097. * Returns the distance (float) between the vectors "value1" and "value2".
  1098. */
  1099. Vector2.Distance = function (value1, value2) {
  1100. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1101. };
  1102. /**
  1103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1104. */
  1105. Vector2.DistanceSquared = function (value1, value2) {
  1106. var x = value1.x - value2.x;
  1107. var y = value1.y - value2.y;
  1108. return (x * x) + (y * y);
  1109. };
  1110. /**
  1111. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1112. */
  1113. Vector2.Center = function (value1, value2) {
  1114. var center = value1.add(value2);
  1115. center.scaleInPlace(0.5);
  1116. return center;
  1117. };
  1118. /**
  1119. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1120. */
  1121. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1122. var l2 = Vector2.DistanceSquared(segA, segB);
  1123. if (l2 === 0.0) {
  1124. return Vector2.Distance(p, segA);
  1125. }
  1126. var v = segB.subtract(segA);
  1127. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1128. var proj = segA.add(v.multiplyByFloats(t, t));
  1129. return Vector2.Distance(p, proj);
  1130. };
  1131. return Vector2;
  1132. }());
  1133. BABYLON.Vector2 = Vector2;
  1134. var Vector3 = (function () {
  1135. /**
  1136. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1137. * A Vector3 is the main object used in 3D geometry.
  1138. * It can represent etiher the coordinates of a point the space, either a direction.
  1139. */
  1140. function Vector3(x, y, z) {
  1141. this.x = x;
  1142. this.y = y;
  1143. this.z = z;
  1144. }
  1145. /**
  1146. * Returns a string with the Vector3 coordinates.
  1147. */
  1148. Vector3.prototype.toString = function () {
  1149. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1150. };
  1151. /**
  1152. * Returns the string "Vector3"
  1153. */
  1154. Vector3.prototype.getClassName = function () {
  1155. return "Vector3";
  1156. };
  1157. /**
  1158. * Returns the Vector hash code.
  1159. */
  1160. Vector3.prototype.getHashCode = function () {
  1161. var hash = this.x || 0;
  1162. hash = (hash * 397) ^ (this.y || 0);
  1163. hash = (hash * 397) ^ (this.z || 0);
  1164. return hash;
  1165. };
  1166. // Operators
  1167. /**
  1168. * Returns a new array with three elements : the coordinates the Vector3.
  1169. */
  1170. Vector3.prototype.asArray = function () {
  1171. var result = [];
  1172. this.toArray(result, 0);
  1173. return result;
  1174. };
  1175. /**
  1176. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1177. * Returns the Vector3.
  1178. */
  1179. Vector3.prototype.toArray = function (array, index) {
  1180. if (index === void 0) { index = 0; }
  1181. array[index] = this.x;
  1182. array[index + 1] = this.y;
  1183. array[index + 2] = this.z;
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1188. */
  1189. Vector3.prototype.toQuaternion = function () {
  1190. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1191. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1192. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1193. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1194. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1195. var cosy = Math.cos(this.y * 0.5);
  1196. var siny = Math.sin(this.y * 0.5);
  1197. result.x = coszMinusx * siny;
  1198. result.y = -sinzMinusx * siny;
  1199. result.z = sinxPlusz * cosy;
  1200. result.w = cosxPlusz * cosy;
  1201. return result;
  1202. };
  1203. /**
  1204. * Adds the passed vector to the current Vector3.
  1205. * Returns the updated Vector3.
  1206. */
  1207. Vector3.prototype.addInPlace = function (otherVector) {
  1208. this.x += otherVector.x;
  1209. this.y += otherVector.y;
  1210. this.z += otherVector.z;
  1211. return this;
  1212. };
  1213. /**
  1214. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1215. */
  1216. Vector3.prototype.add = function (otherVector) {
  1217. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1218. };
  1219. /**
  1220. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1221. * Returns the current Vector3.
  1222. */
  1223. Vector3.prototype.addToRef = function (otherVector, result) {
  1224. result.x = this.x + otherVector.x;
  1225. result.y = this.y + otherVector.y;
  1226. result.z = this.z + otherVector.z;
  1227. return this;
  1228. };
  1229. /**
  1230. * Subtract the passed vector from the current Vector3.
  1231. * Returns the updated Vector3.
  1232. */
  1233. Vector3.prototype.subtractInPlace = function (otherVector) {
  1234. this.x -= otherVector.x;
  1235. this.y -= otherVector.y;
  1236. this.z -= otherVector.z;
  1237. return this;
  1238. };
  1239. /**
  1240. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1241. */
  1242. Vector3.prototype.subtract = function (otherVector) {
  1243. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1244. };
  1245. /**
  1246. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1247. * Returns the current Vector3.
  1248. */
  1249. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1250. result.x = this.x - otherVector.x;
  1251. result.y = this.y - otherVector.y;
  1252. result.z = this.z - otherVector.z;
  1253. return this;
  1254. };
  1255. /**
  1256. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1257. */
  1258. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1259. return new Vector3(this.x - x, this.y - y, this.z - z);
  1260. };
  1261. /**
  1262. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1263. * Returns the current Vector3.
  1264. */
  1265. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1266. result.x = this.x - x;
  1267. result.y = this.y - y;
  1268. result.z = this.z - z;
  1269. return this;
  1270. };
  1271. /**
  1272. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1273. */
  1274. Vector3.prototype.negate = function () {
  1275. return new Vector3(-this.x, -this.y, -this.z);
  1276. };
  1277. /**
  1278. * Multiplies the Vector3 coordinates by the float "scale".
  1279. * Returns the updated Vector3.
  1280. */
  1281. Vector3.prototype.scaleInPlace = function (scale) {
  1282. this.x *= scale;
  1283. this.y *= scale;
  1284. this.z *= scale;
  1285. return this;
  1286. };
  1287. /**
  1288. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1289. */
  1290. Vector3.prototype.scale = function (scale) {
  1291. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1292. };
  1293. /**
  1294. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1295. * Returns the current Vector3.
  1296. */
  1297. Vector3.prototype.scaleToRef = function (scale, result) {
  1298. result.x = this.x * scale;
  1299. result.y = this.y * scale;
  1300. result.z = this.z * scale;
  1301. return this;
  1302. };
  1303. /**
  1304. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1305. */
  1306. Vector3.prototype.equals = function (otherVector) {
  1307. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1308. };
  1309. /**
  1310. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1311. */
  1312. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1313. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1314. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1315. };
  1316. /**
  1317. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1318. */
  1319. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1320. return this.x === x && this.y === y && this.z === z;
  1321. };
  1322. /**
  1323. * Muliplies the current Vector3 coordinates by the passed ones.
  1324. * Returns the updated Vector3.
  1325. */
  1326. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1327. this.x *= otherVector.x;
  1328. this.y *= otherVector.y;
  1329. this.z *= otherVector.z;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1334. */
  1335. Vector3.prototype.multiply = function (otherVector) {
  1336. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1337. };
  1338. /**
  1339. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1340. * Returns the current Vector3.
  1341. */
  1342. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1343. result.x = this.x * otherVector.x;
  1344. result.y = this.y * otherVector.y;
  1345. result.z = this.z * otherVector.z;
  1346. return this;
  1347. };
  1348. /**
  1349. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1350. */
  1351. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1352. return new Vector3(this.x * x, this.y * y, this.z * z);
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1356. */
  1357. Vector3.prototype.divide = function (otherVector) {
  1358. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1359. };
  1360. /**
  1361. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1362. * Returns the current Vector3.
  1363. */
  1364. Vector3.prototype.divideToRef = function (otherVector, result) {
  1365. result.x = this.x / otherVector.x;
  1366. result.y = this.y / otherVector.y;
  1367. result.z = this.z / otherVector.z;
  1368. return this;
  1369. };
  1370. /**
  1371. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1372. * Returns the updated Vector3.
  1373. */
  1374. Vector3.prototype.MinimizeInPlace = function (other) {
  1375. if (other.x < this.x)
  1376. this.x = other.x;
  1377. if (other.y < this.y)
  1378. this.y = other.y;
  1379. if (other.z < this.z)
  1380. this.z = other.z;
  1381. return this;
  1382. };
  1383. /**
  1384. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1385. * Returns the updated Vector3.
  1386. */
  1387. Vector3.prototype.MaximizeInPlace = function (other) {
  1388. if (other.x > this.x)
  1389. this.x = other.x;
  1390. if (other.y > this.y)
  1391. this.y = other.y;
  1392. if (other.z > this.z)
  1393. this.z = other.z;
  1394. return this;
  1395. };
  1396. // Properties
  1397. /**
  1398. * Returns the length of the Vector3 (float).
  1399. */
  1400. Vector3.prototype.length = function () {
  1401. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1402. };
  1403. /**
  1404. * Returns the squared length of the Vector3 (float).
  1405. */
  1406. Vector3.prototype.lengthSquared = function () {
  1407. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1408. };
  1409. // Methods
  1410. /**
  1411. * Normalize the current Vector3.
  1412. * Returns the updated Vector3.
  1413. */
  1414. Vector3.prototype.normalize = function () {
  1415. var len = this.length();
  1416. if (len === 0 || len === 1.0)
  1417. return this;
  1418. var num = 1.0 / len;
  1419. this.x *= num;
  1420. this.y *= num;
  1421. this.z *= num;
  1422. return this;
  1423. };
  1424. /**
  1425. * Returns a new Vector3 copied from the current Vector3.
  1426. */
  1427. Vector3.prototype.clone = function () {
  1428. return new Vector3(this.x, this.y, this.z);
  1429. };
  1430. /**
  1431. * Copies the passed vector coordinates to the current Vector3 ones.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.copyFrom = function (source) {
  1435. this.x = source.x;
  1436. this.y = source.y;
  1437. this.z = source.z;
  1438. return this;
  1439. };
  1440. /**
  1441. * Copies the passed floats to the current Vector3 coordinates.
  1442. * Returns the updated Vector3.
  1443. */
  1444. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1445. this.x = x;
  1446. this.y = y;
  1447. this.z = z;
  1448. return this;
  1449. };
  1450. /**
  1451. * Copies the passed floats to the current Vector3 coordinates.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.set = function (x, y, z) {
  1455. return this.copyFromFloats(x, y, z);
  1456. };
  1457. // Statics
  1458. /**
  1459. *
  1460. */
  1461. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1462. var d0 = Vector3.Dot(vector0, axis) - size;
  1463. var d1 = Vector3.Dot(vector1, axis) - size;
  1464. var s = d0 / (d0 - d1);
  1465. return s;
  1466. };
  1467. /**
  1468. * Returns a new Vector3 set from the index "offset" of the passed array.
  1469. */
  1470. Vector3.FromArray = function (array, offset) {
  1471. if (!offset) {
  1472. offset = 0;
  1473. }
  1474. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1475. };
  1476. /**
  1477. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1478. * This function is deprecated. Use FromArray instead.
  1479. */
  1480. Vector3.FromFloatArray = function (array, offset) {
  1481. return Vector3.FromArray(array, offset);
  1482. };
  1483. /**
  1484. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1485. */
  1486. Vector3.FromArrayToRef = function (array, offset, result) {
  1487. result.x = array[offset];
  1488. result.y = array[offset + 1];
  1489. result.z = array[offset + 2];
  1490. };
  1491. /**
  1492. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1493. * This function is deprecated. Use FromArrayToRef instead.
  1494. */
  1495. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1496. return Vector3.FromArrayToRef(array, offset, result);
  1497. };
  1498. /**
  1499. * Sets the passed vector "result" with the passed floats.
  1500. */
  1501. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1502. result.x = x;
  1503. result.y = y;
  1504. result.z = z;
  1505. };
  1506. /**
  1507. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1508. */
  1509. Vector3.Zero = function () {
  1510. return new Vector3(0.0, 0.0, 0.0);
  1511. };
  1512. /**
  1513. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1514. */
  1515. Vector3.One = function () {
  1516. return new Vector3(1.0, 1.0, 1.0);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1520. */
  1521. Vector3.Up = function () {
  1522. return new Vector3(0.0, 1.0, 0.0);
  1523. };
  1524. /**
  1525. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1526. */
  1527. Vector3.Forward = function () {
  1528. return new Vector3(0.0, 0.0, 1.0);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1532. */
  1533. Vector3.Right = function () {
  1534. return new Vector3(1.0, 0.0, 0.0);
  1535. };
  1536. /**
  1537. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1538. */
  1539. Vector3.Left = function () {
  1540. return new Vector3(-1.0, 0.0, 0.0);
  1541. };
  1542. /**
  1543. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1544. * This method computes tranformed coordinates only, not transformed direction vectors.
  1545. */
  1546. Vector3.TransformCoordinates = function (vector, transformation) {
  1547. var result = Vector3.Zero();
  1548. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1549. return result;
  1550. };
  1551. /**
  1552. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1553. * This method computes tranformed coordinates only, not transformed direction vectors.
  1554. */
  1555. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1558. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1559. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1560. result.x = x / w;
  1561. result.y = y / w;
  1562. result.z = z / w;
  1563. };
  1564. /**
  1565. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1566. * This method computes tranformed coordinates only, not transformed direction vectors.
  1567. */
  1568. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1569. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1570. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1571. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1572. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1573. result.x = rx / rw;
  1574. result.y = ry / rw;
  1575. result.z = rz / rw;
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1579. * This methods computes transformed normalized direction vectors only.
  1580. */
  1581. Vector3.TransformNormal = function (vector, transformation) {
  1582. var result = Vector3.Zero();
  1583. Vector3.TransformNormalToRef(vector, transformation, result);
  1584. return result;
  1585. };
  1586. /**
  1587. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1588. * This methods computes transformed normalized direction vectors only.
  1589. */
  1590. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1591. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1592. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1593. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1594. result.x = x;
  1595. result.y = y;
  1596. result.z = z;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1600. * This methods computes transformed normalized direction vectors only.
  1601. */
  1602. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1603. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1604. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1605. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1606. };
  1607. /**
  1608. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1609. */
  1610. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1611. var squared = amount * amount;
  1612. var cubed = amount * squared;
  1613. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1614. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1615. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1616. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1617. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1618. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1619. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1620. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1621. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1622. return new Vector3(x, y, z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1626. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1627. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1628. */
  1629. Vector3.Clamp = function (value, min, max) {
  1630. var x = value.x;
  1631. x = (x > max.x) ? max.x : x;
  1632. x = (x < min.x) ? min.x : x;
  1633. var y = value.y;
  1634. y = (y > max.y) ? max.y : y;
  1635. y = (y < min.y) ? min.y : y;
  1636. var z = value.z;
  1637. z = (z > max.z) ? max.z : z;
  1638. z = (z < min.z) ? min.z : z;
  1639. return new Vector3(x, y, z);
  1640. };
  1641. /**
  1642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1643. */
  1644. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1645. var squared = amount * amount;
  1646. var cubed = amount * squared;
  1647. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1648. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1649. var part3 = (cubed - (2.0 * squared)) + amount;
  1650. var part4 = cubed - squared;
  1651. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1652. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1653. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1654. return new Vector3(x, y, z);
  1655. };
  1656. /**
  1657. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1658. */
  1659. Vector3.Lerp = function (start, end, amount) {
  1660. var result = new Vector3(0, 0, 0);
  1661. Vector3.LerpToRef(start, end, amount, result);
  1662. return result;
  1663. };
  1664. /**
  1665. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1666. */
  1667. Vector3.LerpToRef = function (start, end, amount, result) {
  1668. result.x = start.x + ((end.x - start.x) * amount);
  1669. result.y = start.y + ((end.y - start.y) * amount);
  1670. result.z = start.z + ((end.z - start.z) * amount);
  1671. };
  1672. /**
  1673. * Returns the dot product (float) between the vectors "left" and "right".
  1674. */
  1675. Vector3.Dot = function (left, right) {
  1676. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1677. };
  1678. /**
  1679. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1680. * The cross product is then orthogonal to both "left" and "right".
  1681. */
  1682. Vector3.Cross = function (left, right) {
  1683. var result = Vector3.Zero();
  1684. Vector3.CrossToRef(left, right, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the cross product of "left" and "right".
  1689. * The cross product is then orthogonal to both "left" and "right".
  1690. */
  1691. Vector3.CrossToRef = function (left, right, result) {
  1692. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1693. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1694. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1695. result.copyFrom(MathTmp.Vector3[0]);
  1696. };
  1697. /**
  1698. * Returns a new Vector3 as the normalization of the passed vector.
  1699. */
  1700. Vector3.Normalize = function (vector) {
  1701. var result = Vector3.Zero();
  1702. Vector3.NormalizeToRef(vector, result);
  1703. return result;
  1704. };
  1705. /**
  1706. * Sets the passed vector "result" with the normalization of the passed first vector.
  1707. */
  1708. Vector3.NormalizeToRef = function (vector, result) {
  1709. result.copyFrom(vector);
  1710. result.normalize();
  1711. };
  1712. Vector3.Project = function (vector, world, transform, viewport) {
  1713. var cw = viewport.width;
  1714. var ch = viewport.height;
  1715. var cx = viewport.x;
  1716. var cy = viewport.y;
  1717. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1718. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1719. var matrix = MathTmp.Matrix[0];
  1720. world.multiplyToRef(transform, matrix);
  1721. matrix.multiplyToRef(viewportMatrix, matrix);
  1722. return Vector3.TransformCoordinates(vector, matrix);
  1723. };
  1724. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1725. var matrix = MathTmp.Matrix[0];
  1726. world.multiplyToRef(transform, matrix);
  1727. matrix.invert();
  1728. source.x = source.x / viewportWidth * 2 - 1;
  1729. source.y = -(source.y / viewportHeight * 2 - 1);
  1730. var vector = Vector3.TransformCoordinates(source, matrix);
  1731. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1732. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1733. vector = vector.scale(1.0 / num);
  1734. }
  1735. return vector;
  1736. };
  1737. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1738. var matrix = MathTmp.Matrix[0];
  1739. world.multiplyToRef(view, matrix);
  1740. matrix.multiplyToRef(projection, matrix);
  1741. matrix.invert();
  1742. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1743. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1744. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1745. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1746. vector = vector.scale(1.0 / num);
  1747. }
  1748. return vector;
  1749. };
  1750. Vector3.Minimize = function (left, right) {
  1751. var min = left.clone();
  1752. min.MinimizeInPlace(right);
  1753. return min;
  1754. };
  1755. Vector3.Maximize = function (left, right) {
  1756. var max = left.clone();
  1757. max.MaximizeInPlace(right);
  1758. return max;
  1759. };
  1760. /**
  1761. * Returns the distance (float) between the vectors "value1" and "value2".
  1762. */
  1763. Vector3.Distance = function (value1, value2) {
  1764. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1765. };
  1766. /**
  1767. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1768. */
  1769. Vector3.DistanceSquared = function (value1, value2) {
  1770. var x = value1.x - value2.x;
  1771. var y = value1.y - value2.y;
  1772. var z = value1.z - value2.z;
  1773. return (x * x) + (y * y) + (z * z);
  1774. };
  1775. /**
  1776. * Returns a new Vector3 located at the center between "value1" and "value2".
  1777. */
  1778. Vector3.Center = function (value1, value2) {
  1779. var center = value1.add(value2);
  1780. center.scaleInPlace(0.5);
  1781. return center;
  1782. };
  1783. /**
  1784. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1785. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1786. * to something in order to rotate it from its local system to the given target system.
  1787. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1788. * Returns a new Vector3.
  1789. */
  1790. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1791. var rotation = Vector3.Zero();
  1792. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1793. return rotation;
  1794. };
  1795. /**
  1796. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1797. */
  1798. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1799. var quat = MathTmp.Quaternion[0];
  1800. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1801. quat.toEulerAnglesToRef(ref);
  1802. };
  1803. return Vector3;
  1804. }());
  1805. BABYLON.Vector3 = Vector3;
  1806. //Vector4 class created for EulerAngle class conversion to Quaternion
  1807. var Vector4 = (function () {
  1808. /**
  1809. * Creates a Vector4 object from the passed floats.
  1810. */
  1811. function Vector4(x, y, z, w) {
  1812. this.x = x;
  1813. this.y = y;
  1814. this.z = z;
  1815. this.w = w;
  1816. }
  1817. /**
  1818. * Returns the string with the Vector4 coordinates.
  1819. */
  1820. Vector4.prototype.toString = function () {
  1821. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1822. };
  1823. /**
  1824. * Returns the string "Vector4".
  1825. */
  1826. Vector4.prototype.getClassName = function () {
  1827. return "Vector4";
  1828. };
  1829. /**
  1830. * Returns the Vector4 hash code.
  1831. */
  1832. Vector4.prototype.getHashCode = function () {
  1833. var hash = this.x || 0;
  1834. hash = (hash * 397) ^ (this.y || 0);
  1835. hash = (hash * 397) ^ (this.z || 0);
  1836. hash = (hash * 397) ^ (this.w || 0);
  1837. return hash;
  1838. };
  1839. // Operators
  1840. /**
  1841. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.asArray = function () {
  1844. var result = [];
  1845. this.toArray(result, 0);
  1846. return result;
  1847. };
  1848. /**
  1849. * Populates the passed array from the passed index with the Vector4 coordinates.
  1850. * Returns the Vector4.
  1851. */
  1852. Vector4.prototype.toArray = function (array, index) {
  1853. if (index === undefined) {
  1854. index = 0;
  1855. }
  1856. array[index] = this.x;
  1857. array[index + 1] = this.y;
  1858. array[index + 2] = this.z;
  1859. array[index + 3] = this.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Adds the passed vector to the current Vector4.
  1864. * Returns the updated Vector4.
  1865. */
  1866. Vector4.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. this.z += otherVector.z;
  1870. this.w += otherVector.w;
  1871. return this;
  1872. };
  1873. /**
  1874. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1875. */
  1876. Vector4.prototype.add = function (otherVector) {
  1877. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1878. };
  1879. /**
  1880. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1881. * Returns the current Vector4.
  1882. */
  1883. Vector4.prototype.addToRef = function (otherVector, result) {
  1884. result.x = this.x + otherVector.x;
  1885. result.y = this.y + otherVector.y;
  1886. result.z = this.z + otherVector.z;
  1887. result.w = this.w + otherVector.w;
  1888. return this;
  1889. };
  1890. /**
  1891. * Subtract in place the passed vector from the current Vector4.
  1892. * Returns the updated Vector4.
  1893. */
  1894. Vector4.prototype.subtractInPlace = function (otherVector) {
  1895. this.x -= otherVector.x;
  1896. this.y -= otherVector.y;
  1897. this.z -= otherVector.z;
  1898. this.w -= otherVector.w;
  1899. return this;
  1900. };
  1901. /**
  1902. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1903. */
  1904. Vector4.prototype.subtract = function (otherVector) {
  1905. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1906. };
  1907. /**
  1908. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1909. * Returns the current Vector4.
  1910. */
  1911. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1912. result.x = this.x - otherVector.x;
  1913. result.y = this.y - otherVector.y;
  1914. result.z = this.z - otherVector.z;
  1915. result.w = this.w - otherVector.w;
  1916. return this;
  1917. };
  1918. /**
  1919. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1922. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1923. };
  1924. /**
  1925. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1926. * Returns the current Vector4.
  1927. */
  1928. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1929. result.x = this.x - x;
  1930. result.y = this.y - y;
  1931. result.z = this.z - z;
  1932. result.w = this.w - w;
  1933. return this;
  1934. };
  1935. /**
  1936. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1937. */
  1938. Vector4.prototype.negate = function () {
  1939. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1940. };
  1941. /**
  1942. * Multiplies the current Vector4 coordinates by scale (float).
  1943. * Returns the updated Vector4.
  1944. */
  1945. Vector4.prototype.scaleInPlace = function (scale) {
  1946. this.x *= scale;
  1947. this.y *= scale;
  1948. this.z *= scale;
  1949. this.w *= scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1954. */
  1955. Vector4.prototype.scale = function (scale) {
  1956. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1957. };
  1958. /**
  1959. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1960. * Returns the current Vector4.
  1961. */
  1962. Vector4.prototype.scaleToRef = function (scale, result) {
  1963. result.x = this.x * scale;
  1964. result.y = this.y * scale;
  1965. result.z = this.z * scale;
  1966. result.w = this.w * scale;
  1967. return this;
  1968. };
  1969. /**
  1970. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1971. */
  1972. Vector4.prototype.equals = function (otherVector) {
  1973. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1974. };
  1975. /**
  1976. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1977. */
  1978. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1979. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1980. return otherVector
  1981. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1982. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1983. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1984. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1985. };
  1986. /**
  1987. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1988. */
  1989. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1990. return this.x === x && this.y === y && this.z === z && this.w === w;
  1991. };
  1992. /**
  1993. * Multiplies in place the current Vector4 by the passed one.
  1994. * Returns the updated Vector4.
  1995. */
  1996. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1997. this.x *= otherVector.x;
  1998. this.y *= otherVector.y;
  1999. this.z *= otherVector.z;
  2000. this.w *= otherVector.w;
  2001. return this;
  2002. };
  2003. /**
  2004. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2005. */
  2006. Vector4.prototype.multiply = function (otherVector) {
  2007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2011. * Returns the current Vector4.
  2012. */
  2013. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2014. result.x = this.x * otherVector.x;
  2015. result.y = this.y * otherVector.y;
  2016. result.z = this.z * otherVector.z;
  2017. result.w = this.w * otherVector.w;
  2018. return this;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2022. */
  2023. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2024. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2028. */
  2029. Vector4.prototype.divide = function (otherVector) {
  2030. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.divideToRef = function (otherVector, result) {
  2037. result.x = this.x / otherVector.x;
  2038. result.y = this.y / otherVector.y;
  2039. result.z = this.z / otherVector.z;
  2040. result.w = this.w / otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2045. */
  2046. Vector4.prototype.MinimizeInPlace = function (other) {
  2047. if (other.x < this.x)
  2048. this.x = other.x;
  2049. if (other.y < this.y)
  2050. this.y = other.y;
  2051. if (other.z < this.z)
  2052. this.z = other.z;
  2053. if (other.w < this.w)
  2054. this.w = other.w;
  2055. return this;
  2056. };
  2057. /**
  2058. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2059. */
  2060. Vector4.prototype.MaximizeInPlace = function (other) {
  2061. if (other.x > this.x)
  2062. this.x = other.x;
  2063. if (other.y > this.y)
  2064. this.y = other.y;
  2065. if (other.z > this.z)
  2066. this.z = other.z;
  2067. if (other.w > this.w)
  2068. this.w = other.w;
  2069. return this;
  2070. };
  2071. // Properties
  2072. /**
  2073. * Returns the Vector4 length (float).
  2074. */
  2075. Vector4.prototype.length = function () {
  2076. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2077. };
  2078. /**
  2079. * Returns the Vector4 squared length (float).
  2080. */
  2081. Vector4.prototype.lengthSquared = function () {
  2082. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2083. };
  2084. // Methods
  2085. /**
  2086. * Normalizes in place the Vector4.
  2087. * Returns the updated Vector4.
  2088. */
  2089. Vector4.prototype.normalize = function () {
  2090. var len = this.length();
  2091. if (len === 0)
  2092. return this;
  2093. var num = 1.0 / len;
  2094. this.x *= num;
  2095. this.y *= num;
  2096. this.z *= num;
  2097. this.w *= num;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2102. */
  2103. Vector4.prototype.toVector3 = function () {
  2104. return new Vector3(this.x, this.y, this.z);
  2105. };
  2106. /**
  2107. * Returns a new Vector4 copied from the current one.
  2108. */
  2109. Vector4.prototype.clone = function () {
  2110. return new Vector4(this.x, this.y, this.z, this.w);
  2111. };
  2112. /**
  2113. * Updates the current Vector4 with the passed one coordinates.
  2114. * Returns the updated Vector4.
  2115. */
  2116. Vector4.prototype.copyFrom = function (source) {
  2117. this.x = source.x;
  2118. this.y = source.y;
  2119. this.z = source.z;
  2120. this.w = source.w;
  2121. return this;
  2122. };
  2123. /**
  2124. * Updates the current Vector4 coordinates with the passed floats.
  2125. * Returns the updated Vector4.
  2126. */
  2127. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2128. this.x = x;
  2129. this.y = y;
  2130. this.z = z;
  2131. this.w = w;
  2132. return this;
  2133. };
  2134. /**
  2135. * Updates the current Vector4 coordinates with the passed floats.
  2136. * Returns the updated Vector4.
  2137. */
  2138. Vector4.prototype.set = function (x, y, z, w) {
  2139. return this.copyFromFloats(x, y, z, w);
  2140. };
  2141. // Statics
  2142. /**
  2143. * Returns a new Vector4 set from the starting index of the passed array.
  2144. */
  2145. Vector4.FromArray = function (array, offset) {
  2146. if (!offset) {
  2147. offset = 0;
  2148. }
  2149. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2150. };
  2151. /**
  2152. * Updates the passed vector "result" from the starting index of the passed array.
  2153. */
  2154. Vector4.FromArrayToRef = function (array, offset, result) {
  2155. result.x = array[offset];
  2156. result.y = array[offset + 1];
  2157. result.z = array[offset + 2];
  2158. result.w = array[offset + 3];
  2159. };
  2160. /**
  2161. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2162. */
  2163. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2164. Vector4.FromArrayToRef(array, offset, result);
  2165. };
  2166. /**
  2167. * Updates the passed vector "result" coordinates from the passed floats.
  2168. */
  2169. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2170. result.x = x;
  2171. result.y = y;
  2172. result.z = z;
  2173. result.w = w;
  2174. };
  2175. /**
  2176. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2177. */
  2178. Vector4.Zero = function () {
  2179. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2180. };
  2181. /**
  2182. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2183. */
  2184. Vector4.One = function () {
  2185. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2186. };
  2187. /**
  2188. * Returns a new normalized Vector4 from the passed one.
  2189. */
  2190. Vector4.Normalize = function (vector) {
  2191. var result = Vector4.Zero();
  2192. Vector4.NormalizeToRef(vector, result);
  2193. return result;
  2194. };
  2195. /**
  2196. * Updates the passed vector "result" from the normalization of the passed one.
  2197. */
  2198. Vector4.NormalizeToRef = function (vector, result) {
  2199. result.copyFrom(vector);
  2200. result.normalize();
  2201. };
  2202. Vector4.Minimize = function (left, right) {
  2203. var min = left.clone();
  2204. min.MinimizeInPlace(right);
  2205. return min;
  2206. };
  2207. Vector4.Maximize = function (left, right) {
  2208. var max = left.clone();
  2209. max.MaximizeInPlace(right);
  2210. return max;
  2211. };
  2212. /**
  2213. * Returns the distance (float) between the vectors "value1" and "value2".
  2214. */
  2215. Vector4.Distance = function (value1, value2) {
  2216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2217. };
  2218. /**
  2219. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2220. */
  2221. Vector4.DistanceSquared = function (value1, value2) {
  2222. var x = value1.x - value2.x;
  2223. var y = value1.y - value2.y;
  2224. var z = value1.z - value2.z;
  2225. var w = value1.w - value2.w;
  2226. return (x * x) + (y * y) + (z * z) + (w * w);
  2227. };
  2228. /**
  2229. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2230. */
  2231. Vector4.Center = function (value1, value2) {
  2232. var center = value1.add(value2);
  2233. center.scaleInPlace(0.5);
  2234. return center;
  2235. };
  2236. /**
  2237. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2238. * This methods computes transformed normalized direction vectors only.
  2239. */
  2240. Vector4.TransformNormal = function (vector, transformation) {
  2241. var result = Vector4.Zero();
  2242. Vector4.TransformNormalToRef(vector, transformation, result);
  2243. return result;
  2244. };
  2245. /**
  2246. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2247. * This methods computes transformed normalized direction vectors only.
  2248. */
  2249. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2250. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2251. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2252. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2253. result.x = x;
  2254. result.y = y;
  2255. result.z = z;
  2256. result.w = vector.w;
  2257. };
  2258. /**
  2259. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2260. * This methods computes transformed normalized direction vectors only.
  2261. */
  2262. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2263. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2264. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2265. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2266. result.w = w;
  2267. };
  2268. return Vector4;
  2269. }());
  2270. BABYLON.Vector4 = Vector4;
  2271. var Size = (function () {
  2272. /**
  2273. * Creates a Size object from the passed width and height (floats).
  2274. */
  2275. function Size(width, height) {
  2276. this.width = width;
  2277. this.height = height;
  2278. }
  2279. // Returns a string with the Size width and height.
  2280. Size.prototype.toString = function () {
  2281. return "{W: " + this.width + ", H: " + this.height + "}";
  2282. };
  2283. /**
  2284. * Returns the string "Size"
  2285. */
  2286. Size.prototype.getClassName = function () {
  2287. return "Size";
  2288. };
  2289. /**
  2290. * Returns the Size hash code.
  2291. */
  2292. Size.prototype.getHashCode = function () {
  2293. var hash = this.width || 0;
  2294. hash = (hash * 397) ^ (this.height || 0);
  2295. return hash;
  2296. };
  2297. /**
  2298. * Updates the current size from the passed one.
  2299. * Returns the updated Size.
  2300. */
  2301. Size.prototype.copyFrom = function (src) {
  2302. this.width = src.width;
  2303. this.height = src.height;
  2304. };
  2305. /**
  2306. * Updates in place the current Size from the passed floats.
  2307. * Returns the updated Size.
  2308. */
  2309. Size.prototype.copyFromFloats = function (width, height) {
  2310. this.width = width;
  2311. this.height = height;
  2312. return this;
  2313. };
  2314. /**
  2315. * Updates in place the current Size from the passed floats.
  2316. * Returns the updated Size.
  2317. */
  2318. Size.prototype.set = function (width, height) {
  2319. return this.copyFromFloats(width, height);
  2320. };
  2321. /**
  2322. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2323. */
  2324. Size.prototype.multiplyByFloats = function (w, h) {
  2325. return new Size(this.width * w, this.height * h);
  2326. };
  2327. /**
  2328. * Returns a new Size copied from the passed one.
  2329. */
  2330. Size.prototype.clone = function () {
  2331. return new Size(this.width, this.height);
  2332. };
  2333. /**
  2334. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2335. */
  2336. Size.prototype.equals = function (other) {
  2337. if (!other) {
  2338. return false;
  2339. }
  2340. return (this.width === other.width) && (this.height === other.height);
  2341. };
  2342. Object.defineProperty(Size.prototype, "surface", {
  2343. /**
  2344. * Returns the surface of the Size : width * height (float).
  2345. */
  2346. get: function () {
  2347. return this.width * this.height;
  2348. },
  2349. enumerable: true,
  2350. configurable: true
  2351. });
  2352. /**
  2353. * Returns a new Size set to (0.0, 0.0)
  2354. */
  2355. Size.Zero = function () {
  2356. return new Size(0.0, 0.0);
  2357. };
  2358. /**
  2359. * Returns a new Size set as the addition result of the current Size and the passed one.
  2360. */
  2361. Size.prototype.add = function (otherSize) {
  2362. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2363. return r;
  2364. };
  2365. /**
  2366. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2367. */
  2368. Size.prototype.subtract = function (otherSize) {
  2369. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2370. return r;
  2371. };
  2372. /**
  2373. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2374. */
  2375. Size.Lerp = function (start, end, amount) {
  2376. var w = start.width + ((end.width - start.width) * amount);
  2377. var h = start.height + ((end.height - start.height) * amount);
  2378. return new Size(w, h);
  2379. };
  2380. return Size;
  2381. }());
  2382. BABYLON.Size = Size;
  2383. var Quaternion = (function () {
  2384. /**
  2385. * Creates a new Quaternion from the passed floats.
  2386. */
  2387. function Quaternion(x, y, z, w) {
  2388. if (x === void 0) { x = 0.0; }
  2389. if (y === void 0) { y = 0.0; }
  2390. if (z === void 0) { z = 0.0; }
  2391. if (w === void 0) { w = 1.0; }
  2392. this.x = x;
  2393. this.y = y;
  2394. this.z = z;
  2395. this.w = w;
  2396. }
  2397. /**
  2398. * Returns a string with the Quaternion coordinates.
  2399. */
  2400. Quaternion.prototype.toString = function () {
  2401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2402. };
  2403. /**
  2404. * Returns the string "Quaternion".
  2405. */
  2406. Quaternion.prototype.getClassName = function () {
  2407. return "Quaternion";
  2408. };
  2409. /**
  2410. * Returns the Quaternion hash code.
  2411. */
  2412. Quaternion.prototype.getHashCode = function () {
  2413. var hash = this.x || 0;
  2414. hash = (hash * 397) ^ (this.y || 0);
  2415. hash = (hash * 397) ^ (this.z || 0);
  2416. hash = (hash * 397) ^ (this.w || 0);
  2417. return hash;
  2418. };
  2419. /**
  2420. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2421. */
  2422. Quaternion.prototype.asArray = function () {
  2423. return [this.x, this.y, this.z, this.w];
  2424. };
  2425. /**
  2426. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2427. */
  2428. Quaternion.prototype.equals = function (otherQuaternion) {
  2429. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2430. };
  2431. /**
  2432. * Returns a new Quaternion copied from the current one.
  2433. */
  2434. Quaternion.prototype.clone = function () {
  2435. return new Quaternion(this.x, this.y, this.z, this.w);
  2436. };
  2437. /**
  2438. * Updates the current Quaternion from the passed one coordinates.
  2439. * Returns the updated Quaterion.
  2440. */
  2441. Quaternion.prototype.copyFrom = function (other) {
  2442. this.x = other.x;
  2443. this.y = other.y;
  2444. this.z = other.z;
  2445. this.w = other.w;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Quaternion from the passed float coordinates.
  2450. * Returns the updated Quaterion.
  2451. */
  2452. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2453. this.x = x;
  2454. this.y = y;
  2455. this.z = z;
  2456. this.w = w;
  2457. return this;
  2458. };
  2459. /**
  2460. * Updates the current Quaternion from the passed float coordinates.
  2461. * Returns the updated Quaterion.
  2462. */
  2463. Quaternion.prototype.set = function (x, y, z, w) {
  2464. return this.copyFromFloats(x, y, z, w);
  2465. };
  2466. /**
  2467. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2468. */
  2469. Quaternion.prototype.add = function (other) {
  2470. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2471. };
  2472. /**
  2473. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2474. */
  2475. Quaternion.prototype.subtract = function (other) {
  2476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2477. };
  2478. /**
  2479. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2480. */
  2481. Quaternion.prototype.scale = function (value) {
  2482. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2483. };
  2484. /**
  2485. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2486. */
  2487. Quaternion.prototype.multiply = function (q1) {
  2488. var result = new Quaternion(0, 0, 0, 1.0);
  2489. this.multiplyToRef(q1, result);
  2490. return result;
  2491. };
  2492. /**
  2493. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2494. * Returns the current Quaternion.
  2495. */
  2496. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2497. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2498. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2499. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2500. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2501. result.copyFromFloats(x, y, z, w);
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.multiplyInPlace = function (q1) {
  2509. this.multiplyToRef(q1, this);
  2510. return this;
  2511. };
  2512. /**
  2513. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.conjugateToRef = function (ref) {
  2517. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2518. return this;
  2519. };
  2520. /**
  2521. * Conjugates in place the current Quaternion.
  2522. * Returns the updated Quaternion.
  2523. */
  2524. Quaternion.prototype.conjugateInPlace = function () {
  2525. this.x *= -1;
  2526. this.y *= -1;
  2527. this.z *= -1;
  2528. return this;
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2532. */
  2533. Quaternion.prototype.conjugate = function () {
  2534. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2535. return result;
  2536. };
  2537. /**
  2538. * Returns the Quaternion length (float).
  2539. */
  2540. Quaternion.prototype.length = function () {
  2541. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2542. };
  2543. /**
  2544. * Normalize in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.normalize = function () {
  2548. var length = 1.0 / this.length();
  2549. this.x *= length;
  2550. this.y *= length;
  2551. this.z *= length;
  2552. this.w *= length;
  2553. return this;
  2554. };
  2555. /**
  2556. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2557. */
  2558. Quaternion.prototype.toEulerAngles = function (order) {
  2559. if (order === void 0) { order = "YZX"; }
  2560. var result = Vector3.Zero();
  2561. this.toEulerAnglesToRef(result, order);
  2562. return result;
  2563. };
  2564. /**
  2565. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2566. * Returns the current Quaternion.
  2567. */
  2568. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2569. if (order === void 0) { order = "YZX"; }
  2570. var qz = this.z;
  2571. var qx = this.x;
  2572. var qy = this.y;
  2573. var qw = this.w;
  2574. var sqw = qw * qw;
  2575. var sqz = qz * qz;
  2576. var sqx = qx * qx;
  2577. var sqy = qy * qy;
  2578. var zAxisY = qy * qz - qx * qw;
  2579. var limit = .4999999;
  2580. if (zAxisY < -limit) {
  2581. result.y = 2 * Math.atan2(qy, qw);
  2582. result.x = Math.PI / 2;
  2583. result.z = 0;
  2584. }
  2585. else if (zAxisY > limit) {
  2586. result.y = 2 * Math.atan2(qy, qw);
  2587. result.x = -Math.PI / 2;
  2588. result.z = 0;
  2589. }
  2590. else {
  2591. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2592. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2593. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2594. }
  2595. return this;
  2596. };
  2597. /**
  2598. * Updates the passed rotation matrix with the current Quaternion values.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toRotationMatrix = function (result) {
  2602. var xx = this.x * this.x;
  2603. var yy = this.y * this.y;
  2604. var zz = this.z * this.z;
  2605. var xy = this.x * this.y;
  2606. var zw = this.z * this.w;
  2607. var zx = this.z * this.x;
  2608. var yw = this.y * this.w;
  2609. var yz = this.y * this.z;
  2610. var xw = this.x * this.w;
  2611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2612. result.m[1] = 2.0 * (xy + zw);
  2613. result.m[2] = 2.0 * (zx - yw);
  2614. result.m[3] = 0;
  2615. result.m[4] = 2.0 * (xy - zw);
  2616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2617. result.m[6] = 2.0 * (yz + xw);
  2618. result.m[7] = 0;
  2619. result.m[8] = 2.0 * (zx + yw);
  2620. result.m[9] = 2.0 * (yz - xw);
  2621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2622. result.m[11] = 0;
  2623. result.m[12] = 0;
  2624. result.m[13] = 0;
  2625. result.m[14] = 0;
  2626. result.m[15] = 1.0;
  2627. result._markAsUpdated();
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the current Quaternion from the passed rotation matrix values.
  2632. * Returns the updated Quaternion.
  2633. */
  2634. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2635. Quaternion.FromRotationMatrixToRef(matrix, this);
  2636. return this;
  2637. };
  2638. // Statics
  2639. /**
  2640. * Returns a new Quaternion set from the passed rotation matrix values.
  2641. */
  2642. Quaternion.FromRotationMatrix = function (matrix) {
  2643. var result = new Quaternion();
  2644. Quaternion.FromRotationMatrixToRef(matrix, result);
  2645. return result;
  2646. };
  2647. /**
  2648. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2649. */
  2650. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2651. var data = matrix.m;
  2652. var m11 = data[0], m12 = data[4], m13 = data[8];
  2653. var m21 = data[1], m22 = data[5], m23 = data[9];
  2654. var m31 = data[2], m32 = data[6], m33 = data[10];
  2655. var trace = m11 + m22 + m33;
  2656. var s;
  2657. if (trace > 0) {
  2658. s = 0.5 / Math.sqrt(trace + 1.0);
  2659. result.w = 0.25 / s;
  2660. result.x = (m32 - m23) * s;
  2661. result.y = (m13 - m31) * s;
  2662. result.z = (m21 - m12) * s;
  2663. }
  2664. else if (m11 > m22 && m11 > m33) {
  2665. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2666. result.w = (m32 - m23) / s;
  2667. result.x = 0.25 * s;
  2668. result.y = (m12 + m21) / s;
  2669. result.z = (m13 + m31) / s;
  2670. }
  2671. else if (m22 > m33) {
  2672. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2673. result.w = (m13 - m31) / s;
  2674. result.x = (m12 + m21) / s;
  2675. result.y = 0.25 * s;
  2676. result.z = (m23 + m32) / s;
  2677. }
  2678. else {
  2679. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2680. result.w = (m21 - m12) / s;
  2681. result.x = (m13 + m31) / s;
  2682. result.y = (m23 + m32) / s;
  2683. result.z = 0.25 * s;
  2684. }
  2685. };
  2686. /**
  2687. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2688. */
  2689. Quaternion.Zero = function () {
  2690. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2691. };
  2692. /**
  2693. * Returns a new Quaternion as the inverted current Quaternion.
  2694. */
  2695. Quaternion.Inverse = function (q) {
  2696. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2697. };
  2698. /**
  2699. * Returns the identity Quaternion.
  2700. */
  2701. Quaternion.Identity = function () {
  2702. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2703. };
  2704. Quaternion.IsIdentity = function (quaternion) {
  2705. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2706. };
  2707. /**
  2708. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2709. */
  2710. Quaternion.RotationAxis = function (axis, angle) {
  2711. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2712. };
  2713. /**
  2714. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2715. */
  2716. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2717. var sin = Math.sin(angle / 2);
  2718. axis.normalize();
  2719. result.w = Math.cos(angle / 2);
  2720. result.x = axis.x * sin;
  2721. result.y = axis.y * sin;
  2722. result.z = axis.z * sin;
  2723. return result;
  2724. };
  2725. /**
  2726. * Retuns a new Quaternion set from the starting index of the passed array.
  2727. */
  2728. Quaternion.FromArray = function (array, offset) {
  2729. if (!offset) {
  2730. offset = 0;
  2731. }
  2732. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2733. };
  2734. /**
  2735. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2736. */
  2737. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2738. var q = new Quaternion();
  2739. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2740. return q;
  2741. };
  2742. /**
  2743. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2744. */
  2745. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2746. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2747. var halfRoll = roll * 0.5;
  2748. var halfPitch = pitch * 0.5;
  2749. var halfYaw = yaw * 0.5;
  2750. var sinRoll = Math.sin(halfRoll);
  2751. var cosRoll = Math.cos(halfRoll);
  2752. var sinPitch = Math.sin(halfPitch);
  2753. var cosPitch = Math.cos(halfPitch);
  2754. var sinYaw = Math.sin(halfYaw);
  2755. var cosYaw = Math.cos(halfYaw);
  2756. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2757. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2758. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2759. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2760. };
  2761. /**
  2762. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2763. */
  2764. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2765. var result = new Quaternion();
  2766. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2767. return result;
  2768. };
  2769. /**
  2770. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2771. */
  2772. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2773. // Produces a quaternion from Euler angles in the z-x-z orientation
  2774. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2775. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2776. var halfBeta = beta * 0.5;
  2777. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2778. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2779. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2780. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2781. };
  2782. /**
  2783. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2784. * cf to Vector3.RotationFromAxis() documentation.
  2785. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2786. */
  2787. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2788. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2789. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2790. return quat;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2794. * cf to Vector3.RotationFromAxis() documentation.
  2795. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2796. */
  2797. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2798. var rotMat = MathTmp.Matrix[0];
  2799. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2800. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2801. };
  2802. Quaternion.Slerp = function (left, right, amount) {
  2803. var result = Quaternion.Identity();
  2804. Quaternion.SlerpToRef(left, right, amount, result);
  2805. return result;
  2806. };
  2807. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2808. var num2;
  2809. var num3;
  2810. var num = amount;
  2811. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2812. var flag = false;
  2813. if (num4 < 0) {
  2814. flag = true;
  2815. num4 = -num4;
  2816. }
  2817. if (num4 > 0.999999) {
  2818. num3 = 1 - num;
  2819. num2 = flag ? -num : num;
  2820. }
  2821. else {
  2822. var num5 = Math.acos(num4);
  2823. var num6 = (1.0 / Math.sin(num5));
  2824. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2825. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2826. }
  2827. result.x = (num3 * left.x) + (num2 * right.x);
  2828. result.y = (num3 * left.y) + (num2 * right.y);
  2829. result.z = (num3 * left.z) + (num2 * right.z);
  2830. result.w = (num3 * left.w) + (num2 * right.w);
  2831. };
  2832. /**
  2833. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2834. */
  2835. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2836. var squared = amount * amount;
  2837. var cubed = amount * squared;
  2838. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2839. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2840. var part3 = (cubed - (2.0 * squared)) + amount;
  2841. var part4 = cubed - squared;
  2842. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2843. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2844. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2845. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2846. return new Quaternion(x, y, z, w);
  2847. };
  2848. return Quaternion;
  2849. }());
  2850. BABYLON.Quaternion = Quaternion;
  2851. var Matrix = (function () {
  2852. function Matrix() {
  2853. this._isIdentity = false;
  2854. this._isIdentityDirty = true;
  2855. this.m = new Float32Array(16);
  2856. this._markAsUpdated();
  2857. }
  2858. Matrix.prototype._markAsUpdated = function () {
  2859. this.updateFlag = Matrix._updateFlagSeed++;
  2860. this._isIdentityDirty = true;
  2861. };
  2862. // Properties
  2863. /**
  2864. * Boolean : True is the matrix is the identity matrix
  2865. */
  2866. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2867. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2868. if (this._isIdentityDirty) {
  2869. this._isIdentityDirty = false;
  2870. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2871. this._isIdentity = false;
  2872. }
  2873. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2874. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2875. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2876. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2877. this._isIdentity = false;
  2878. }
  2879. else {
  2880. this._isIdentity = true;
  2881. }
  2882. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2883. this._isIdentity = false;
  2884. }
  2885. }
  2886. return this._isIdentity;
  2887. };
  2888. /**
  2889. * Returns the matrix determinant (float).
  2890. */
  2891. Matrix.prototype.determinant = function () {
  2892. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2893. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2894. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2895. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2896. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2897. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2898. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2899. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2900. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2901. };
  2902. // Methods
  2903. /**
  2904. * Returns the matrix underlying array.
  2905. */
  2906. Matrix.prototype.toArray = function () {
  2907. return this.m;
  2908. };
  2909. /**
  2910. * Returns the matrix underlying array.
  2911. */
  2912. Matrix.prototype.asArray = function () {
  2913. return this.toArray();
  2914. };
  2915. /**
  2916. * Inverts in place the Matrix.
  2917. * Returns the Matrix inverted.
  2918. */
  2919. Matrix.prototype.invert = function () {
  2920. this.invertToRef(this);
  2921. return this;
  2922. };
  2923. /**
  2924. * Sets all the matrix elements to zero.
  2925. * Returns the Matrix.
  2926. */
  2927. Matrix.prototype.reset = function () {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = 0.0;
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2936. */
  2937. Matrix.prototype.add = function (other) {
  2938. var result = new Matrix();
  2939. this.addToRef(other, result);
  2940. return result;
  2941. };
  2942. /**
  2943. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.addToRef = function (other, result) {
  2947. for (var index = 0; index < 16; index++) {
  2948. result.m[index] = this.m[index] + other.m[index];
  2949. }
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Adds in place the passed matrix to the current Matrix.
  2955. * Returns the updated Matrix.
  2956. */
  2957. Matrix.prototype.addToSelf = function (other) {
  2958. for (var index = 0; index < 16; index++) {
  2959. this.m[index] += other.m[index];
  2960. }
  2961. this._markAsUpdated();
  2962. return this;
  2963. };
  2964. /**
  2965. * Sets the passed matrix with the current inverted Matrix.
  2966. * Returns the unmodified current Matrix.
  2967. */
  2968. Matrix.prototype.invertToRef = function (other) {
  2969. var l1 = this.m[0];
  2970. var l2 = this.m[1];
  2971. var l3 = this.m[2];
  2972. var l4 = this.m[3];
  2973. var l5 = this.m[4];
  2974. var l6 = this.m[5];
  2975. var l7 = this.m[6];
  2976. var l8 = this.m[7];
  2977. var l9 = this.m[8];
  2978. var l10 = this.m[9];
  2979. var l11 = this.m[10];
  2980. var l12 = this.m[11];
  2981. var l13 = this.m[12];
  2982. var l14 = this.m[13];
  2983. var l15 = this.m[14];
  2984. var l16 = this.m[15];
  2985. var l17 = (l11 * l16) - (l12 * l15);
  2986. var l18 = (l10 * l16) - (l12 * l14);
  2987. var l19 = (l10 * l15) - (l11 * l14);
  2988. var l20 = (l9 * l16) - (l12 * l13);
  2989. var l21 = (l9 * l15) - (l11 * l13);
  2990. var l22 = (l9 * l14) - (l10 * l13);
  2991. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2992. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2993. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2994. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2995. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2996. var l28 = (l7 * l16) - (l8 * l15);
  2997. var l29 = (l6 * l16) - (l8 * l14);
  2998. var l30 = (l6 * l15) - (l7 * l14);
  2999. var l31 = (l5 * l16) - (l8 * l13);
  3000. var l32 = (l5 * l15) - (l7 * l13);
  3001. var l33 = (l5 * l14) - (l6 * l13);
  3002. var l34 = (l7 * l12) - (l8 * l11);
  3003. var l35 = (l6 * l12) - (l8 * l10);
  3004. var l36 = (l6 * l11) - (l7 * l10);
  3005. var l37 = (l5 * l12) - (l8 * l9);
  3006. var l38 = (l5 * l11) - (l7 * l9);
  3007. var l39 = (l5 * l10) - (l6 * l9);
  3008. other.m[0] = l23 * l27;
  3009. other.m[4] = l24 * l27;
  3010. other.m[8] = l25 * l27;
  3011. other.m[12] = l26 * l27;
  3012. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3013. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3014. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3015. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3016. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3017. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3018. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3019. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3020. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3021. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3022. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3023. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3024. other._markAsUpdated();
  3025. return this;
  3026. };
  3027. /**
  3028. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3029. * Returns the updated Matrix.
  3030. */
  3031. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3032. this.m[12] = x;
  3033. this.m[13] = y;
  3034. this.m[14] = z;
  3035. this._markAsUpdated();
  3036. return this;
  3037. };
  3038. /**
  3039. * Inserts the translation vector in the current Matrix.
  3040. * Returns the updated Matrix.
  3041. */
  3042. Matrix.prototype.setTranslation = function (vector3) {
  3043. this.m[12] = vector3.x;
  3044. this.m[13] = vector3.y;
  3045. this.m[14] = vector3.z;
  3046. this._markAsUpdated();
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns a new Vector3 as the extracted translation from the Matrix.
  3051. */
  3052. Matrix.prototype.getTranslation = function () {
  3053. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3054. };
  3055. /**
  3056. * Fill a Vector3 with the extracted translation from the Matrix.
  3057. */
  3058. Matrix.prototype.getTranslationToRef = function (result) {
  3059. result.x = this.m[12];
  3060. result.y = this.m[13];
  3061. result.z = this.m[14];
  3062. return this;
  3063. };
  3064. /**
  3065. * Remove rotation and scaling part from the Matrix.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.removeRotationAndScaling = function () {
  3069. this.setRowFromFloats(0, 1, 0, 0, 0);
  3070. this.setRowFromFloats(1, 0, 1, 0, 0);
  3071. this.setRowFromFloats(2, 0, 0, 1, 0);
  3072. return this;
  3073. };
  3074. /**
  3075. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3076. */
  3077. Matrix.prototype.multiply = function (other) {
  3078. var result = new Matrix();
  3079. this.multiplyToRef(other, result);
  3080. return result;
  3081. };
  3082. /**
  3083. * Updates the current Matrix from the passed one values.
  3084. * Returns the updated Matrix.
  3085. */
  3086. Matrix.prototype.copyFrom = function (other) {
  3087. for (var index = 0; index < 16; index++) {
  3088. this.m[index] = other.m[index];
  3089. }
  3090. this._markAsUpdated();
  3091. return this;
  3092. };
  3093. /**
  3094. * Populates the passed array from the starting index with the Matrix values.
  3095. * Returns the Matrix.
  3096. */
  3097. Matrix.prototype.copyToArray = function (array, offset) {
  3098. if (offset === void 0) { offset = 0; }
  3099. for (var index = 0; index < 16; index++) {
  3100. array[offset + index] = this.m[index];
  3101. }
  3102. return this;
  3103. };
  3104. /**
  3105. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3106. */
  3107. Matrix.prototype.multiplyToRef = function (other, result) {
  3108. this.multiplyToArray(other, result.m, 0);
  3109. result._markAsUpdated();
  3110. return this;
  3111. };
  3112. /**
  3113. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3114. */
  3115. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3116. var tm0 = this.m[0];
  3117. var tm1 = this.m[1];
  3118. var tm2 = this.m[2];
  3119. var tm3 = this.m[3];
  3120. var tm4 = this.m[4];
  3121. var tm5 = this.m[5];
  3122. var tm6 = this.m[6];
  3123. var tm7 = this.m[7];
  3124. var tm8 = this.m[8];
  3125. var tm9 = this.m[9];
  3126. var tm10 = this.m[10];
  3127. var tm11 = this.m[11];
  3128. var tm12 = this.m[12];
  3129. var tm13 = this.m[13];
  3130. var tm14 = this.m[14];
  3131. var tm15 = this.m[15];
  3132. var om0 = other.m[0];
  3133. var om1 = other.m[1];
  3134. var om2 = other.m[2];
  3135. var om3 = other.m[3];
  3136. var om4 = other.m[4];
  3137. var om5 = other.m[5];
  3138. var om6 = other.m[6];
  3139. var om7 = other.m[7];
  3140. var om8 = other.m[8];
  3141. var om9 = other.m[9];
  3142. var om10 = other.m[10];
  3143. var om11 = other.m[11];
  3144. var om12 = other.m[12];
  3145. var om13 = other.m[13];
  3146. var om14 = other.m[14];
  3147. var om15 = other.m[15];
  3148. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3149. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3150. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3151. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3152. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3153. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3154. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3155. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3156. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3157. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3158. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3159. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3160. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3161. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3162. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3163. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3164. return this;
  3165. };
  3166. /**
  3167. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3168. */
  3169. Matrix.prototype.equals = function (value) {
  3170. return value &&
  3171. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3172. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3173. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3174. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3175. };
  3176. /**
  3177. * Returns a new Matrix from the current Matrix.
  3178. */
  3179. Matrix.prototype.clone = function () {
  3180. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3181. };
  3182. /**
  3183. * Returns the string "Matrix"
  3184. */
  3185. Matrix.prototype.getClassName = function () {
  3186. return "Matrix";
  3187. };
  3188. /**
  3189. * Returns the Matrix hash code.
  3190. */
  3191. Matrix.prototype.getHashCode = function () {
  3192. var hash = this.m[0] || 0;
  3193. for (var i = 1; i < 16; i++) {
  3194. hash = (hash * 397) ^ (this.m[i] || 0);
  3195. }
  3196. return hash;
  3197. };
  3198. /**
  3199. * Decomposes the current Matrix into :
  3200. * - a scale vector3 passed as a reference to update,
  3201. * - a rotation quaternion passed as a reference to update,
  3202. * - a translation vector3 passed as a reference to update.
  3203. * Returns the boolean `true`.
  3204. */
  3205. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3206. translation.x = this.m[12];
  3207. translation.y = this.m[13];
  3208. translation.z = this.m[14];
  3209. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3210. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3211. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3212. if (this.determinant() <= 0) {
  3213. scale.y *= -1;
  3214. }
  3215. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3216. rotation.x = 0;
  3217. rotation.y = 0;
  3218. rotation.z = 0;
  3219. rotation.w = 1;
  3220. return false;
  3221. }
  3222. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3223. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3224. return true;
  3225. };
  3226. /**
  3227. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3228. */
  3229. Matrix.prototype.getRotationMatrix = function () {
  3230. var result = Matrix.Identity();
  3231. this.getRotationMatrixToRef(result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3236. * Returns the current Matrix.
  3237. */
  3238. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3239. var m = this.m;
  3240. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3241. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3242. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3243. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3244. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3245. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3246. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3247. return this;
  3248. };
  3249. // Statics
  3250. /**
  3251. * Returns a new Matrix set from the starting index of the passed array.
  3252. */
  3253. Matrix.FromArray = function (array, offset) {
  3254. var result = new Matrix();
  3255. if (!offset) {
  3256. offset = 0;
  3257. }
  3258. Matrix.FromArrayToRef(array, offset, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * Sets the passed "result" matrix from the starting index of the passed array.
  3263. */
  3264. Matrix.FromArrayToRef = function (array, offset, result) {
  3265. for (var index = 0; index < 16; index++) {
  3266. result.m[index] = array[index + offset];
  3267. }
  3268. result._markAsUpdated();
  3269. };
  3270. /**
  3271. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3272. */
  3273. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3274. for (var index = 0; index < 16; index++) {
  3275. result.m[index] = array[index + offset] * scale;
  3276. }
  3277. result._markAsUpdated();
  3278. };
  3279. /**
  3280. * Sets the passed matrix "result" with the 16 passed floats.
  3281. */
  3282. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3283. result.m[0] = initialM11;
  3284. result.m[1] = initialM12;
  3285. result.m[2] = initialM13;
  3286. result.m[3] = initialM14;
  3287. result.m[4] = initialM21;
  3288. result.m[5] = initialM22;
  3289. result.m[6] = initialM23;
  3290. result.m[7] = initialM24;
  3291. result.m[8] = initialM31;
  3292. result.m[9] = initialM32;
  3293. result.m[10] = initialM33;
  3294. result.m[11] = initialM34;
  3295. result.m[12] = initialM41;
  3296. result.m[13] = initialM42;
  3297. result.m[14] = initialM43;
  3298. result.m[15] = initialM44;
  3299. result._markAsUpdated();
  3300. };
  3301. /**
  3302. * Returns the index-th row of the current matrix as a new Vector4.
  3303. */
  3304. Matrix.prototype.getRow = function (index) {
  3305. if (index < 0 || index > 3) {
  3306. return null;
  3307. }
  3308. var i = index * 4;
  3309. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3310. };
  3311. /**
  3312. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3313. * Returns the updated Matrix.
  3314. */
  3315. Matrix.prototype.setRow = function (index, row) {
  3316. if (index < 0 || index > 3) {
  3317. return this;
  3318. }
  3319. var i = index * 4;
  3320. this.m[i + 0] = row.x;
  3321. this.m[i + 1] = row.y;
  3322. this.m[i + 2] = row.z;
  3323. this.m[i + 3] = row.w;
  3324. this._markAsUpdated();
  3325. return this;
  3326. };
  3327. /**
  3328. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3329. * Returns the updated Matrix.
  3330. */
  3331. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3332. if (index < 0 || index > 3) {
  3333. return this;
  3334. }
  3335. var i = index * 4;
  3336. this.m[i + 0] = x;
  3337. this.m[i + 1] = y;
  3338. this.m[i + 2] = z;
  3339. this.m[i + 3] = w;
  3340. this._markAsUpdated();
  3341. return this;
  3342. };
  3343. /**
  3344. * Returns a new Matrix set from the 16 passed floats.
  3345. */
  3346. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3347. var result = new Matrix();
  3348. result.m[0] = initialM11;
  3349. result.m[1] = initialM12;
  3350. result.m[2] = initialM13;
  3351. result.m[3] = initialM14;
  3352. result.m[4] = initialM21;
  3353. result.m[5] = initialM22;
  3354. result.m[6] = initialM23;
  3355. result.m[7] = initialM24;
  3356. result.m[8] = initialM31;
  3357. result.m[9] = initialM32;
  3358. result.m[10] = initialM33;
  3359. result.m[11] = initialM34;
  3360. result.m[12] = initialM41;
  3361. result.m[13] = initialM42;
  3362. result.m[14] = initialM43;
  3363. result.m[15] = initialM44;
  3364. return result;
  3365. };
  3366. /**
  3367. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3368. */
  3369. Matrix.Compose = function (scale, rotation, translation) {
  3370. var result = Matrix.Identity();
  3371. Matrix.ComposeToRef(scale, rotation, translation, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3376. */
  3377. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3378. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3379. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3380. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3381. result.setTranslation(translation);
  3382. };
  3383. /**
  3384. * Returns a new indentity Matrix.
  3385. */
  3386. Matrix.Identity = function () {
  3387. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3388. };
  3389. /**
  3390. * Sets the passed "result" as an identity matrix.
  3391. */
  3392. Matrix.IdentityToRef = function (result) {
  3393. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3394. };
  3395. /**
  3396. * Returns a new zero Matrix.
  3397. */
  3398. Matrix.Zero = function () {
  3399. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new rotation matrix for "angle" radians around the X axis.
  3403. */
  3404. Matrix.RotationX = function (angle) {
  3405. var result = new Matrix();
  3406. Matrix.RotationXToRef(angle, result);
  3407. return result;
  3408. };
  3409. /**
  3410. * Returns a new Matrix as the passed inverted one.
  3411. */
  3412. Matrix.Invert = function (source) {
  3413. var result = new Matrix();
  3414. source.invertToRef(result);
  3415. return result;
  3416. };
  3417. /**
  3418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3419. */
  3420. Matrix.RotationXToRef = function (angle, result) {
  3421. var s = Math.sin(angle);
  3422. var c = Math.cos(angle);
  3423. result.m[0] = 1.0;
  3424. result.m[15] = 1.0;
  3425. result.m[5] = c;
  3426. result.m[10] = c;
  3427. result.m[9] = -s;
  3428. result.m[6] = s;
  3429. result.m[1] = 0.0;
  3430. result.m[2] = 0.0;
  3431. result.m[3] = 0.0;
  3432. result.m[4] = 0.0;
  3433. result.m[7] = 0.0;
  3434. result.m[8] = 0.0;
  3435. result.m[11] = 0.0;
  3436. result.m[12] = 0.0;
  3437. result.m[13] = 0.0;
  3438. result.m[14] = 0.0;
  3439. result._markAsUpdated();
  3440. };
  3441. /**
  3442. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3443. */
  3444. Matrix.RotationY = function (angle) {
  3445. var result = new Matrix();
  3446. Matrix.RotationYToRef(angle, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3451. */
  3452. Matrix.RotationYToRef = function (angle, result) {
  3453. var s = Math.sin(angle);
  3454. var c = Math.cos(angle);
  3455. result.m[5] = 1.0;
  3456. result.m[15] = 1.0;
  3457. result.m[0] = c;
  3458. result.m[2] = -s;
  3459. result.m[8] = s;
  3460. result.m[10] = c;
  3461. result.m[1] = 0.0;
  3462. result.m[3] = 0.0;
  3463. result.m[4] = 0.0;
  3464. result.m[6] = 0.0;
  3465. result.m[7] = 0.0;
  3466. result.m[9] = 0.0;
  3467. result.m[11] = 0.0;
  3468. result.m[12] = 0.0;
  3469. result.m[13] = 0.0;
  3470. result.m[14] = 0.0;
  3471. result._markAsUpdated();
  3472. };
  3473. /**
  3474. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3475. */
  3476. Matrix.RotationZ = function (angle) {
  3477. var result = new Matrix();
  3478. Matrix.RotationZToRef(angle, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3483. */
  3484. Matrix.RotationZToRef = function (angle, result) {
  3485. var s = Math.sin(angle);
  3486. var c = Math.cos(angle);
  3487. result.m[10] = 1.0;
  3488. result.m[15] = 1.0;
  3489. result.m[0] = c;
  3490. result.m[1] = s;
  3491. result.m[4] = -s;
  3492. result.m[5] = c;
  3493. result.m[2] = 0.0;
  3494. result.m[3] = 0.0;
  3495. result.m[6] = 0.0;
  3496. result.m[7] = 0.0;
  3497. result.m[8] = 0.0;
  3498. result.m[9] = 0.0;
  3499. result.m[11] = 0.0;
  3500. result.m[12] = 0.0;
  3501. result.m[13] = 0.0;
  3502. result.m[14] = 0.0;
  3503. result._markAsUpdated();
  3504. };
  3505. /**
  3506. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3507. */
  3508. Matrix.RotationAxis = function (axis, angle) {
  3509. var result = Matrix.Zero();
  3510. Matrix.RotationAxisToRef(axis, angle, result);
  3511. return result;
  3512. };
  3513. /**
  3514. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3515. */
  3516. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3517. var s = Math.sin(-angle);
  3518. var c = Math.cos(-angle);
  3519. var c1 = 1 - c;
  3520. axis.normalize();
  3521. result.m[0] = (axis.x * axis.x) * c1 + c;
  3522. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3523. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3524. result.m[3] = 0.0;
  3525. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3526. result.m[5] = (axis.y * axis.y) * c1 + c;
  3527. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3528. result.m[7] = 0.0;
  3529. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3530. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3531. result.m[10] = (axis.z * axis.z) * c1 + c;
  3532. result.m[11] = 0.0;
  3533. result.m[15] = 1.0;
  3534. result._markAsUpdated();
  3535. };
  3536. /**
  3537. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3538. */
  3539. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3540. var result = new Matrix();
  3541. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3546. */
  3547. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3548. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3549. this._tempQuaternion.toRotationMatrix(result);
  3550. };
  3551. /**
  3552. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3553. */
  3554. Matrix.Scaling = function (x, y, z) {
  3555. var result = Matrix.Zero();
  3556. Matrix.ScalingToRef(x, y, z, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3561. */
  3562. Matrix.ScalingToRef = function (x, y, z, result) {
  3563. result.m[0] = x;
  3564. result.m[1] = 0.0;
  3565. result.m[2] = 0.0;
  3566. result.m[3] = 0.0;
  3567. result.m[4] = 0.0;
  3568. result.m[5] = y;
  3569. result.m[6] = 0.0;
  3570. result.m[7] = 0.0;
  3571. result.m[8] = 0.0;
  3572. result.m[9] = 0.0;
  3573. result.m[10] = z;
  3574. result.m[11] = 0.0;
  3575. result.m[12] = 0.0;
  3576. result.m[13] = 0.0;
  3577. result.m[14] = 0.0;
  3578. result.m[15] = 1.0;
  3579. result._markAsUpdated();
  3580. };
  3581. /**
  3582. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3583. */
  3584. Matrix.Translation = function (x, y, z) {
  3585. var result = Matrix.Identity();
  3586. Matrix.TranslationToRef(x, y, z, result);
  3587. return result;
  3588. };
  3589. /**
  3590. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3591. */
  3592. Matrix.TranslationToRef = function (x, y, z, result) {
  3593. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3594. };
  3595. /**
  3596. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3597. */
  3598. Matrix.Lerp = function (startValue, endValue, gradient) {
  3599. var result = Matrix.Zero();
  3600. for (var index = 0; index < 16; index++) {
  3601. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3602. }
  3603. result._markAsUpdated();
  3604. return result;
  3605. };
  3606. /**
  3607. * Returns a new Matrix whose values are computed by :
  3608. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3609. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3610. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3611. */
  3612. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3613. var startScale = new Vector3(0, 0, 0);
  3614. var startRotation = new Quaternion();
  3615. var startTranslation = new Vector3(0, 0, 0);
  3616. startValue.decompose(startScale, startRotation, startTranslation);
  3617. var endScale = new Vector3(0, 0, 0);
  3618. var endRotation = new Quaternion();
  3619. var endTranslation = new Vector3(0, 0, 0);
  3620. endValue.decompose(endScale, endRotation, endTranslation);
  3621. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3622. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3623. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3624. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3625. };
  3626. /**
  3627. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3628. * This methods works for a Left-Handed system.
  3629. */
  3630. Matrix.LookAtLH = function (eye, target, up) {
  3631. var result = Matrix.Zero();
  3632. Matrix.LookAtLHToRef(eye, target, up, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3637. * This methods works for a Left-Handed system.
  3638. */
  3639. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3640. // Z axis
  3641. target.subtractToRef(eye, this._zAxis);
  3642. this._zAxis.normalize();
  3643. // X axis
  3644. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3645. if (this._xAxis.lengthSquared() === 0) {
  3646. this._xAxis.x = 1.0;
  3647. }
  3648. else {
  3649. this._xAxis.normalize();
  3650. }
  3651. // Y axis
  3652. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3653. this._yAxis.normalize();
  3654. // Eye angles
  3655. var ex = -Vector3.Dot(this._xAxis, eye);
  3656. var ey = -Vector3.Dot(this._yAxis, eye);
  3657. var ez = -Vector3.Dot(this._zAxis, eye);
  3658. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3659. };
  3660. /**
  3661. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3662. * This methods works for a Right-Handed system.
  3663. */
  3664. Matrix.LookAtRH = function (eye, target, up) {
  3665. var result = Matrix.Zero();
  3666. Matrix.LookAtRHToRef(eye, target, up, result);
  3667. return result;
  3668. };
  3669. /**
  3670. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3671. * This methods works for a Left-Handed system.
  3672. */
  3673. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3674. // Z axis
  3675. eye.subtractToRef(target, this._zAxis);
  3676. this._zAxis.normalize();
  3677. // X axis
  3678. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3679. if (this._xAxis.lengthSquared() === 0) {
  3680. this._xAxis.x = 1.0;
  3681. }
  3682. else {
  3683. this._xAxis.normalize();
  3684. }
  3685. // Y axis
  3686. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3687. this._yAxis.normalize();
  3688. // Eye angles
  3689. var ex = -Vector3.Dot(this._xAxis, eye);
  3690. var ey = -Vector3.Dot(this._yAxis, eye);
  3691. var ez = -Vector3.Dot(this._zAxis, eye);
  3692. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3693. };
  3694. /**
  3695. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3696. */
  3697. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3698. var matrix = Matrix.Zero();
  3699. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3700. return matrix;
  3701. };
  3702. /**
  3703. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3704. */
  3705. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3706. var n = znear;
  3707. var f = zfar;
  3708. var a = 2.0 / width;
  3709. var b = 2.0 / height;
  3710. var c = 2.0 / (f - n);
  3711. var d = -(f + n) / (f - n);
  3712. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3713. };
  3714. /**
  3715. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3716. */
  3717. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3718. var matrix = Matrix.Zero();
  3719. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3720. return matrix;
  3721. };
  3722. /**
  3723. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3724. */
  3725. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3726. var n = znear;
  3727. var f = zfar;
  3728. var a = 2.0 / (right - left);
  3729. var b = 2.0 / (top - bottom);
  3730. var c = 2.0 / (f - n);
  3731. var d = -(f + n) / (f - n);
  3732. var i0 = (left + right) / (left - right);
  3733. var i1 = (top + bottom) / (bottom - top);
  3734. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3735. };
  3736. /**
  3737. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3738. */
  3739. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3740. var matrix = Matrix.Zero();
  3741. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3742. return matrix;
  3743. };
  3744. /**
  3745. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3746. */
  3747. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3749. result.m[10] *= -1.0;
  3750. };
  3751. /**
  3752. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3753. */
  3754. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3755. var matrix = Matrix.Zero();
  3756. var n = znear;
  3757. var f = zfar;
  3758. var a = 2.0 * n / width;
  3759. var b = 2.0 * n / height;
  3760. var c = (f + n) / (f - n);
  3761. var d = -2.0 * f * n / (f - n);
  3762. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3763. return matrix;
  3764. };
  3765. /**
  3766. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3767. */
  3768. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3769. var matrix = Matrix.Zero();
  3770. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3771. return matrix;
  3772. };
  3773. /**
  3774. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3775. */
  3776. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3778. var n = znear;
  3779. var f = zfar;
  3780. var t = 1.0 / (Math.tan(fov * 0.5));
  3781. var a = isVerticalFovFixed ? (t / aspect) : t;
  3782. var b = isVerticalFovFixed ? t : (t * aspect);
  3783. var c = (f + n) / (f - n);
  3784. var d = -2.0 * f * n / (f - n);
  3785. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3786. };
  3787. /**
  3788. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3789. */
  3790. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3791. var matrix = Matrix.Zero();
  3792. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3793. return matrix;
  3794. };
  3795. /**
  3796. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3797. */
  3798. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3799. //alternatively this could be expressed as:
  3800. // m = PerspectiveFovLHToRef
  3801. // m[10] *= -1.0;
  3802. // m[11] *= -1.0;
  3803. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3804. var n = znear;
  3805. var f = zfar;
  3806. var t = 1.0 / (Math.tan(fov * 0.5));
  3807. var a = isVerticalFovFixed ? (t / aspect) : t;
  3808. var b = isVerticalFovFixed ? t : (t * aspect);
  3809. var c = -(f + n) / (f - n);
  3810. var d = -2 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3812. };
  3813. /**
  3814. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3815. */
  3816. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3817. if (rightHanded === void 0) { rightHanded = false; }
  3818. var rightHandedFactor = rightHanded ? -1 : 1;
  3819. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3820. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3821. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3822. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3823. var xScale = 2.0 / (leftTan + rightTan);
  3824. var yScale = 2.0 / (upTan + downTan);
  3825. result.m[0] = xScale;
  3826. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3827. result.m[5] = yScale;
  3828. result.m[6] = result.m[7] = 0.0;
  3829. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3830. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3831. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3832. result.m[10] = -zfar / (znear - zfar);
  3833. result.m[11] = 1.0 * rightHandedFactor;
  3834. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3835. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3836. // result.m[14] = (znear * zfar) / (znear - zfar);
  3837. result._markAsUpdated();
  3838. };
  3839. /**
  3840. * Returns the final transformation matrix : world * view * projection * viewport
  3841. */
  3842. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3843. var cw = viewport.width;
  3844. var ch = viewport.height;
  3845. var cx = viewport.x;
  3846. var cy = viewport.y;
  3847. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3848. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3849. };
  3850. /**
  3851. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3852. */
  3853. Matrix.GetAsMatrix2x2 = function (matrix) {
  3854. return new Float32Array([
  3855. matrix.m[0], matrix.m[1],
  3856. matrix.m[4], matrix.m[5]
  3857. ]);
  3858. };
  3859. /**
  3860. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3861. */
  3862. Matrix.GetAsMatrix3x3 = function (matrix) {
  3863. return new Float32Array([
  3864. matrix.m[0], matrix.m[1], matrix.m[2],
  3865. matrix.m[4], matrix.m[5], matrix.m[6],
  3866. matrix.m[8], matrix.m[9], matrix.m[10]
  3867. ]);
  3868. };
  3869. /**
  3870. * Compute the transpose of the passed Matrix.
  3871. * Returns a new Matrix.
  3872. */
  3873. Matrix.Transpose = function (matrix) {
  3874. var result = new Matrix();
  3875. result.m[0] = matrix.m[0];
  3876. result.m[1] = matrix.m[4];
  3877. result.m[2] = matrix.m[8];
  3878. result.m[3] = matrix.m[12];
  3879. result.m[4] = matrix.m[1];
  3880. result.m[5] = matrix.m[5];
  3881. result.m[6] = matrix.m[9];
  3882. result.m[7] = matrix.m[13];
  3883. result.m[8] = matrix.m[2];
  3884. result.m[9] = matrix.m[6];
  3885. result.m[10] = matrix.m[10];
  3886. result.m[11] = matrix.m[14];
  3887. result.m[12] = matrix.m[3];
  3888. result.m[13] = matrix.m[7];
  3889. result.m[14] = matrix.m[11];
  3890. result.m[15] = matrix.m[15];
  3891. return result;
  3892. };
  3893. /**
  3894. * Returns a new Matrix as the reflection matrix across the passed plane.
  3895. */
  3896. Matrix.Reflection = function (plane) {
  3897. var matrix = new Matrix();
  3898. Matrix.ReflectionToRef(plane, matrix);
  3899. return matrix;
  3900. };
  3901. /**
  3902. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3903. */
  3904. Matrix.ReflectionToRef = function (plane, result) {
  3905. plane.normalize();
  3906. var x = plane.normal.x;
  3907. var y = plane.normal.y;
  3908. var z = plane.normal.z;
  3909. var temp = -2 * x;
  3910. var temp2 = -2 * y;
  3911. var temp3 = -2 * z;
  3912. result.m[0] = (temp * x) + 1;
  3913. result.m[1] = temp2 * x;
  3914. result.m[2] = temp3 * x;
  3915. result.m[3] = 0.0;
  3916. result.m[4] = temp * y;
  3917. result.m[5] = (temp2 * y) + 1;
  3918. result.m[6] = temp3 * y;
  3919. result.m[7] = 0.0;
  3920. result.m[8] = temp * z;
  3921. result.m[9] = temp2 * z;
  3922. result.m[10] = (temp3 * z) + 1;
  3923. result.m[11] = 0.0;
  3924. result.m[12] = temp * plane.d;
  3925. result.m[13] = temp2 * plane.d;
  3926. result.m[14] = temp3 * plane.d;
  3927. result.m[15] = 1.0;
  3928. result._markAsUpdated();
  3929. };
  3930. /**
  3931. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3932. */
  3933. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3934. result.m[0] = xaxis.x;
  3935. result.m[1] = xaxis.y;
  3936. result.m[2] = xaxis.z;
  3937. result.m[3] = 0.0;
  3938. result.m[4] = yaxis.x;
  3939. result.m[5] = yaxis.y;
  3940. result.m[6] = yaxis.z;
  3941. result.m[7] = 0.0;
  3942. result.m[8] = zaxis.x;
  3943. result.m[9] = zaxis.y;
  3944. result.m[10] = zaxis.z;
  3945. result.m[11] = 0.0;
  3946. result.m[12] = 0.0;
  3947. result.m[13] = 0.0;
  3948. result.m[14] = 0.0;
  3949. result.m[15] = 1.0;
  3950. result._markAsUpdated();
  3951. };
  3952. /**
  3953. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3954. */
  3955. Matrix.FromQuaternionToRef = function (quat, result) {
  3956. var xx = quat.x * quat.x;
  3957. var yy = quat.y * quat.y;
  3958. var zz = quat.z * quat.z;
  3959. var xy = quat.x * quat.y;
  3960. var zw = quat.z * quat.w;
  3961. var zx = quat.z * quat.x;
  3962. var yw = quat.y * quat.w;
  3963. var yz = quat.y * quat.z;
  3964. var xw = quat.x * quat.w;
  3965. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3966. result.m[1] = 2.0 * (xy + zw);
  3967. result.m[2] = 2.0 * (zx - yw);
  3968. result.m[3] = 0.0;
  3969. result.m[4] = 2.0 * (xy - zw);
  3970. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3971. result.m[6] = 2.0 * (yz + xw);
  3972. result.m[7] = 0.0;
  3973. result.m[8] = 2.0 * (zx + yw);
  3974. result.m[9] = 2.0 * (yz - xw);
  3975. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3976. result.m[11] = 0.0;
  3977. result.m[12] = 0.0;
  3978. result.m[13] = 0.0;
  3979. result.m[14] = 0.0;
  3980. result.m[15] = 1.0;
  3981. result._markAsUpdated();
  3982. };
  3983. Matrix._tempQuaternion = new Quaternion();
  3984. Matrix._xAxis = Vector3.Zero();
  3985. Matrix._yAxis = Vector3.Zero();
  3986. Matrix._zAxis = Vector3.Zero();
  3987. Matrix._updateFlagSeed = 0;
  3988. return Matrix;
  3989. }());
  3990. BABYLON.Matrix = Matrix;
  3991. var Plane = (function () {
  3992. /**
  3993. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3994. */
  3995. function Plane(a, b, c, d) {
  3996. this.normal = new Vector3(a, b, c);
  3997. this.d = d;
  3998. }
  3999. /**
  4000. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4001. */
  4002. Plane.prototype.asArray = function () {
  4003. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4004. };
  4005. // Methods
  4006. /**
  4007. * Returns a new plane copied from the current Plane.
  4008. */
  4009. Plane.prototype.clone = function () {
  4010. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4011. };
  4012. /**
  4013. * Returns the string "Plane".
  4014. */
  4015. Plane.prototype.getClassName = function () {
  4016. return "Plane";
  4017. };
  4018. /**
  4019. * Returns the Plane hash code.
  4020. */
  4021. Plane.prototype.getHashCode = function () {
  4022. var hash = this.normal.getHashCode();
  4023. hash = (hash * 397) ^ (this.d || 0);
  4024. return hash;
  4025. };
  4026. /**
  4027. * Normalize the current Plane in place.
  4028. * Returns the updated Plane.
  4029. */
  4030. Plane.prototype.normalize = function () {
  4031. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4032. var magnitude = 0.0;
  4033. if (norm !== 0) {
  4034. magnitude = 1.0 / norm;
  4035. }
  4036. this.normal.x *= magnitude;
  4037. this.normal.y *= magnitude;
  4038. this.normal.z *= magnitude;
  4039. this.d *= magnitude;
  4040. return this;
  4041. };
  4042. /**
  4043. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4044. */
  4045. Plane.prototype.transform = function (transformation) {
  4046. var transposedMatrix = Matrix.Transpose(transformation);
  4047. var x = this.normal.x;
  4048. var y = this.normal.y;
  4049. var z = this.normal.z;
  4050. var d = this.d;
  4051. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4052. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4053. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4054. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4055. return new Plane(normalX, normalY, normalZ, finalD);
  4056. };
  4057. /**
  4058. * Returns the dot product (float) of the point coordinates and the plane normal.
  4059. */
  4060. Plane.prototype.dotCoordinate = function (point) {
  4061. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4062. };
  4063. /**
  4064. * Updates the current Plane from the plane defined by the three passed points.
  4065. * Returns the updated Plane.
  4066. */
  4067. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4068. var x1 = point2.x - point1.x;
  4069. var y1 = point2.y - point1.y;
  4070. var z1 = point2.z - point1.z;
  4071. var x2 = point3.x - point1.x;
  4072. var y2 = point3.y - point1.y;
  4073. var z2 = point3.z - point1.z;
  4074. var yz = (y1 * z2) - (z1 * y2);
  4075. var xz = (z1 * x2) - (x1 * z2);
  4076. var xy = (x1 * y2) - (y1 * x2);
  4077. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4078. var invPyth;
  4079. if (pyth !== 0) {
  4080. invPyth = 1.0 / pyth;
  4081. }
  4082. else {
  4083. invPyth = 0.0;
  4084. }
  4085. this.normal.x = yz * invPyth;
  4086. this.normal.y = xz * invPyth;
  4087. this.normal.z = xy * invPyth;
  4088. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4089. return this;
  4090. };
  4091. /**
  4092. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4093. */
  4094. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4095. var dot = Vector3.Dot(this.normal, direction);
  4096. return (dot <= epsilon);
  4097. };
  4098. /**
  4099. * Returns the signed distance (float) from the passed point to the Plane.
  4100. */
  4101. Plane.prototype.signedDistanceTo = function (point) {
  4102. return Vector3.Dot(point, this.normal) + this.d;
  4103. };
  4104. // Statics
  4105. /**
  4106. * Returns a new Plane from the passed array.
  4107. */
  4108. Plane.FromArray = function (array) {
  4109. return new Plane(array[0], array[1], array[2], array[3]);
  4110. };
  4111. /**
  4112. * Returns a new Plane defined by the three passed points.
  4113. */
  4114. Plane.FromPoints = function (point1, point2, point3) {
  4115. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4116. result.copyFromPoints(point1, point2, point3);
  4117. return result;
  4118. };
  4119. /**
  4120. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4121. * Note : the vector "normal" is updated because normalized.
  4122. */
  4123. Plane.FromPositionAndNormal = function (origin, normal) {
  4124. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4125. normal.normalize();
  4126. result.normal = normal;
  4127. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4128. return result;
  4129. };
  4130. /**
  4131. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4132. */
  4133. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4134. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4135. return Vector3.Dot(point, normal) + d;
  4136. };
  4137. return Plane;
  4138. }());
  4139. BABYLON.Plane = Plane;
  4140. var Viewport = (function () {
  4141. /**
  4142. * Creates a Viewport object located at (x, y) and sized (width, height).
  4143. */
  4144. function Viewport(x, y, width, height) {
  4145. this.x = x;
  4146. this.y = y;
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4151. if (renderWidthOrEngine.getRenderWidth) {
  4152. var engine = renderWidthOrEngine;
  4153. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4154. }
  4155. var renderWidth = renderWidthOrEngine;
  4156. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4157. };
  4158. /**
  4159. * Returns a new Viewport copied from the current one.
  4160. */
  4161. Viewport.prototype.clone = function () {
  4162. return new Viewport(this.x, this.y, this.width, this.height);
  4163. };
  4164. return Viewport;
  4165. }());
  4166. BABYLON.Viewport = Viewport;
  4167. var Frustum = (function () {
  4168. function Frustum() {
  4169. }
  4170. /**
  4171. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4172. */
  4173. Frustum.GetPlanes = function (transform) {
  4174. var frustumPlanes = [];
  4175. for (var index = 0; index < 6; index++) {
  4176. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4177. }
  4178. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4179. return frustumPlanes;
  4180. };
  4181. /**
  4182. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4183. */
  4184. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4185. // Near
  4186. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4187. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4188. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4189. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4190. frustumPlanes[0].normalize();
  4191. // Far
  4192. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4193. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4194. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4195. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4196. frustumPlanes[1].normalize();
  4197. // Left
  4198. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4199. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4200. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4201. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4202. frustumPlanes[2].normalize();
  4203. // Right
  4204. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4205. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4206. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4207. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4208. frustumPlanes[3].normalize();
  4209. // Top
  4210. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4214. frustumPlanes[4].normalize();
  4215. // Bottom
  4216. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4217. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4218. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4219. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4220. frustumPlanes[5].normalize();
  4221. };
  4222. return Frustum;
  4223. }());
  4224. BABYLON.Frustum = Frustum;
  4225. var Space;
  4226. (function (Space) {
  4227. Space[Space["LOCAL"] = 0] = "LOCAL";
  4228. Space[Space["WORLD"] = 1] = "WORLD";
  4229. Space[Space["BONE"] = 2] = "BONE";
  4230. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4231. var Axis = (function () {
  4232. function Axis() {
  4233. }
  4234. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4235. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4236. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4237. return Axis;
  4238. }());
  4239. BABYLON.Axis = Axis;
  4240. ;
  4241. var BezierCurve = (function () {
  4242. function BezierCurve() {
  4243. }
  4244. /**
  4245. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4246. */
  4247. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4248. // Extract X (which is equal to time here)
  4249. var f0 = 1 - 3 * x2 + 3 * x1;
  4250. var f1 = 3 * x2 - 6 * x1;
  4251. var f2 = 3 * x1;
  4252. var refinedT = t;
  4253. for (var i = 0; i < 5; i++) {
  4254. var refinedT2 = refinedT * refinedT;
  4255. var refinedT3 = refinedT2 * refinedT;
  4256. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4257. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4258. refinedT -= (x - t) * slope;
  4259. refinedT = Math.min(1, Math.max(0, refinedT));
  4260. }
  4261. // Resolve cubic bezier for the given x
  4262. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4263. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4264. Math.pow(refinedT, 3);
  4265. };
  4266. return BezierCurve;
  4267. }());
  4268. BABYLON.BezierCurve = BezierCurve;
  4269. var Orientation;
  4270. (function (Orientation) {
  4271. Orientation[Orientation["CW"] = 0] = "CW";
  4272. Orientation[Orientation["CCW"] = 1] = "CCW";
  4273. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4274. var Angle = (function () {
  4275. /**
  4276. * Creates an Angle object of "radians" radians (float).
  4277. */
  4278. function Angle(radians) {
  4279. var _this = this;
  4280. /**
  4281. * Returns the Angle value in degrees (float).
  4282. */
  4283. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4284. /**
  4285. * Returns the Angle value in radians (float).
  4286. */
  4287. this.radians = function () { return _this._radians; };
  4288. this._radians = radians;
  4289. if (this._radians < 0.0)
  4290. this._radians += (2.0 * Math.PI);
  4291. }
  4292. /**
  4293. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4294. */
  4295. Angle.BetweenTwoPoints = function (a, b) {
  4296. var delta = b.subtract(a);
  4297. var theta = Math.atan2(delta.y, delta.x);
  4298. return new Angle(theta);
  4299. };
  4300. /**
  4301. * Returns a new Angle object from the passed float in radians.
  4302. */
  4303. Angle.FromRadians = function (radians) {
  4304. return new Angle(radians);
  4305. };
  4306. /**
  4307. * Returns a new Angle object from the passed float in degrees.
  4308. */
  4309. Angle.FromDegrees = function (degrees) {
  4310. return new Angle(degrees * Math.PI / 180.0);
  4311. };
  4312. return Angle;
  4313. }());
  4314. BABYLON.Angle = Angle;
  4315. var Arc2 = (function () {
  4316. /**
  4317. * Creates an Arc object from the three passed points : start, middle and end.
  4318. */
  4319. function Arc2(startPoint, midPoint, endPoint) {
  4320. this.startPoint = startPoint;
  4321. this.midPoint = midPoint;
  4322. this.endPoint = endPoint;
  4323. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4324. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4325. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4326. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4327. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4328. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4329. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4330. var a1 = this.startAngle.degrees();
  4331. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4332. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4333. // angles correction
  4334. if (a2 - a1 > +180.0)
  4335. a2 -= 360.0;
  4336. if (a2 - a1 < -180.0)
  4337. a2 += 360.0;
  4338. if (a3 - a2 > +180.0)
  4339. a3 -= 360.0;
  4340. if (a3 - a2 < -180.0)
  4341. a3 += 360.0;
  4342. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4343. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4344. }
  4345. return Arc2;
  4346. }());
  4347. BABYLON.Arc2 = Arc2;
  4348. var Path2 = (function () {
  4349. /**
  4350. * Creates a Path2 object from the starting 2D coordinates x and y.
  4351. */
  4352. function Path2(x, y) {
  4353. this._points = new Array();
  4354. this._length = 0.0;
  4355. this.closed = false;
  4356. this._points.push(new Vector2(x, y));
  4357. }
  4358. /**
  4359. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4360. * Returns the updated Path2.
  4361. */
  4362. Path2.prototype.addLineTo = function (x, y) {
  4363. if (closed) {
  4364. //Tools.Error("cannot add lines to closed paths");
  4365. return this;
  4366. }
  4367. var newPoint = new Vector2(x, y);
  4368. var previousPoint = this._points[this._points.length - 1];
  4369. this._points.push(newPoint);
  4370. this._length += newPoint.subtract(previousPoint).length();
  4371. return this;
  4372. };
  4373. /**
  4374. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4375. * Returns the updated Path2.
  4376. */
  4377. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4378. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4379. if (closed) {
  4380. //Tools.Error("cannot add arcs to closed paths");
  4381. return this;
  4382. }
  4383. var startPoint = this._points[this._points.length - 1];
  4384. var midPoint = new Vector2(midX, midY);
  4385. var endPoint = new Vector2(endX, endY);
  4386. var arc = new Arc2(startPoint, midPoint, endPoint);
  4387. var increment = arc.angle.radians() / numberOfSegments;
  4388. if (arc.orientation === Orientation.CW)
  4389. increment *= -1;
  4390. var currentAngle = arc.startAngle.radians() + increment;
  4391. for (var i = 0; i < numberOfSegments; i++) {
  4392. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4393. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4394. this.addLineTo(x, y);
  4395. currentAngle += increment;
  4396. }
  4397. return this;
  4398. };
  4399. /**
  4400. * Closes the Path2.
  4401. * Returns the Path2.
  4402. */
  4403. Path2.prototype.close = function () {
  4404. this.closed = true;
  4405. return this;
  4406. };
  4407. /**
  4408. * Returns the Path2 total length (float).
  4409. */
  4410. Path2.prototype.length = function () {
  4411. var result = this._length;
  4412. if (!this.closed) {
  4413. var lastPoint = this._points[this._points.length - 1];
  4414. var firstPoint = this._points[0];
  4415. result += (firstPoint.subtract(lastPoint).length());
  4416. }
  4417. return result;
  4418. };
  4419. /**
  4420. * Returns the Path2 internal array of points.
  4421. */
  4422. Path2.prototype.getPoints = function () {
  4423. return this._points;
  4424. };
  4425. /**
  4426. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4427. */
  4428. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4429. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4430. //Tools.Error("normalized length position should be between 0 and 1.");
  4431. return Vector2.Zero();
  4432. }
  4433. var lengthPosition = normalizedLengthPosition * this.length();
  4434. var previousOffset = 0;
  4435. for (var i = 0; i < this._points.length; i++) {
  4436. var j = (i + 1) % this._points.length;
  4437. var a = this._points[i];
  4438. var b = this._points[j];
  4439. var bToA = b.subtract(a);
  4440. var nextOffset = (bToA.length() + previousOffset);
  4441. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4442. var dir = bToA.normalize();
  4443. var localOffset = lengthPosition - previousOffset;
  4444. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4445. }
  4446. previousOffset = nextOffset;
  4447. }
  4448. //Tools.Error("internal error");
  4449. return Vector2.Zero();
  4450. };
  4451. /**
  4452. * Returns a new Path2 starting at the coordinates (x, y).
  4453. */
  4454. Path2.StartingAt = function (x, y) {
  4455. return new Path2(x, y);
  4456. };
  4457. return Path2;
  4458. }());
  4459. BABYLON.Path2 = Path2;
  4460. var Path3D = (function () {
  4461. /**
  4462. * new Path3D(path, normal, raw)
  4463. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4464. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4465. * path : an array of Vector3, the curve axis of the Path3D
  4466. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4467. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4468. */
  4469. function Path3D(path, firstNormal, raw) {
  4470. this.path = path;
  4471. this._curve = new Array();
  4472. this._distances = new Array();
  4473. this._tangents = new Array();
  4474. this._normals = new Array();
  4475. this._binormals = new Array();
  4476. for (var p = 0; p < path.length; p++) {
  4477. this._curve[p] = path[p].clone(); // hard copy
  4478. }
  4479. this._raw = raw || false;
  4480. this._compute(firstNormal);
  4481. }
  4482. /**
  4483. * Returns the Path3D array of successive Vector3 designing its curve.
  4484. */
  4485. Path3D.prototype.getCurve = function () {
  4486. return this._curve;
  4487. };
  4488. /**
  4489. * Returns an array populated with tangent vectors on each Path3D curve point.
  4490. */
  4491. Path3D.prototype.getTangents = function () {
  4492. return this._tangents;
  4493. };
  4494. /**
  4495. * Returns an array populated with normal vectors on each Path3D curve point.
  4496. */
  4497. Path3D.prototype.getNormals = function () {
  4498. return this._normals;
  4499. };
  4500. /**
  4501. * Returns an array populated with binormal vectors on each Path3D curve point.
  4502. */
  4503. Path3D.prototype.getBinormals = function () {
  4504. return this._binormals;
  4505. };
  4506. /**
  4507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4508. */
  4509. Path3D.prototype.getDistances = function () {
  4510. return this._distances;
  4511. };
  4512. /**
  4513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4514. * Returns the same object updated.
  4515. */
  4516. Path3D.prototype.update = function (path, firstNormal) {
  4517. for (var p = 0; p < path.length; p++) {
  4518. this._curve[p].x = path[p].x;
  4519. this._curve[p].y = path[p].y;
  4520. this._curve[p].z = path[p].z;
  4521. }
  4522. this._compute(firstNormal);
  4523. return this;
  4524. };
  4525. // private function compute() : computes tangents, normals and binormals
  4526. Path3D.prototype._compute = function (firstNormal) {
  4527. var l = this._curve.length;
  4528. // first and last tangents
  4529. this._tangents[0] = this._getFirstNonNullVector(0);
  4530. if (!this._raw) {
  4531. this._tangents[0].normalize();
  4532. }
  4533. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4534. if (!this._raw) {
  4535. this._tangents[l - 1].normalize();
  4536. }
  4537. // normals and binormals at first point : arbitrary vector with _normalVector()
  4538. var tg0 = this._tangents[0];
  4539. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4540. this._normals[0] = pp0;
  4541. if (!this._raw) {
  4542. this._normals[0].normalize();
  4543. }
  4544. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4545. if (!this._raw) {
  4546. this._binormals[0].normalize();
  4547. }
  4548. this._distances[0] = 0.0;
  4549. // normals and binormals : next points
  4550. var prev; // previous vector (segment)
  4551. var cur; // current vector (segment)
  4552. var curTang; // current tangent
  4553. // previous normal
  4554. var prevBinor; // previous binormal
  4555. for (var i = 1; i < l; i++) {
  4556. // tangents
  4557. prev = this._getLastNonNullVector(i);
  4558. if (i < l - 1) {
  4559. cur = this._getFirstNonNullVector(i);
  4560. this._tangents[i] = prev.add(cur);
  4561. this._tangents[i].normalize();
  4562. }
  4563. this._distances[i] = this._distances[i - 1] + prev.length();
  4564. // normals and binormals
  4565. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4566. curTang = this._tangents[i];
  4567. prevBinor = this._binormals[i - 1];
  4568. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4569. if (!this._raw) {
  4570. this._normals[i].normalize();
  4571. }
  4572. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4573. if (!this._raw) {
  4574. this._binormals[i].normalize();
  4575. }
  4576. }
  4577. };
  4578. // private function getFirstNonNullVector(index)
  4579. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4580. Path3D.prototype._getFirstNonNullVector = function (index) {
  4581. var i = 1;
  4582. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4583. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4584. i++;
  4585. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4586. }
  4587. return nNVector;
  4588. };
  4589. // private function getLastNonNullVector(index)
  4590. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4591. Path3D.prototype._getLastNonNullVector = function (index) {
  4592. var i = 1;
  4593. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4594. while (nLVector.length() === 0 && index > i + 1) {
  4595. i++;
  4596. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4597. }
  4598. return nLVector;
  4599. };
  4600. // private function normalVector(v0, vt, va) :
  4601. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4602. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4603. Path3D.prototype._normalVector = function (v0, vt, va) {
  4604. var normal0;
  4605. var tgl = vt.length();
  4606. if (tgl === 0.0) {
  4607. tgl = 1.0;
  4608. }
  4609. if (va === undefined || va === null) {
  4610. var point;
  4611. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4612. point = new Vector3(0.0, -1.0, 0.0);
  4613. }
  4614. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4615. point = new Vector3(1.0, 0.0, 0.0);
  4616. }
  4617. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4618. point = new Vector3(0.0, 0.0, 1.0);
  4619. }
  4620. normal0 = Vector3.Cross(vt, point);
  4621. }
  4622. else {
  4623. normal0 = Vector3.Cross(vt, va);
  4624. Vector3.CrossToRef(normal0, vt, normal0);
  4625. }
  4626. normal0.normalize();
  4627. return normal0;
  4628. };
  4629. return Path3D;
  4630. }());
  4631. BABYLON.Path3D = Path3D;
  4632. var Curve3 = (function () {
  4633. /**
  4634. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4635. * A Curve3 is designed from a series of successive Vector3.
  4636. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4637. */
  4638. function Curve3(points) {
  4639. this._length = 0.0;
  4640. this._points = points;
  4641. this._length = this._computeLength(points);
  4642. }
  4643. /**
  4644. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4645. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4646. * @param v1 (Vector3) the control point
  4647. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4648. * @param nbPoints (integer) the wanted number of points in the curve
  4649. */
  4650. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4651. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4652. var bez = new Array();
  4653. var equation = function (t, val0, val1, val2) {
  4654. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4655. return res;
  4656. };
  4657. for (var i = 0; i <= nbPoints; i++) {
  4658. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4659. }
  4660. return new Curve3(bez);
  4661. };
  4662. /**
  4663. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4664. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4665. * @param v1 (Vector3) the first control point
  4666. * @param v2 (Vector3) the second control point
  4667. * @param v3 (Vector3) the end point of the Cubic Bezier
  4668. * @param nbPoints (integer) the wanted number of points in the curve
  4669. */
  4670. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4671. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4672. var bez = new Array();
  4673. var equation = function (t, val0, val1, val2, val3) {
  4674. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4675. return res;
  4676. };
  4677. for (var i = 0; i <= nbPoints; i++) {
  4678. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4679. }
  4680. return new Curve3(bez);
  4681. };
  4682. /**
  4683. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4684. * @param p1 (Vector3) the origin point of the Hermite Spline
  4685. * @param t1 (Vector3) the tangent vector at the origin point
  4686. * @param p2 (Vector3) the end point of the Hermite Spline
  4687. * @param t2 (Vector3) the tangent vector at the end point
  4688. * @param nbPoints (integer) the wanted number of points in the curve
  4689. */
  4690. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4691. var hermite = new Array();
  4692. var step = 1.0 / nbPoints;
  4693. for (var i = 0; i <= nbPoints; i++) {
  4694. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4695. }
  4696. return new Curve3(hermite);
  4697. };
  4698. /**
  4699. * Returns a Curve3 object along a CatmullRom Spline curve :
  4700. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4701. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4702. */
  4703. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4704. var totalPoints = new Array();
  4705. totalPoints.push(points[0].clone());
  4706. Array.prototype.push.apply(totalPoints, points);
  4707. totalPoints.push(points[points.length - 1].clone());
  4708. var catmullRom = new Array();
  4709. var step = 1.0 / nbPoints;
  4710. for (var i = 0; i < totalPoints.length - 3; i++) {
  4711. var amount = 0.0;
  4712. for (var c = 0; c < nbPoints; c++) {
  4713. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4714. amount += step;
  4715. }
  4716. }
  4717. i--;
  4718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4719. return new Curve3(catmullRom);
  4720. };
  4721. /**
  4722. * Returns the Curve3 stored array of successive Vector3
  4723. */
  4724. Curve3.prototype.getPoints = function () {
  4725. return this._points;
  4726. };
  4727. /**
  4728. * Returns the computed length (float) of the curve.
  4729. */
  4730. Curve3.prototype.length = function () {
  4731. return this._length;
  4732. };
  4733. /**
  4734. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4735. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4736. * curveA and curveB keep unchanged.
  4737. */
  4738. Curve3.prototype.continue = function (curve) {
  4739. var lastPoint = this._points[this._points.length - 1];
  4740. var continuedPoints = this._points.slice();
  4741. var curvePoints = curve.getPoints();
  4742. for (var i = 1; i < curvePoints.length; i++) {
  4743. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4744. }
  4745. var continuedCurve = new Curve3(continuedPoints);
  4746. return continuedCurve;
  4747. };
  4748. Curve3.prototype._computeLength = function (path) {
  4749. var l = 0;
  4750. for (var i = 1; i < path.length; i++) {
  4751. l += (path[i].subtract(path[i - 1])).length();
  4752. }
  4753. return l;
  4754. };
  4755. return Curve3;
  4756. }());
  4757. BABYLON.Curve3 = Curve3;
  4758. // Vertex formats
  4759. var PositionNormalVertex = (function () {
  4760. function PositionNormalVertex(position, normal) {
  4761. if (position === void 0) { position = Vector3.Zero(); }
  4762. if (normal === void 0) { normal = Vector3.Up(); }
  4763. this.position = position;
  4764. this.normal = normal;
  4765. }
  4766. PositionNormalVertex.prototype.clone = function () {
  4767. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4768. };
  4769. return PositionNormalVertex;
  4770. }());
  4771. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4772. var PositionNormalTextureVertex = (function () {
  4773. function PositionNormalTextureVertex(position, normal, uv) {
  4774. if (position === void 0) { position = Vector3.Zero(); }
  4775. if (normal === void 0) { normal = Vector3.Up(); }
  4776. if (uv === void 0) { uv = Vector2.Zero(); }
  4777. this.position = position;
  4778. this.normal = normal;
  4779. this.uv = uv;
  4780. }
  4781. PositionNormalTextureVertex.prototype.clone = function () {
  4782. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4783. };
  4784. return PositionNormalTextureVertex;
  4785. }());
  4786. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4787. // Temporary pre-allocated objects for engine internal use
  4788. // usage in any internal function :
  4789. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4790. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4791. var Tmp = (function () {
  4792. function Tmp() {
  4793. }
  4794. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4795. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4796. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4797. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4798. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4799. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4800. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4801. Matrix.Zero(), Matrix.Zero(),
  4802. Matrix.Zero(), Matrix.Zero(),
  4803. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4804. return Tmp;
  4805. }());
  4806. BABYLON.Tmp = Tmp;
  4807. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4808. var MathTmp = (function () {
  4809. function MathTmp() {
  4810. }
  4811. MathTmp.Vector3 = [Vector3.Zero()];
  4812. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4813. MathTmp.Quaternion = [Quaternion.Zero()];
  4814. return MathTmp;
  4815. }());
  4816. })(BABYLON || (BABYLON = {}));
  4817. //# sourceMappingURL=babylon.math.js.map
  4818. var BABYLON;
  4819. (function (BABYLON) {
  4820. var Scalar = (function () {
  4821. function Scalar() {
  4822. }
  4823. /**
  4824. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4825. */
  4826. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4827. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4828. var num = a - b;
  4829. return -epsilon <= num && num <= epsilon;
  4830. };
  4831. /**
  4832. * Returns a string : the upper case translation of the number i to hexadecimal.
  4833. */
  4834. Scalar.ToHex = function (i) {
  4835. var str = i.toString(16);
  4836. if (i <= 15) {
  4837. return ("0" + str).toUpperCase();
  4838. }
  4839. return str.toUpperCase();
  4840. };
  4841. /**
  4842. * Returns -1 if value is negative and +1 is value is positive.
  4843. * Returns the value itself if it's equal to zero.
  4844. */
  4845. Scalar.Sign = function (value) {
  4846. value = +value; // convert to a number
  4847. if (value === 0 || isNaN(value))
  4848. return value;
  4849. return value > 0 ? 1 : -1;
  4850. };
  4851. /**
  4852. * Returns the value itself if it's between min and max.
  4853. * Returns min if the value is lower than min.
  4854. * Returns max if the value is greater than max.
  4855. */
  4856. Scalar.Clamp = function (value, min, max) {
  4857. if (min === void 0) { min = 0; }
  4858. if (max === void 0) { max = 1; }
  4859. return Math.min(max, Math.max(min, value));
  4860. };
  4861. /**
  4862. * Returns the log2 of value.
  4863. */
  4864. Scalar.Log2 = function (value) {
  4865. return Math.log(value) * Math.LOG2E;
  4866. };
  4867. /**
  4868. * Loops the value, so that it is never larger than length and never smaller than 0.
  4869. *
  4870. * This is similar to the modulo operator but it works with floating point numbers.
  4871. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4872. * With t = 5 and length = 2.5, the result would be 0.0.
  4873. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4874. */
  4875. Scalar.Repeat = function (value, length) {
  4876. return value - Math.floor(value / length) * length;
  4877. };
  4878. /**
  4879. * Normalize the value between 0.0 and 1.0 using min and max values
  4880. */
  4881. Scalar.Normalize = function (value, min, max) {
  4882. return (value - min) / (max - min);
  4883. };
  4884. /**
  4885. * Denormalize the value from 0.0 and 1.0 using min and max values
  4886. */
  4887. Scalar.Denormalize = function (normalized, min, max) {
  4888. return (normalized * (max - min) + min);
  4889. };
  4890. /**
  4891. * Calculates the shortest difference between two given angles given in degrees.
  4892. */
  4893. Scalar.DeltaAngle = function (current, target) {
  4894. var num = Scalar.Repeat(target - current, 360.0);
  4895. if (num > 180.0) {
  4896. num -= 360.0;
  4897. }
  4898. return num;
  4899. };
  4900. /**
  4901. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4902. *
  4903. * The returned value will move back and forth between 0 and length
  4904. */
  4905. Scalar.PingPong = function (tx, length) {
  4906. var t = Scalar.Repeat(tx, length * 2.0);
  4907. return length - Math.abs(t - length);
  4908. };
  4909. /**
  4910. * Interpolates between min and max with smoothing at the limits.
  4911. *
  4912. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4913. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4914. */
  4915. Scalar.SmoothStep = function (from, to, tx) {
  4916. var t = Scalar.Clamp(tx);
  4917. t = -2.0 * t * t * t + 3.0 * t * t;
  4918. return to * t + from * (1.0 - t);
  4919. };
  4920. /**
  4921. * Moves a value current towards target.
  4922. *
  4923. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4924. * Negative values of maxDelta pushes the value away from target.
  4925. */
  4926. Scalar.MoveTowards = function (current, target, maxDelta) {
  4927. var result = 0;
  4928. if (Math.abs(target - current) <= maxDelta) {
  4929. result = target;
  4930. }
  4931. else {
  4932. result = current + Scalar.Sign(target - current) * maxDelta;
  4933. }
  4934. return result;
  4935. };
  4936. /**
  4937. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4938. *
  4939. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4940. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4941. */
  4942. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4943. var num = Scalar.DeltaAngle(current, target);
  4944. var result = 0;
  4945. if (-maxDelta < num && num < maxDelta) {
  4946. result = target;
  4947. }
  4948. else {
  4949. target = current + num;
  4950. result = Scalar.MoveTowards(current, target, maxDelta);
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4956. */
  4957. Scalar.Lerp = function (start, end, amount) {
  4958. return start + ((end - start) * amount);
  4959. };
  4960. /**
  4961. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4962. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4963. */
  4964. Scalar.LerpAngle = function (start, end, amount) {
  4965. var num = Scalar.Repeat(end - start, 360.0);
  4966. if (num > 180.0) {
  4967. num -= 360.0;
  4968. }
  4969. return start + num * Scalar.Clamp(amount);
  4970. };
  4971. /**
  4972. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4973. */
  4974. Scalar.InverseLerp = function (a, b, value) {
  4975. var result = 0;
  4976. if (a != b) {
  4977. result = Scalar.Clamp((value - a) / (b - a));
  4978. }
  4979. else {
  4980. result = 0.0;
  4981. }
  4982. return result;
  4983. };
  4984. /**
  4985. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4986. */
  4987. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4988. var squared = amount * amount;
  4989. var cubed = amount * squared;
  4990. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4991. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4992. var part3 = (cubed - (2.0 * squared)) + amount;
  4993. var part4 = cubed - squared;
  4994. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4995. };
  4996. /**
  4997. * Returns a random float number between and min and max values
  4998. */
  4999. Scalar.RandomRange = function (min, max) {
  5000. if (min === max)
  5001. return min;
  5002. return ((Math.random() * (max - min)) + min);
  5003. };
  5004. /**
  5005. * This function returns percentage of a number in a given range.
  5006. *
  5007. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5008. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5009. */
  5010. Scalar.RangeToPercent = function (number, min, max) {
  5011. return ((number - min) / (max - min));
  5012. };
  5013. /**
  5014. * This function returns number that corresponds to the percentage in a given range.
  5015. *
  5016. * PercentToRange(0.34,0,100) will return 34.
  5017. */
  5018. Scalar.PercentToRange = function (percent, min, max) {
  5019. return ((max - min) * percent + min);
  5020. };
  5021. return Scalar;
  5022. }());
  5023. BABYLON.Scalar = Scalar;
  5024. })(BABYLON || (BABYLON = {}));
  5025. //# sourceMappingURL=babylon.math.scalar.js.map
  5026. //# sourceMappingURL=babylon.mixins.js.map
  5027. var BABYLON;
  5028. (function (BABYLON) {
  5029. var __decoratorInitialStore = {};
  5030. var __mergedStore = {};
  5031. var _copySource = function (creationFunction, source, instanciate) {
  5032. var destination = creationFunction();
  5033. // Tags
  5034. if (BABYLON.Tags) {
  5035. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5036. }
  5037. var classStore = getMergedStore(destination);
  5038. // Properties
  5039. for (var property in classStore) {
  5040. var propertyDescriptor = classStore[property];
  5041. var sourceProperty = source[property];
  5042. var propertyType = propertyDescriptor.type;
  5043. if (sourceProperty !== undefined && sourceProperty !== null) {
  5044. switch (propertyType) {
  5045. case 0: // Value
  5046. case 6:// Mesh reference
  5047. destination[property] = sourceProperty;
  5048. break;
  5049. case 1: // Texture
  5050. case 2: // Color3
  5051. case 3: // FresnelParameters
  5052. case 4: // Vector2
  5053. case 5: // Vector3
  5054. case 7:// Color Curves
  5055. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5056. break;
  5057. }
  5058. }
  5059. }
  5060. return destination;
  5061. };
  5062. function getDirectStore(target) {
  5063. var classKey = target.getClassName();
  5064. if (!__decoratorInitialStore[classKey]) {
  5065. __decoratorInitialStore[classKey] = {};
  5066. }
  5067. return __decoratorInitialStore[classKey];
  5068. }
  5069. /**
  5070. * Return the list of properties flagged as serializable
  5071. * @param target: host object
  5072. */
  5073. function getMergedStore(target) {
  5074. var classKey = target.getClassName();
  5075. if (__mergedStore[classKey]) {
  5076. return __mergedStore[classKey];
  5077. }
  5078. __mergedStore[classKey] = {};
  5079. var store = __mergedStore[classKey];
  5080. var currentTarget = target;
  5081. var currentKey = classKey;
  5082. while (currentKey) {
  5083. var initialStore = __decoratorInitialStore[currentKey];
  5084. for (var property in initialStore) {
  5085. store[property] = initialStore[property];
  5086. }
  5087. var parent_1 = void 0;
  5088. var done = false;
  5089. do {
  5090. parent_1 = Object.getPrototypeOf(currentTarget);
  5091. if (!parent_1.getClassName) {
  5092. done = true;
  5093. break;
  5094. }
  5095. if (parent_1.getClassName() !== currentKey) {
  5096. break;
  5097. }
  5098. currentTarget = parent_1;
  5099. } while (parent_1);
  5100. if (done) {
  5101. break;
  5102. }
  5103. currentKey = parent_1.getClassName();
  5104. currentTarget = parent_1;
  5105. }
  5106. return store;
  5107. }
  5108. function generateSerializableMember(type, sourceName) {
  5109. return function (target, propertyKey) {
  5110. var classStore = getDirectStore(target);
  5111. if (!classStore[propertyKey]) {
  5112. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5113. }
  5114. };
  5115. }
  5116. function generateExpandMember(setCallback, targetKey) {
  5117. return function (target, propertyKey) {
  5118. var key = targetKey || ("_" + propertyKey);
  5119. Object.defineProperty(target, propertyKey, {
  5120. get: function () {
  5121. return this[key];
  5122. },
  5123. set: function (value) {
  5124. if (this[key] === value) {
  5125. return;
  5126. }
  5127. this[key] = value;
  5128. target[setCallback].apply(this);
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. };
  5134. }
  5135. function expandToProperty(callback, targetKey) {
  5136. return generateExpandMember(callback, targetKey);
  5137. }
  5138. BABYLON.expandToProperty = expandToProperty;
  5139. function serialize(sourceName) {
  5140. return generateSerializableMember(0, sourceName); // value member
  5141. }
  5142. BABYLON.serialize = serialize;
  5143. function serializeAsTexture(sourceName) {
  5144. return generateSerializableMember(1, sourceName); // texture member
  5145. }
  5146. BABYLON.serializeAsTexture = serializeAsTexture;
  5147. function serializeAsColor3(sourceName) {
  5148. return generateSerializableMember(2, sourceName); // color3 member
  5149. }
  5150. BABYLON.serializeAsColor3 = serializeAsColor3;
  5151. function serializeAsFresnelParameters(sourceName) {
  5152. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5153. }
  5154. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5155. function serializeAsVector2(sourceName) {
  5156. return generateSerializableMember(4, sourceName); // vector2 member
  5157. }
  5158. BABYLON.serializeAsVector2 = serializeAsVector2;
  5159. function serializeAsVector3(sourceName) {
  5160. return generateSerializableMember(5, sourceName); // vector3 member
  5161. }
  5162. BABYLON.serializeAsVector3 = serializeAsVector3;
  5163. function serializeAsMeshReference(sourceName) {
  5164. return generateSerializableMember(6, sourceName); // mesh reference member
  5165. }
  5166. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5167. function serializeAsColorCurves(sourceName) {
  5168. return generateSerializableMember(7, sourceName); // color curves
  5169. }
  5170. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5171. function serializeAsColor4(sourceName) {
  5172. return generateSerializableMember(8, sourceName); // color 4
  5173. }
  5174. BABYLON.serializeAsColor4 = serializeAsColor4;
  5175. function serializeAsImageProcessingConfiguration(sourceName) {
  5176. return generateSerializableMember(9, sourceName); // image processing
  5177. }
  5178. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5179. var SerializationHelper = (function () {
  5180. function SerializationHelper() {
  5181. }
  5182. SerializationHelper.Serialize = function (entity, serializationObject) {
  5183. if (!serializationObject) {
  5184. serializationObject = {};
  5185. }
  5186. // Tags
  5187. if (BABYLON.Tags) {
  5188. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5189. }
  5190. var serializedProperties = getMergedStore(entity);
  5191. // Properties
  5192. for (var property in serializedProperties) {
  5193. var propertyDescriptor = serializedProperties[property];
  5194. var targetPropertyName = propertyDescriptor.sourceName || property;
  5195. var propertyType = propertyDescriptor.type;
  5196. var sourceProperty = entity[property];
  5197. if (sourceProperty !== undefined && sourceProperty !== null) {
  5198. switch (propertyType) {
  5199. case 0:// Value
  5200. serializationObject[targetPropertyName] = sourceProperty;
  5201. break;
  5202. case 1:// Texture
  5203. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5204. break;
  5205. case 2:// Color3
  5206. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5207. break;
  5208. case 3:// FresnelParameters
  5209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5210. break;
  5211. case 4:// Vector2
  5212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5213. break;
  5214. case 5:// Vector3
  5215. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5216. break;
  5217. case 6:// Mesh reference
  5218. serializationObject[targetPropertyName] = sourceProperty.id;
  5219. break;
  5220. case 7:// Color Curves
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 8:// Color 4
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 9:// Image Processing
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. }
  5230. }
  5231. }
  5232. return serializationObject;
  5233. };
  5234. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5235. var destination = creationFunction();
  5236. // Tags
  5237. if (BABYLON.Tags) {
  5238. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5239. }
  5240. var classStore = getMergedStore(destination);
  5241. // Properties
  5242. for (var property in classStore) {
  5243. var propertyDescriptor = classStore[property];
  5244. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5245. var propertyType = propertyDescriptor.type;
  5246. if (sourceProperty !== undefined && sourceProperty !== null) {
  5247. switch (propertyType) {
  5248. case 0:// Value
  5249. destination[property] = sourceProperty;
  5250. break;
  5251. case 1:// Texture
  5252. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5253. break;
  5254. case 2:// Color3
  5255. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5256. break;
  5257. case 3:// FresnelParameters
  5258. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5259. break;
  5260. case 4:// Vector2
  5261. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5262. break;
  5263. case 5:// Vector3
  5264. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5265. break;
  5266. case 6:// Mesh reference
  5267. destination[property] = scene.getLastMeshByID(sourceProperty);
  5268. break;
  5269. case 7:// Color Curves
  5270. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5271. break;
  5272. case 8:// Color 4
  5273. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5274. break;
  5275. case 9:// Image Processing
  5276. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5277. break;
  5278. }
  5279. }
  5280. }
  5281. return destination;
  5282. };
  5283. SerializationHelper.Clone = function (creationFunction, source) {
  5284. return _copySource(creationFunction, source, false);
  5285. };
  5286. SerializationHelper.Instanciate = function (creationFunction, source) {
  5287. return _copySource(creationFunction, source, true);
  5288. };
  5289. return SerializationHelper;
  5290. }());
  5291. BABYLON.SerializationHelper = SerializationHelper;
  5292. })(BABYLON || (BABYLON = {}));
  5293. //# sourceMappingURL=babylon.decorators.js.map
  5294. var BABYLON;
  5295. (function (BABYLON) {
  5296. /**
  5297. * A class serves as a medium between the observable and its observers
  5298. */
  5299. var EventState = (function () {
  5300. /**
  5301. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5302. */
  5303. function EventState(mask, skipNextObservers) {
  5304. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5305. this.initalize(mask, skipNextObservers);
  5306. }
  5307. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5308. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5309. this.mask = mask;
  5310. this.skipNextObservers = skipNextObservers;
  5311. return this;
  5312. };
  5313. return EventState;
  5314. }());
  5315. BABYLON.EventState = EventState;
  5316. /**
  5317. * Represent an Observer registered to a given Observable object.
  5318. */
  5319. var Observer = (function () {
  5320. function Observer(callback, mask) {
  5321. this.callback = callback;
  5322. this.mask = mask;
  5323. }
  5324. return Observer;
  5325. }());
  5326. BABYLON.Observer = Observer;
  5327. /**
  5328. * The Observable class is a simple implementation of the Observable pattern.
  5329. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5330. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5331. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5332. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5333. */
  5334. var Observable = (function () {
  5335. function Observable() {
  5336. this._observers = new Array();
  5337. this._eventState = new EventState(0);
  5338. }
  5339. /**
  5340. * Create a new Observer with the specified callback
  5341. * @param callback the callback that will be executed for that Observer
  5342. * @param mask the mask used to filter observers
  5343. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5344. */
  5345. Observable.prototype.add = function (callback, mask, insertFirst) {
  5346. if (mask === void 0) { mask = -1; }
  5347. if (insertFirst === void 0) { insertFirst = false; }
  5348. if (!callback) {
  5349. return null;
  5350. }
  5351. var observer = new Observer(callback, mask);
  5352. if (insertFirst) {
  5353. this._observers.unshift(observer);
  5354. }
  5355. else {
  5356. this._observers.push(observer);
  5357. }
  5358. return observer;
  5359. };
  5360. /**
  5361. * Remove an Observer from the Observable object
  5362. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5363. */
  5364. Observable.prototype.remove = function (observer) {
  5365. var index = this._observers.indexOf(observer);
  5366. if (index !== -1) {
  5367. this._observers.splice(index, 1);
  5368. return true;
  5369. }
  5370. return false;
  5371. };
  5372. /**
  5373. * Remove a callback from the Observable object
  5374. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5375. */
  5376. Observable.prototype.removeCallback = function (callback) {
  5377. for (var index = 0; index < this._observers.length; index++) {
  5378. if (this._observers[index].callback === callback) {
  5379. this._observers.splice(index, 1);
  5380. return true;
  5381. }
  5382. }
  5383. return false;
  5384. };
  5385. /**
  5386. * Notify all Observers by calling their respective callback with the given data
  5387. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5388. * @param eventData
  5389. * @param mask
  5390. */
  5391. Observable.prototype.notifyObservers = function (eventData, mask) {
  5392. if (mask === void 0) { mask = -1; }
  5393. var state = this._eventState;
  5394. state.mask = mask;
  5395. state.skipNextObservers = false;
  5396. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5397. var obs = _a[_i];
  5398. if (obs.mask & mask) {
  5399. obs.callback(eventData, state);
  5400. }
  5401. if (state.skipNextObservers) {
  5402. return false;
  5403. }
  5404. }
  5405. return true;
  5406. };
  5407. /**
  5408. * return true is the Observable has at least one Observer registered
  5409. */
  5410. Observable.prototype.hasObservers = function () {
  5411. return this._observers.length > 0;
  5412. };
  5413. /**
  5414. * Clear the list of observers
  5415. */
  5416. Observable.prototype.clear = function () {
  5417. this._observers = new Array();
  5418. };
  5419. /**
  5420. * Clone the current observable
  5421. */
  5422. Observable.prototype.clone = function () {
  5423. var result = new Observable();
  5424. result._observers = this._observers.slice(0);
  5425. return result;
  5426. };
  5427. /**
  5428. * Does this observable handles observer registered with a given mask
  5429. * @param {number} trigger - the mask to be tested
  5430. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5431. **/
  5432. Observable.prototype.hasSpecificMask = function (mask) {
  5433. if (mask === void 0) { mask = -1; }
  5434. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5435. var obs = _a[_i];
  5436. if (obs.mask & mask || obs.mask === mask) {
  5437. return true;
  5438. }
  5439. }
  5440. return false;
  5441. };
  5442. return Observable;
  5443. }());
  5444. BABYLON.Observable = Observable;
  5445. })(BABYLON || (BABYLON = {}));
  5446. //# sourceMappingURL=babylon.observable.js.map
  5447. var BABYLON;
  5448. (function (BABYLON) {
  5449. var SmartArray = (function () {
  5450. function SmartArray(capacity) {
  5451. this.length = 0;
  5452. this._duplicateId = 0;
  5453. this.data = new Array(capacity);
  5454. this._id = SmartArray._GlobalId++;
  5455. }
  5456. SmartArray.prototype.push = function (value) {
  5457. this.data[this.length++] = value;
  5458. if (this.length > this.data.length) {
  5459. this.data.length *= 2;
  5460. }
  5461. if (!value.__smartArrayFlags) {
  5462. value.__smartArrayFlags = {};
  5463. }
  5464. value.__smartArrayFlags[this._id] = this._duplicateId;
  5465. };
  5466. SmartArray.prototype.forEach = function (func) {
  5467. for (var index = 0; index < this.length; index++) {
  5468. func(this.data[index]);
  5469. }
  5470. };
  5471. SmartArray.prototype.pushNoDuplicate = function (value) {
  5472. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5473. return false;
  5474. }
  5475. this.push(value);
  5476. return true;
  5477. };
  5478. SmartArray.prototype.sort = function (compareFn) {
  5479. this.data.sort(compareFn);
  5480. };
  5481. SmartArray.prototype.reset = function () {
  5482. this.length = 0;
  5483. this._duplicateId++;
  5484. };
  5485. SmartArray.prototype.dispose = function () {
  5486. this.reset();
  5487. if (this.data) {
  5488. this.data.length = 0;
  5489. this.data = null;
  5490. }
  5491. };
  5492. SmartArray.prototype.concat = function (array) {
  5493. if (array.length === 0) {
  5494. return;
  5495. }
  5496. if (this.length + array.length > this.data.length) {
  5497. this.data.length = (this.length + array.length) * 2;
  5498. }
  5499. for (var index = 0; index < array.length; index++) {
  5500. this.data[this.length++] = (array.data || array)[index];
  5501. }
  5502. };
  5503. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5504. if (array.length === 0) {
  5505. return;
  5506. }
  5507. if (this.length + array.length > this.data.length) {
  5508. this.data.length = (this.length + array.length) * 2;
  5509. }
  5510. for (var index = 0; index < array.length; index++) {
  5511. var item = (array.data || array)[index];
  5512. this.pushNoDuplicate(item);
  5513. }
  5514. };
  5515. SmartArray.prototype.indexOf = function (value) {
  5516. var position = this.data.indexOf(value);
  5517. if (position >= this.length) {
  5518. return -1;
  5519. }
  5520. return position;
  5521. };
  5522. SmartArray.prototype.contains = function (value) {
  5523. return this.data.indexOf(value) !== -1;
  5524. };
  5525. // Statics
  5526. SmartArray._GlobalId = 0;
  5527. return SmartArray;
  5528. }());
  5529. BABYLON.SmartArray = SmartArray;
  5530. })(BABYLON || (BABYLON = {}));
  5531. //# sourceMappingURL=babylon.smartArray.js.map
  5532. var BABYLON;
  5533. (function (BABYLON) {
  5534. // Screenshots
  5535. var screenshotCanvas;
  5536. var cloneValue = function (source, destinationObject) {
  5537. if (!source)
  5538. return null;
  5539. if (source instanceof BABYLON.Mesh) {
  5540. return null;
  5541. }
  5542. if (source instanceof BABYLON.SubMesh) {
  5543. return source.clone(destinationObject);
  5544. }
  5545. else if (source.clone) {
  5546. return source.clone();
  5547. }
  5548. return null;
  5549. };
  5550. var Tools = (function () {
  5551. function Tools() {
  5552. }
  5553. ;
  5554. /**
  5555. * Interpolates between a and b via alpha
  5556. * @param a The lower value (returned when alpha = 0)
  5557. * @param b The upper value (returned when alpha = 1)
  5558. * @param alpha The interpolation-factor
  5559. * @return The mixed value
  5560. */
  5561. Tools.Mix = function (a, b, alpha) {
  5562. return a * (1 - alpha) + b * alpha;
  5563. };
  5564. Tools.Instantiate = function (className) {
  5565. var arr = className.split(".");
  5566. var fn = (window || this);
  5567. for (var i = 0, len = arr.length; i < len; i++) {
  5568. fn = fn[arr[i]];
  5569. }
  5570. if (typeof fn !== "function") {
  5571. return null;
  5572. }
  5573. return fn;
  5574. };
  5575. Tools.SetImmediate = function (action) {
  5576. if (window.setImmediate) {
  5577. window.setImmediate(action);
  5578. }
  5579. else {
  5580. setTimeout(action, 1);
  5581. }
  5582. };
  5583. Tools.IsExponentOfTwo = function (value) {
  5584. var count = 1;
  5585. do {
  5586. count *= 2;
  5587. } while (count < value);
  5588. return count === value;
  5589. };
  5590. /**
  5591. * Find the next highest power of two.
  5592. * @param x Number to start search from.
  5593. * @return Next highest power of two.
  5594. */
  5595. Tools.CeilingPOT = function (x) {
  5596. x--;
  5597. x |= x >> 1;
  5598. x |= x >> 2;
  5599. x |= x >> 4;
  5600. x |= x >> 8;
  5601. x |= x >> 16;
  5602. x++;
  5603. return x;
  5604. };
  5605. /**
  5606. * Find the next lowest power of two.
  5607. * @param x Number to start search from.
  5608. * @return Next lowest power of two.
  5609. */
  5610. Tools.FloorPOT = function (x) {
  5611. x = x | (x >> 1);
  5612. x = x | (x >> 2);
  5613. x = x | (x >> 4);
  5614. x = x | (x >> 8);
  5615. x = x | (x >> 16);
  5616. return x - (x >> 1);
  5617. };
  5618. /**
  5619. * Find the nearest power of two.
  5620. * @param x Number to start search from.
  5621. * @return Next nearest power of two.
  5622. */
  5623. Tools.NearestPOT = function (x) {
  5624. var c = Tools.CeilingPOT(x);
  5625. var f = Tools.FloorPOT(x);
  5626. return (c - x) > (x - f) ? f : c;
  5627. };
  5628. Tools.GetExponentOfTwo = function (value, max, mode) {
  5629. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5630. var pot;
  5631. switch (mode) {
  5632. case BABYLON.Engine.SCALEMODE_FLOOR:
  5633. pot = Tools.FloorPOT(value);
  5634. break;
  5635. case BABYLON.Engine.SCALEMODE_NEAREST:
  5636. pot = Tools.NearestPOT(value);
  5637. break;
  5638. case BABYLON.Engine.SCALEMODE_CEILING:
  5639. pot = Tools.CeilingPOT(value);
  5640. break;
  5641. }
  5642. return Math.min(pot, max);
  5643. };
  5644. Tools.GetFilename = function (path) {
  5645. var index = path.lastIndexOf("/");
  5646. if (index < 0)
  5647. return path;
  5648. return path.substring(index + 1);
  5649. };
  5650. Tools.GetDOMTextContent = function (element) {
  5651. var result = "";
  5652. var child = element.firstChild;
  5653. while (child) {
  5654. if (child.nodeType === 3) {
  5655. result += child.textContent;
  5656. }
  5657. child = child.nextSibling;
  5658. }
  5659. return result;
  5660. };
  5661. Tools.ToDegrees = function (angle) {
  5662. return angle * 180 / Math.PI;
  5663. };
  5664. Tools.ToRadians = function (angle) {
  5665. return angle * Math.PI / 180;
  5666. };
  5667. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5668. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5669. var output = "";
  5670. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5671. var i = 0;
  5672. var bytes = new Uint8Array(buffer);
  5673. while (i < bytes.length) {
  5674. chr1 = bytes[i++];
  5675. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5676. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5677. enc1 = chr1 >> 2;
  5678. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5679. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5680. enc4 = chr3 & 63;
  5681. if (isNaN(chr2)) {
  5682. enc3 = enc4 = 64;
  5683. }
  5684. else if (isNaN(chr3)) {
  5685. enc4 = 64;
  5686. }
  5687. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5688. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5689. }
  5690. return "data:image/png;base64," + output;
  5691. };
  5692. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5693. if (bias === void 0) { bias = null; }
  5694. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5695. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5696. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5697. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5698. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5699. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5700. }
  5701. if (bias) {
  5702. minimum.x -= minimum.x * bias.x + bias.y;
  5703. minimum.y -= minimum.y * bias.x + bias.y;
  5704. minimum.z -= minimum.z * bias.x + bias.y;
  5705. maximum.x += maximum.x * bias.x + bias.y;
  5706. maximum.y += maximum.y * bias.x + bias.y;
  5707. maximum.z += maximum.z * bias.x + bias.y;
  5708. }
  5709. return {
  5710. minimum: minimum,
  5711. maximum: maximum
  5712. };
  5713. };
  5714. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5715. if (bias === void 0) { bias = null; }
  5716. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5717. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5718. if (!stride) {
  5719. stride = 3;
  5720. }
  5721. for (var index = start; index < start + count; index++) {
  5722. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5723. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5724. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5725. }
  5726. if (bias) {
  5727. minimum.x -= minimum.x * bias.x + bias.y;
  5728. minimum.y -= minimum.y * bias.x + bias.y;
  5729. minimum.z -= minimum.z * bias.x + bias.y;
  5730. maximum.x += maximum.x * bias.x + bias.y;
  5731. maximum.y += maximum.y * bias.x + bias.y;
  5732. maximum.z += maximum.z * bias.x + bias.y;
  5733. }
  5734. return {
  5735. minimum: minimum,
  5736. maximum: maximum
  5737. };
  5738. };
  5739. Tools.Vector2ArrayFeeder = function (array) {
  5740. return function (index) {
  5741. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5742. var length = isFloatArray ? array.length / 2 : array.length;
  5743. if (index >= length) {
  5744. return null;
  5745. }
  5746. if (isFloatArray) {
  5747. var fa = array;
  5748. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5749. }
  5750. var a = array;
  5751. return a[index];
  5752. };
  5753. };
  5754. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5755. if (bias === void 0) { bias = null; }
  5756. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5757. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5758. var i = 0;
  5759. var cur = feeder(i++);
  5760. while (cur) {
  5761. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5762. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5763. cur = feeder(i++);
  5764. }
  5765. if (bias) {
  5766. minimum.x -= minimum.x * bias.x + bias.y;
  5767. minimum.y -= minimum.y * bias.x + bias.y;
  5768. maximum.x += maximum.x * bias.x + bias.y;
  5769. maximum.y += maximum.y * bias.x + bias.y;
  5770. }
  5771. return {
  5772. minimum: minimum,
  5773. maximum: maximum
  5774. };
  5775. };
  5776. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5777. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5778. return undefined;
  5779. return Array.isArray(obj) ? obj : [obj];
  5780. };
  5781. // Misc.
  5782. Tools.GetPointerPrefix = function () {
  5783. var eventPrefix = "pointer";
  5784. // Check if pointer events are supported
  5785. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5786. eventPrefix = "mouse";
  5787. }
  5788. return eventPrefix;
  5789. };
  5790. /**
  5791. * @param func - the function to be called
  5792. * @param requester - the object that will request the next frame. Falls back to window.
  5793. */
  5794. Tools.QueueNewFrame = function (func, requester) {
  5795. if (requester === void 0) { requester = window; }
  5796. if (requester.requestAnimationFrame) {
  5797. return requester.requestAnimationFrame(func);
  5798. }
  5799. else if (requester.msRequestAnimationFrame) {
  5800. return requester.msRequestAnimationFrame(func);
  5801. }
  5802. else if (requester.webkitRequestAnimationFrame) {
  5803. return requester.webkitRequestAnimationFrame(func);
  5804. }
  5805. else if (requester.mozRequestAnimationFrame) {
  5806. return requester.mozRequestAnimationFrame(func);
  5807. }
  5808. else if (requester.oRequestAnimationFrame) {
  5809. return requester.oRequestAnimationFrame(func);
  5810. }
  5811. else {
  5812. return window.setTimeout(func, 16);
  5813. }
  5814. };
  5815. Tools.RequestFullscreen = function (element) {
  5816. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5817. if (!requestFunction)
  5818. return;
  5819. requestFunction.call(element);
  5820. };
  5821. Tools.ExitFullscreen = function () {
  5822. if (document.exitFullscreen) {
  5823. document.exitFullscreen();
  5824. }
  5825. else if (document.mozCancelFullScreen) {
  5826. document.mozCancelFullScreen();
  5827. }
  5828. else if (document.webkitCancelFullScreen) {
  5829. document.webkitCancelFullScreen();
  5830. }
  5831. else if (document.msCancelFullScreen) {
  5832. document.msCancelFullScreen();
  5833. }
  5834. };
  5835. Tools.SetCorsBehavior = function (url, img) {
  5836. if (Tools.CorsBehavior) {
  5837. switch (typeof (Tools.CorsBehavior)) {
  5838. case "function":
  5839. var result = Tools.CorsBehavior(url);
  5840. if (result) {
  5841. img.crossOrigin = result;
  5842. }
  5843. break;
  5844. case "string":
  5845. default:
  5846. img.crossOrigin = Tools.CorsBehavior;
  5847. break;
  5848. }
  5849. }
  5850. };
  5851. // External files
  5852. Tools.CleanUrl = function (url) {
  5853. url = url.replace(/#/mg, "%23");
  5854. return url;
  5855. };
  5856. Tools.LoadImage = function (url, onload, onerror, database) {
  5857. if (url instanceof ArrayBuffer) {
  5858. url = Tools.EncodeArrayBufferTobase64(url);
  5859. }
  5860. url = Tools.CleanUrl(url);
  5861. url = Tools.PreprocessUrl(url);
  5862. var img = new Image();
  5863. if (url.substr(0, 5) !== "data:") {
  5864. Tools.SetCorsBehavior(url, img);
  5865. }
  5866. img.onload = function () {
  5867. onload(img);
  5868. };
  5869. img.onerror = function (err) {
  5870. Tools.Error("Error while trying to load image: " + url);
  5871. if (Tools.UseFallbackTexture) {
  5872. img.src = Tools.fallbackTexture;
  5873. onload(img);
  5874. }
  5875. else {
  5876. onerror();
  5877. }
  5878. };
  5879. var noIndexedDB = function () {
  5880. img.src = url;
  5881. };
  5882. var loadFromIndexedDB = function () {
  5883. database.loadImageFromDB(url, img);
  5884. };
  5885. //ANY database to do!
  5886. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5887. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5888. }
  5889. else {
  5890. if (url.indexOf("file:") !== 0) {
  5891. noIndexedDB();
  5892. }
  5893. else {
  5894. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5895. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5896. try {
  5897. var blobURL;
  5898. try {
  5899. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5900. }
  5901. catch (ex) {
  5902. // Chrome doesn't support oneTimeOnly parameter
  5903. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5904. }
  5905. img.src = blobURL;
  5906. }
  5907. catch (e) {
  5908. img.src = null;
  5909. }
  5910. }
  5911. else {
  5912. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5913. img.src = Tools.fallbackTexture;
  5914. }
  5915. }
  5916. }
  5917. return img;
  5918. };
  5919. //ANY
  5920. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5921. url = Tools.CleanUrl(url);
  5922. url = Tools.PreprocessUrl(url);
  5923. var noIndexedDB = function () {
  5924. var request = new XMLHttpRequest();
  5925. var loadUrl = Tools.BaseUrl + url;
  5926. request.open('GET', loadUrl, true);
  5927. if (useArrayBuffer) {
  5928. request.responseType = "arraybuffer";
  5929. }
  5930. request.onprogress = progressCallBack;
  5931. request.onreadystatechange = function () {
  5932. // In case of undefined state in some browsers.
  5933. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5934. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5935. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5936. callback(!useArrayBuffer ? request.responseText : request.response);
  5937. }
  5938. else {
  5939. if (onError) {
  5940. onError(request);
  5941. }
  5942. else {
  5943. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5944. }
  5945. }
  5946. }
  5947. };
  5948. request.send(null);
  5949. };
  5950. var loadFromIndexedDB = function () {
  5951. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5952. };
  5953. if (url.indexOf("file:") !== -1) {
  5954. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5955. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5956. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5957. }
  5958. else {
  5959. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5960. }
  5961. }
  5962. else {
  5963. // Caching all files
  5964. if (database && database.enableSceneOffline) {
  5965. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5966. }
  5967. else {
  5968. noIndexedDB();
  5969. }
  5970. }
  5971. };
  5972. /**
  5973. * Load a script (identified by an url). When the url returns, the
  5974. * content of this file is added into a new script element, attached to the DOM (body element)
  5975. */
  5976. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5977. var head = document.getElementsByTagName('head')[0];
  5978. var script = document.createElement('script');
  5979. script.type = 'text/javascript';
  5980. script.src = scriptUrl;
  5981. var self = this;
  5982. script.onload = function () {
  5983. if (onSuccess) {
  5984. onSuccess();
  5985. }
  5986. };
  5987. script.onerror = function () {
  5988. if (onError) {
  5989. onError();
  5990. }
  5991. };
  5992. head.appendChild(script);
  5993. };
  5994. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5995. var reader = new FileReader();
  5996. reader.onload = function (e) {
  5997. //target doesn't have result from ts 1.3
  5998. callback(e.target['result']);
  5999. };
  6000. reader.onprogress = progressCallback;
  6001. reader.readAsDataURL(fileToLoad);
  6002. };
  6003. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6004. var reader = new FileReader();
  6005. reader.onerror = function (e) {
  6006. Tools.Log("Error while reading file: " + fileToLoad.name);
  6007. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6008. };
  6009. reader.onload = function (e) {
  6010. //target doesn't have result from ts 1.3
  6011. callback(e.target['result']);
  6012. };
  6013. reader.onprogress = progressCallBack;
  6014. if (!useArrayBuffer) {
  6015. // Asynchronous read
  6016. reader.readAsText(fileToLoad);
  6017. }
  6018. else {
  6019. reader.readAsArrayBuffer(fileToLoad);
  6020. }
  6021. };
  6022. //returns a downloadable url to a file content.
  6023. Tools.FileAsURL = function (content) {
  6024. var fileBlob = new Blob([content]);
  6025. var url = window.URL || window.webkitURL;
  6026. var link = url.createObjectURL(fileBlob);
  6027. return link;
  6028. };
  6029. // Misc.
  6030. Tools.Format = function (value, decimals) {
  6031. if (decimals === void 0) { decimals = 2; }
  6032. return value.toFixed(decimals);
  6033. };
  6034. Tools.CheckExtends = function (v, min, max) {
  6035. if (v.x < min.x)
  6036. min.x = v.x;
  6037. if (v.y < min.y)
  6038. min.y = v.y;
  6039. if (v.z < min.z)
  6040. min.z = v.z;
  6041. if (v.x > max.x)
  6042. max.x = v.x;
  6043. if (v.y > max.y)
  6044. max.y = v.y;
  6045. if (v.z > max.z)
  6046. max.z = v.z;
  6047. };
  6048. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6049. for (var prop in source) {
  6050. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6051. continue;
  6052. }
  6053. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6054. continue;
  6055. }
  6056. var sourceValue = source[prop];
  6057. var typeOfSourceValue = typeof sourceValue;
  6058. if (typeOfSourceValue === "function") {
  6059. continue;
  6060. }
  6061. if (typeOfSourceValue === "object") {
  6062. if (sourceValue instanceof Array) {
  6063. destination[prop] = [];
  6064. if (sourceValue.length > 0) {
  6065. if (typeof sourceValue[0] == "object") {
  6066. for (var index = 0; index < sourceValue.length; index++) {
  6067. var clonedValue = cloneValue(sourceValue[index], destination);
  6068. if (destination[prop].indexOf(clonedValue) === -1) {
  6069. destination[prop].push(clonedValue);
  6070. }
  6071. }
  6072. }
  6073. else {
  6074. destination[prop] = sourceValue.slice(0);
  6075. }
  6076. }
  6077. }
  6078. else {
  6079. destination[prop] = cloneValue(sourceValue, destination);
  6080. }
  6081. }
  6082. else {
  6083. destination[prop] = sourceValue;
  6084. }
  6085. }
  6086. };
  6087. Tools.IsEmpty = function (obj) {
  6088. for (var i in obj) {
  6089. return false;
  6090. }
  6091. return true;
  6092. };
  6093. Tools.RegisterTopRootEvents = function (events) {
  6094. for (var index = 0; index < events.length; index++) {
  6095. var event = events[index];
  6096. window.addEventListener(event.name, event.handler, false);
  6097. try {
  6098. if (window.parent) {
  6099. window.parent.addEventListener(event.name, event.handler, false);
  6100. }
  6101. }
  6102. catch (e) {
  6103. // Silently fails...
  6104. }
  6105. }
  6106. };
  6107. Tools.UnregisterTopRootEvents = function (events) {
  6108. for (var index = 0; index < events.length; index++) {
  6109. var event = events[index];
  6110. window.removeEventListener(event.name, event.handler);
  6111. try {
  6112. if (window.parent) {
  6113. window.parent.removeEventListener(event.name, event.handler);
  6114. }
  6115. }
  6116. catch (e) {
  6117. // Silently fails...
  6118. }
  6119. }
  6120. };
  6121. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6122. if (mimeType === void 0) { mimeType = "image/png"; }
  6123. // Read the contents of the framebuffer
  6124. var numberOfChannelsByLine = width * 4;
  6125. var halfHeight = height / 2;
  6126. //Reading datas from WebGL
  6127. var data = engine.readPixels(0, 0, width, height);
  6128. //To flip image on Y axis.
  6129. for (var i = 0; i < halfHeight; i++) {
  6130. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6131. var currentCell = j + i * numberOfChannelsByLine;
  6132. var targetLine = height - i - 1;
  6133. var targetCell = j + targetLine * numberOfChannelsByLine;
  6134. var temp = data[currentCell];
  6135. data[currentCell] = data[targetCell];
  6136. data[targetCell] = temp;
  6137. }
  6138. }
  6139. // Create a 2D canvas to store the result
  6140. if (!screenshotCanvas) {
  6141. screenshotCanvas = document.createElement('canvas');
  6142. }
  6143. screenshotCanvas.width = width;
  6144. screenshotCanvas.height = height;
  6145. var context = screenshotCanvas.getContext('2d');
  6146. // Copy the pixels to a 2D canvas
  6147. var imageData = context.createImageData(width, height);
  6148. var castData = (imageData.data);
  6149. castData.set(data);
  6150. context.putImageData(imageData, 0, 0);
  6151. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6152. };
  6153. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6154. if (mimeType === void 0) { mimeType = "image/png"; }
  6155. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6156. if (successCallback) {
  6157. successCallback(base64Image);
  6158. }
  6159. else {
  6160. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6161. if (("download" in document.createElement("a"))) {
  6162. var a = window.document.createElement("a");
  6163. a.href = base64Image;
  6164. var date = new Date();
  6165. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6166. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6167. window.document.body.appendChild(a);
  6168. a.addEventListener("click", function () {
  6169. a.parentElement.removeChild(a);
  6170. });
  6171. a.click();
  6172. //Or opening a new tab with the image if it is not possible to automatically start download.
  6173. }
  6174. else {
  6175. var newWindow = window.open("");
  6176. var img = newWindow.document.createElement("img");
  6177. img.src = base64Image;
  6178. newWindow.document.body.appendChild(img);
  6179. }
  6180. }
  6181. };
  6182. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6183. if (mimeType === void 0) { mimeType = "image/png"; }
  6184. var width;
  6185. var height;
  6186. // If a precision value is specified
  6187. if (size.precision) {
  6188. width = Math.round(engine.getRenderWidth() * size.precision);
  6189. height = Math.round(width / engine.getAspectRatio(camera));
  6190. }
  6191. else if (size.width && size.height) {
  6192. width = size.width;
  6193. height = size.height;
  6194. }
  6195. else if (size.width && !size.height) {
  6196. width = size.width;
  6197. height = Math.round(width / engine.getAspectRatio(camera));
  6198. }
  6199. else if (size.height && !size.width) {
  6200. height = size.height;
  6201. width = Math.round(height * engine.getAspectRatio(camera));
  6202. }
  6203. else if (!isNaN(size)) {
  6204. height = size;
  6205. width = size;
  6206. }
  6207. else {
  6208. Tools.Error("Invalid 'size' parameter !");
  6209. return;
  6210. }
  6211. if (!screenshotCanvas) {
  6212. screenshotCanvas = document.createElement('canvas');
  6213. }
  6214. screenshotCanvas.width = width;
  6215. screenshotCanvas.height = height;
  6216. var renderContext = screenshotCanvas.getContext("2d");
  6217. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6218. var newWidth = width;
  6219. var newHeight = newWidth / ratio;
  6220. if (newHeight > height) {
  6221. newHeight = height;
  6222. newWidth = newHeight * ratio;
  6223. }
  6224. var offsetX = Math.max(0, width - newWidth) / 2;
  6225. var offsetY = Math.max(0, height - newHeight) / 2;
  6226. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6227. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6228. };
  6229. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6230. if (mimeType === void 0) { mimeType = "image/png"; }
  6231. if (samples === void 0) { samples = 1; }
  6232. var width;
  6233. var height;
  6234. //If a precision value is specified
  6235. if (size.precision) {
  6236. width = Math.round(engine.getRenderWidth() * size.precision);
  6237. height = Math.round(width / engine.getAspectRatio(camera));
  6238. size = { width: width, height: height };
  6239. }
  6240. else if (size.width && size.height) {
  6241. width = size.width;
  6242. height = size.height;
  6243. }
  6244. else if (size.width && !size.height) {
  6245. width = size.width;
  6246. height = Math.round(width / engine.getAspectRatio(camera));
  6247. size = { width: width, height: height };
  6248. }
  6249. else if (size.height && !size.width) {
  6250. height = size.height;
  6251. width = Math.round(height * engine.getAspectRatio(camera));
  6252. size = { width: width, height: height };
  6253. }
  6254. else if (!isNaN(size)) {
  6255. height = size;
  6256. width = size;
  6257. }
  6258. else {
  6259. Tools.Error("Invalid 'size' parameter !");
  6260. return;
  6261. }
  6262. var scene = camera.getScene();
  6263. var previousCamera = null;
  6264. if (scene.activeCamera !== camera) {
  6265. previousCamera = scene.activeCamera;
  6266. scene.activeCamera = camera;
  6267. }
  6268. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6269. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6270. texture.renderList = null;
  6271. texture.samples = samples;
  6272. texture.onAfterRenderObservable.add(function () {
  6273. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6274. });
  6275. scene.incrementRenderId();
  6276. scene.resetCachedMaterial();
  6277. texture.render(true);
  6278. texture.dispose();
  6279. if (previousCamera) {
  6280. scene.activeCamera = previousCamera;
  6281. }
  6282. camera.getProjectionMatrix(true); // Force cache refresh;
  6283. };
  6284. // XHR response validator for local file scenario
  6285. Tools.ValidateXHRData = function (xhr, dataType) {
  6286. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6287. if (dataType === void 0) { dataType = 7; }
  6288. try {
  6289. if (dataType & 1) {
  6290. if (xhr.responseText && xhr.responseText.length > 0) {
  6291. return true;
  6292. }
  6293. else if (dataType === 1) {
  6294. return false;
  6295. }
  6296. }
  6297. if (dataType & 2) {
  6298. // Check header width and height since there is no "TGA" magic number
  6299. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6300. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6301. return true;
  6302. }
  6303. else if (dataType === 2) {
  6304. return false;
  6305. }
  6306. }
  6307. if (dataType & 4) {
  6308. // Check for the "DDS" magic number
  6309. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6310. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6311. return true;
  6312. }
  6313. else {
  6314. return false;
  6315. }
  6316. }
  6317. }
  6318. catch (e) {
  6319. // Global protection
  6320. }
  6321. return false;
  6322. };
  6323. /**
  6324. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6325. * Be aware Math.random() could cause collisions, but:
  6326. * "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"
  6327. */
  6328. Tools.RandomId = function () {
  6329. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6330. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6331. return v.toString(16);
  6332. });
  6333. };
  6334. Object.defineProperty(Tools, "NoneLogLevel", {
  6335. get: function () {
  6336. return Tools._NoneLogLevel;
  6337. },
  6338. enumerable: true,
  6339. configurable: true
  6340. });
  6341. Object.defineProperty(Tools, "MessageLogLevel", {
  6342. get: function () {
  6343. return Tools._MessageLogLevel;
  6344. },
  6345. enumerable: true,
  6346. configurable: true
  6347. });
  6348. Object.defineProperty(Tools, "WarningLogLevel", {
  6349. get: function () {
  6350. return Tools._WarningLogLevel;
  6351. },
  6352. enumerable: true,
  6353. configurable: true
  6354. });
  6355. Object.defineProperty(Tools, "ErrorLogLevel", {
  6356. get: function () {
  6357. return Tools._ErrorLogLevel;
  6358. },
  6359. enumerable: true,
  6360. configurable: true
  6361. });
  6362. Object.defineProperty(Tools, "AllLogLevel", {
  6363. get: function () {
  6364. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6365. },
  6366. enumerable: true,
  6367. configurable: true
  6368. });
  6369. Tools._AddLogEntry = function (entry) {
  6370. Tools._LogCache = entry + Tools._LogCache;
  6371. if (Tools.OnNewCacheEntry) {
  6372. Tools.OnNewCacheEntry(entry);
  6373. }
  6374. };
  6375. Tools._FormatMessage = function (message) {
  6376. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6377. var date = new Date();
  6378. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6379. };
  6380. Tools._LogDisabled = function (message) {
  6381. // nothing to do
  6382. };
  6383. Tools._LogEnabled = function (message) {
  6384. var formattedMessage = Tools._FormatMessage(message);
  6385. console.log("BJS - " + formattedMessage);
  6386. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6387. Tools._AddLogEntry(entry);
  6388. };
  6389. Tools._WarnDisabled = function (message) {
  6390. // nothing to do
  6391. };
  6392. Tools._WarnEnabled = function (message) {
  6393. var formattedMessage = Tools._FormatMessage(message);
  6394. console.warn("BJS - " + formattedMessage);
  6395. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6396. Tools._AddLogEntry(entry);
  6397. };
  6398. Tools._ErrorDisabled = function (message) {
  6399. // nothing to do
  6400. };
  6401. Tools._ErrorEnabled = function (message) {
  6402. Tools.errorsCount++;
  6403. var formattedMessage = Tools._FormatMessage(message);
  6404. console.error("BJS - " + formattedMessage);
  6405. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6406. Tools._AddLogEntry(entry);
  6407. };
  6408. Object.defineProperty(Tools, "LogCache", {
  6409. get: function () {
  6410. return Tools._LogCache;
  6411. },
  6412. enumerable: true,
  6413. configurable: true
  6414. });
  6415. Tools.ClearLogCache = function () {
  6416. Tools._LogCache = "";
  6417. Tools.errorsCount = 0;
  6418. };
  6419. Object.defineProperty(Tools, "LogLevels", {
  6420. set: function (level) {
  6421. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6422. Tools.Log = Tools._LogEnabled;
  6423. }
  6424. else {
  6425. Tools.Log = Tools._LogDisabled;
  6426. }
  6427. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6428. Tools.Warn = Tools._WarnEnabled;
  6429. }
  6430. else {
  6431. Tools.Warn = Tools._WarnDisabled;
  6432. }
  6433. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6434. Tools.Error = Tools._ErrorEnabled;
  6435. }
  6436. else {
  6437. Tools.Error = Tools._ErrorDisabled;
  6438. }
  6439. },
  6440. enumerable: true,
  6441. configurable: true
  6442. });
  6443. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6444. get: function () {
  6445. return Tools._PerformanceNoneLogLevel;
  6446. },
  6447. enumerable: true,
  6448. configurable: true
  6449. });
  6450. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6451. get: function () {
  6452. return Tools._PerformanceUserMarkLogLevel;
  6453. },
  6454. enumerable: true,
  6455. configurable: true
  6456. });
  6457. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6458. get: function () {
  6459. return Tools._PerformanceConsoleLogLevel;
  6460. },
  6461. enumerable: true,
  6462. configurable: true
  6463. });
  6464. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6465. set: function (level) {
  6466. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6467. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6468. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6469. return;
  6470. }
  6471. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6472. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6473. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6474. return;
  6475. }
  6476. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6477. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6478. },
  6479. enumerable: true,
  6480. configurable: true
  6481. });
  6482. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6483. };
  6484. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6485. };
  6486. Tools._StartUserMark = function (counterName, condition) {
  6487. if (condition === void 0) { condition = true; }
  6488. if (!condition || !Tools._performance.mark) {
  6489. return;
  6490. }
  6491. Tools._performance.mark(counterName + "-Begin");
  6492. };
  6493. Tools._EndUserMark = function (counterName, condition) {
  6494. if (condition === void 0) { condition = true; }
  6495. if (!condition || !Tools._performance.mark) {
  6496. return;
  6497. }
  6498. Tools._performance.mark(counterName + "-End");
  6499. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6500. };
  6501. Tools._StartPerformanceConsole = function (counterName, condition) {
  6502. if (condition === void 0) { condition = true; }
  6503. if (!condition) {
  6504. return;
  6505. }
  6506. Tools._StartUserMark(counterName, condition);
  6507. if (console.time) {
  6508. console.time(counterName);
  6509. }
  6510. };
  6511. Tools._EndPerformanceConsole = function (counterName, condition) {
  6512. if (condition === void 0) { condition = true; }
  6513. if (!condition) {
  6514. return;
  6515. }
  6516. Tools._EndUserMark(counterName, condition);
  6517. if (console.time) {
  6518. console.timeEnd(counterName);
  6519. }
  6520. };
  6521. Object.defineProperty(Tools, "Now", {
  6522. get: function () {
  6523. if (window.performance && window.performance.now) {
  6524. return window.performance.now();
  6525. }
  6526. return new Date().getTime();
  6527. },
  6528. enumerable: true,
  6529. configurable: true
  6530. });
  6531. /**
  6532. * This method will return the name of the class used to create the instance of the given object.
  6533. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6534. * @param object the object to get the class name from
  6535. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6536. */
  6537. Tools.GetClassName = function (object, isType) {
  6538. if (isType === void 0) { isType = false; }
  6539. var name = null;
  6540. if (!isType && object.getClassName) {
  6541. name = object.getClassName();
  6542. }
  6543. else {
  6544. if (object instanceof Object) {
  6545. var classObj = isType ? object : Object.getPrototypeOf(object);
  6546. name = classObj.constructor["__bjsclassName__"];
  6547. }
  6548. if (!name) {
  6549. name = typeof object;
  6550. }
  6551. }
  6552. return name;
  6553. };
  6554. Tools.first = function (array, predicate) {
  6555. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6556. var el = array_1[_i];
  6557. if (predicate(el)) {
  6558. return el;
  6559. }
  6560. }
  6561. };
  6562. /**
  6563. * This method will return the name of the full name of the class, including its owning module (if any).
  6564. * 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).
  6565. * @param object the object to get the class name from
  6566. * @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.
  6567. */
  6568. Tools.getFullClassName = function (object, isType) {
  6569. if (isType === void 0) { isType = false; }
  6570. var className = null;
  6571. var moduleName = null;
  6572. if (!isType && object.getClassName) {
  6573. className = object.getClassName();
  6574. }
  6575. else {
  6576. if (object instanceof Object) {
  6577. var classObj = isType ? object : Object.getPrototypeOf(object);
  6578. className = classObj.constructor["__bjsclassName__"];
  6579. moduleName = classObj.constructor["__bjsmoduleName__"];
  6580. }
  6581. if (!className) {
  6582. className = typeof object;
  6583. }
  6584. }
  6585. if (!className) {
  6586. return null;
  6587. }
  6588. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6589. };
  6590. /**
  6591. * 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.
  6592. * @param array
  6593. */
  6594. Tools.arrayOrStringFeeder = function (array) {
  6595. return function (index) {
  6596. if (index >= array.length) {
  6597. return null;
  6598. }
  6599. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6600. if (val && val.getHashCode) {
  6601. val = val.getHashCode();
  6602. }
  6603. if (typeof val === "string") {
  6604. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6605. }
  6606. return val;
  6607. };
  6608. };
  6609. /**
  6610. * Compute the hashCode of a stream of number
  6611. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6612. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6613. * @return the hash code computed
  6614. */
  6615. Tools.hashCodeFromStream = function (feeder) {
  6616. // Based from here: http://stackoverflow.com/a/7616484/802124
  6617. var hash = 0;
  6618. var index = 0;
  6619. var chr = feeder(index++);
  6620. while (chr != null) {
  6621. hash = ((hash << 5) - hash) + chr;
  6622. hash |= 0; // Convert to 32bit integer
  6623. chr = feeder(index++);
  6624. }
  6625. return hash;
  6626. };
  6627. Tools.BaseUrl = "";
  6628. Tools.CorsBehavior = "anonymous";
  6629. Tools.UseFallbackTexture = true;
  6630. // Used in case of a texture loading problem
  6631. 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";
  6632. Tools.PreprocessUrl = function (url) {
  6633. return url;
  6634. };
  6635. // Logs
  6636. Tools._NoneLogLevel = 0;
  6637. Tools._MessageLogLevel = 1;
  6638. Tools._WarningLogLevel = 2;
  6639. Tools._ErrorLogLevel = 4;
  6640. Tools._LogCache = "";
  6641. Tools.errorsCount = 0;
  6642. Tools.Log = Tools._LogEnabled;
  6643. Tools.Warn = Tools._WarnEnabled;
  6644. Tools.Error = Tools._ErrorEnabled;
  6645. // Performances
  6646. Tools._PerformanceNoneLogLevel = 0;
  6647. Tools._PerformanceUserMarkLogLevel = 1;
  6648. Tools._PerformanceConsoleLogLevel = 2;
  6649. Tools._performance = window.performance;
  6650. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6651. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6652. return Tools;
  6653. }());
  6654. BABYLON.Tools = Tools;
  6655. /**
  6656. * This class is used to track a performance counter which is number based.
  6657. * The user has access to many properties which give statistics of different nature
  6658. *
  6659. * The implementer can track two kinds of Performance Counter: time and count
  6660. * 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.
  6661. * 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.
  6662. */
  6663. var PerfCounter = (function () {
  6664. function PerfCounter() {
  6665. this._startMonitoringTime = 0;
  6666. this._min = 0;
  6667. this._max = 0;
  6668. this._average = 0;
  6669. this._lastSecAverage = 0;
  6670. this._current = 0;
  6671. this._totalValueCount = 0;
  6672. this._totalAccumulated = 0;
  6673. this._lastSecAccumulated = 0;
  6674. this._lastSecTime = 0;
  6675. this._lastSecValueCount = 0;
  6676. }
  6677. Object.defineProperty(PerfCounter.prototype, "min", {
  6678. /**
  6679. * Returns the smallest value ever
  6680. */
  6681. get: function () {
  6682. return this._min;
  6683. },
  6684. enumerable: true,
  6685. configurable: true
  6686. });
  6687. Object.defineProperty(PerfCounter.prototype, "max", {
  6688. /**
  6689. * Returns the biggest value ever
  6690. */
  6691. get: function () {
  6692. return this._max;
  6693. },
  6694. enumerable: true,
  6695. configurable: true
  6696. });
  6697. Object.defineProperty(PerfCounter.prototype, "average", {
  6698. /**
  6699. * Returns the average value since the performance counter is running
  6700. */
  6701. get: function () {
  6702. return this._average;
  6703. },
  6704. enumerable: true,
  6705. configurable: true
  6706. });
  6707. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6708. /**
  6709. * Returns the average value of the last second the counter was monitored
  6710. */
  6711. get: function () {
  6712. return this._lastSecAverage;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(PerfCounter.prototype, "current", {
  6718. /**
  6719. * Returns the current value
  6720. */
  6721. get: function () {
  6722. return this._current;
  6723. },
  6724. enumerable: true,
  6725. configurable: true
  6726. });
  6727. Object.defineProperty(PerfCounter.prototype, "total", {
  6728. get: function () {
  6729. return this._totalAccumulated;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. /**
  6735. * Call this method to start monitoring a new frame.
  6736. * 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.
  6737. */
  6738. PerfCounter.prototype.fetchNewFrame = function () {
  6739. this._totalValueCount++;
  6740. this._current = 0;
  6741. this._lastSecValueCount++;
  6742. };
  6743. /**
  6744. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6745. * @param newCount the count value to add to the monitored count
  6746. * @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.
  6747. */
  6748. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6749. if (!PerfCounter.Enabled) {
  6750. return;
  6751. }
  6752. this._current += newCount;
  6753. if (fetchResult) {
  6754. this._fetchResult();
  6755. }
  6756. };
  6757. /**
  6758. * Start monitoring this performance counter
  6759. */
  6760. PerfCounter.prototype.beginMonitoring = function () {
  6761. if (!PerfCounter.Enabled) {
  6762. return;
  6763. }
  6764. this._startMonitoringTime = Tools.Now;
  6765. };
  6766. /**
  6767. * Compute the time lapsed since the previous beginMonitoring() call.
  6768. * @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
  6769. */
  6770. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6771. if (newFrame === void 0) { newFrame = true; }
  6772. if (!PerfCounter.Enabled) {
  6773. return;
  6774. }
  6775. if (newFrame) {
  6776. this.fetchNewFrame();
  6777. }
  6778. var currentTime = Tools.Now;
  6779. this._current = currentTime - this._startMonitoringTime;
  6780. if (newFrame) {
  6781. this._fetchResult();
  6782. }
  6783. };
  6784. PerfCounter.prototype._fetchResult = function () {
  6785. this._totalAccumulated += this._current;
  6786. this._lastSecAccumulated += this._current;
  6787. // Min/Max update
  6788. this._min = Math.min(this._min, this._current);
  6789. this._max = Math.max(this._max, this._current);
  6790. this._average = this._totalAccumulated / this._totalValueCount;
  6791. // Reset last sec?
  6792. var now = Tools.Now;
  6793. if ((now - this._lastSecTime) > 1000) {
  6794. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6795. this._lastSecTime = now;
  6796. this._lastSecAccumulated = 0;
  6797. this._lastSecValueCount = 0;
  6798. }
  6799. };
  6800. PerfCounter.Enabled = true;
  6801. return PerfCounter;
  6802. }());
  6803. BABYLON.PerfCounter = PerfCounter;
  6804. /**
  6805. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6806. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6807. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6808. * @param name The name of the class, case should be preserved
  6809. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6810. */
  6811. function className(name, module) {
  6812. return function (target) {
  6813. target["__bjsclassName__"] = name;
  6814. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6815. };
  6816. }
  6817. BABYLON.className = className;
  6818. /**
  6819. * An implementation of a loop for asynchronous functions.
  6820. */
  6821. var AsyncLoop = (function () {
  6822. /**
  6823. * Constroctor.
  6824. * @param iterations the number of iterations.
  6825. * @param _fn the function to run each iteration
  6826. * @param _successCallback the callback that will be called upon succesful execution
  6827. * @param offset starting offset.
  6828. */
  6829. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6830. if (offset === void 0) { offset = 0; }
  6831. this.iterations = iterations;
  6832. this._fn = _fn;
  6833. this._successCallback = _successCallback;
  6834. this.index = offset - 1;
  6835. this._done = false;
  6836. }
  6837. /**
  6838. * Execute the next iteration. Must be called after the last iteration was finished.
  6839. */
  6840. AsyncLoop.prototype.executeNext = function () {
  6841. if (!this._done) {
  6842. if (this.index + 1 < this.iterations) {
  6843. ++this.index;
  6844. this._fn(this);
  6845. }
  6846. else {
  6847. this.breakLoop();
  6848. }
  6849. }
  6850. };
  6851. /**
  6852. * Break the loop and run the success callback.
  6853. */
  6854. AsyncLoop.prototype.breakLoop = function () {
  6855. this._done = true;
  6856. this._successCallback();
  6857. };
  6858. /**
  6859. * Helper function
  6860. */
  6861. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6862. if (offset === void 0) { offset = 0; }
  6863. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6864. loop.executeNext();
  6865. return loop;
  6866. };
  6867. /**
  6868. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6869. * @param iterations total number of iterations
  6870. * @param syncedIterations number of synchronous iterations in each async iteration.
  6871. * @param fn the function to call each iteration.
  6872. * @param callback a success call back that will be called when iterating stops.
  6873. * @param breakFunction a break condition (optional)
  6874. * @param timeout timeout settings for the setTimeout function. default - 0.
  6875. * @constructor
  6876. */
  6877. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6878. if (timeout === void 0) { timeout = 0; }
  6879. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6880. if (breakFunction && breakFunction())
  6881. loop.breakLoop();
  6882. else {
  6883. setTimeout(function () {
  6884. for (var i = 0; i < syncedIterations; ++i) {
  6885. var iteration = (loop.index * syncedIterations) + i;
  6886. if (iteration >= iterations)
  6887. break;
  6888. fn(iteration);
  6889. if (breakFunction && breakFunction()) {
  6890. loop.breakLoop();
  6891. break;
  6892. }
  6893. }
  6894. loop.executeNext();
  6895. }, timeout);
  6896. }
  6897. }, callback);
  6898. };
  6899. return AsyncLoop;
  6900. }());
  6901. BABYLON.AsyncLoop = AsyncLoop;
  6902. })(BABYLON || (BABYLON = {}));
  6903. //# sourceMappingURL=babylon.tools.js.map
  6904. var BABYLON;
  6905. (function (BABYLON) {
  6906. var Internals;
  6907. (function (Internals) {
  6908. var _AlphaState = (function () {
  6909. /**
  6910. * Initializes the state.
  6911. */
  6912. function _AlphaState() {
  6913. this._isAlphaBlendDirty = false;
  6914. this._isBlendFunctionParametersDirty = false;
  6915. this._isBlendEquationParametersDirty = false;
  6916. this._isBlendConstantsDirty = false;
  6917. this._alphaBlend = false;
  6918. this._blendFunctionParameters = new Array(4);
  6919. this._blendEquationParameters = new Array(2);
  6920. this._blendConstants = new Array(4);
  6921. this.reset();
  6922. }
  6923. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6924. get: function () {
  6925. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6926. },
  6927. enumerable: true,
  6928. configurable: true
  6929. });
  6930. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6931. get: function () {
  6932. return this._alphaBlend;
  6933. },
  6934. set: function (value) {
  6935. if (this._alphaBlend === value) {
  6936. return;
  6937. }
  6938. this._alphaBlend = value;
  6939. this._isAlphaBlendDirty = true;
  6940. },
  6941. enumerable: true,
  6942. configurable: true
  6943. });
  6944. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6945. if (this._blendConstants[0] === r &&
  6946. this._blendConstants[1] === g &&
  6947. this._blendConstants[2] === b &&
  6948. this._blendConstants[3] === a) {
  6949. return;
  6950. }
  6951. this._blendConstants[0] = r;
  6952. this._blendConstants[1] = g;
  6953. this._blendConstants[2] = b;
  6954. this._blendConstants[3] = a;
  6955. this._isBlendConstantsDirty = true;
  6956. };
  6957. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6958. if (this._blendFunctionParameters[0] === value0 &&
  6959. this._blendFunctionParameters[1] === value1 &&
  6960. this._blendFunctionParameters[2] === value2 &&
  6961. this._blendFunctionParameters[3] === value3) {
  6962. return;
  6963. }
  6964. this._blendFunctionParameters[0] = value0;
  6965. this._blendFunctionParameters[1] = value1;
  6966. this._blendFunctionParameters[2] = value2;
  6967. this._blendFunctionParameters[3] = value3;
  6968. this._isBlendFunctionParametersDirty = true;
  6969. };
  6970. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6971. if (this._blendEquationParameters[0] === rgb &&
  6972. this._blendEquationParameters[1] === alpha) {
  6973. return;
  6974. }
  6975. this._blendEquationParameters[0] = rgb;
  6976. this._blendEquationParameters[1] = alpha;
  6977. this._isBlendEquationParametersDirty = true;
  6978. };
  6979. _AlphaState.prototype.reset = function () {
  6980. this._alphaBlend = false;
  6981. this._blendFunctionParameters[0] = null;
  6982. this._blendFunctionParameters[1] = null;
  6983. this._blendFunctionParameters[2] = null;
  6984. this._blendFunctionParameters[3] = null;
  6985. this._blendEquationParameters[0] = null;
  6986. this._blendEquationParameters[1] = null;
  6987. this._blendConstants[0] = null;
  6988. this._blendConstants[1] = null;
  6989. this._blendConstants[2] = null;
  6990. this._blendConstants[3] = null;
  6991. this._isAlphaBlendDirty = true;
  6992. this._isBlendFunctionParametersDirty = false;
  6993. this._isBlendEquationParametersDirty = false;
  6994. this._isBlendConstantsDirty = false;
  6995. };
  6996. _AlphaState.prototype.apply = function (gl) {
  6997. if (!this.isDirty) {
  6998. return;
  6999. }
  7000. // Alpha blend
  7001. if (this._isAlphaBlendDirty) {
  7002. if (this._alphaBlend) {
  7003. gl.enable(gl.BLEND);
  7004. }
  7005. else {
  7006. gl.disable(gl.BLEND);
  7007. }
  7008. this._isAlphaBlendDirty = false;
  7009. }
  7010. // Alpha function
  7011. if (this._isBlendFunctionParametersDirty) {
  7012. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7013. this._isBlendFunctionParametersDirty = false;
  7014. }
  7015. // Alpha equation
  7016. if (this._isBlendEquationParametersDirty) {
  7017. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7018. this._isBlendEquationParametersDirty = false;
  7019. }
  7020. // Constants
  7021. if (this._isBlendConstantsDirty) {
  7022. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7023. this._isBlendConstantsDirty = false;
  7024. }
  7025. };
  7026. return _AlphaState;
  7027. }());
  7028. Internals._AlphaState = _AlphaState;
  7029. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7030. })(BABYLON || (BABYLON = {}));
  7031. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7032. var BABYLON;
  7033. (function (BABYLON) {
  7034. var Internals;
  7035. (function (Internals) {
  7036. var _DepthCullingState = (function () {
  7037. /**
  7038. * Initializes the state.
  7039. */
  7040. function _DepthCullingState() {
  7041. this._isDepthTestDirty = false;
  7042. this._isDepthMaskDirty = false;
  7043. this._isDepthFuncDirty = false;
  7044. this._isCullFaceDirty = false;
  7045. this._isCullDirty = false;
  7046. this._isZOffsetDirty = false;
  7047. this.reset();
  7048. }
  7049. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7050. get: function () {
  7051. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7052. },
  7053. enumerable: true,
  7054. configurable: true
  7055. });
  7056. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7057. get: function () {
  7058. return this._zOffset;
  7059. },
  7060. set: function (value) {
  7061. if (this._zOffset === value) {
  7062. return;
  7063. }
  7064. this._zOffset = value;
  7065. this._isZOffsetDirty = true;
  7066. },
  7067. enumerable: true,
  7068. configurable: true
  7069. });
  7070. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7071. get: function () {
  7072. return this._cullFace;
  7073. },
  7074. set: function (value) {
  7075. if (this._cullFace === value) {
  7076. return;
  7077. }
  7078. this._cullFace = value;
  7079. this._isCullFaceDirty = true;
  7080. },
  7081. enumerable: true,
  7082. configurable: true
  7083. });
  7084. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7085. get: function () {
  7086. return this._cull;
  7087. },
  7088. set: function (value) {
  7089. if (this._cull === value) {
  7090. return;
  7091. }
  7092. this._cull = value;
  7093. this._isCullDirty = true;
  7094. },
  7095. enumerable: true,
  7096. configurable: true
  7097. });
  7098. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7099. get: function () {
  7100. return this._depthFunc;
  7101. },
  7102. set: function (value) {
  7103. if (this._depthFunc === value) {
  7104. return;
  7105. }
  7106. this._depthFunc = value;
  7107. this._isDepthFuncDirty = true;
  7108. },
  7109. enumerable: true,
  7110. configurable: true
  7111. });
  7112. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7113. get: function () {
  7114. return this._depthMask;
  7115. },
  7116. set: function (value) {
  7117. if (this._depthMask === value) {
  7118. return;
  7119. }
  7120. this._depthMask = value;
  7121. this._isDepthMaskDirty = true;
  7122. },
  7123. enumerable: true,
  7124. configurable: true
  7125. });
  7126. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7127. get: function () {
  7128. return this._depthTest;
  7129. },
  7130. set: function (value) {
  7131. if (this._depthTest === value) {
  7132. return;
  7133. }
  7134. this._depthTest = value;
  7135. this._isDepthTestDirty = true;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. _DepthCullingState.prototype.reset = function () {
  7141. this._depthMask = true;
  7142. this._depthTest = true;
  7143. this._depthFunc = null;
  7144. this._cullFace = null;
  7145. this._cull = null;
  7146. this._zOffset = 0;
  7147. this._isDepthTestDirty = true;
  7148. this._isDepthMaskDirty = true;
  7149. this._isDepthFuncDirty = false;
  7150. this._isCullFaceDirty = false;
  7151. this._isCullDirty = false;
  7152. this._isZOffsetDirty = false;
  7153. };
  7154. _DepthCullingState.prototype.apply = function (gl) {
  7155. if (!this.isDirty) {
  7156. return;
  7157. }
  7158. // Cull
  7159. if (this._isCullDirty) {
  7160. if (this.cull) {
  7161. gl.enable(gl.CULL_FACE);
  7162. }
  7163. else {
  7164. gl.disable(gl.CULL_FACE);
  7165. }
  7166. this._isCullDirty = false;
  7167. }
  7168. // Cull face
  7169. if (this._isCullFaceDirty) {
  7170. gl.cullFace(this.cullFace);
  7171. this._isCullFaceDirty = false;
  7172. }
  7173. // Depth mask
  7174. if (this._isDepthMaskDirty) {
  7175. gl.depthMask(this.depthMask);
  7176. this._isDepthMaskDirty = false;
  7177. }
  7178. // Depth test
  7179. if (this._isDepthTestDirty) {
  7180. if (this.depthTest) {
  7181. gl.enable(gl.DEPTH_TEST);
  7182. }
  7183. else {
  7184. gl.disable(gl.DEPTH_TEST);
  7185. }
  7186. this._isDepthTestDirty = false;
  7187. }
  7188. // Depth func
  7189. if (this._isDepthFuncDirty) {
  7190. gl.depthFunc(this.depthFunc);
  7191. this._isDepthFuncDirty = false;
  7192. }
  7193. // zOffset
  7194. if (this._isZOffsetDirty) {
  7195. if (this.zOffset) {
  7196. gl.enable(gl.POLYGON_OFFSET_FILL);
  7197. gl.polygonOffset(this.zOffset, 0);
  7198. }
  7199. else {
  7200. gl.disable(gl.POLYGON_OFFSET_FILL);
  7201. }
  7202. this._isZOffsetDirty = false;
  7203. }
  7204. };
  7205. return _DepthCullingState;
  7206. }());
  7207. Internals._DepthCullingState = _DepthCullingState;
  7208. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7209. })(BABYLON || (BABYLON = {}));
  7210. //# sourceMappingURL=babylon.depthCullingState.js.map
  7211. var BABYLON;
  7212. (function (BABYLON) {
  7213. var Internals;
  7214. (function (Internals) {
  7215. var _StencilState = (function () {
  7216. function _StencilState() {
  7217. this._isStencilTestDirty = false;
  7218. this._isStencilMaskDirty = false;
  7219. this._isStencilFuncDirty = false;
  7220. this._isStencilOpDirty = false;
  7221. this.reset();
  7222. }
  7223. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7224. get: function () {
  7225. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7226. },
  7227. enumerable: true,
  7228. configurable: true
  7229. });
  7230. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7231. get: function () {
  7232. return this._stencilFunc;
  7233. },
  7234. set: function (value) {
  7235. if (this._stencilFunc === value) {
  7236. return;
  7237. }
  7238. this._stencilFunc = value;
  7239. this._isStencilFuncDirty = true;
  7240. },
  7241. enumerable: true,
  7242. configurable: true
  7243. });
  7244. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7245. get: function () {
  7246. return this._stencilFuncRef;
  7247. },
  7248. set: function (value) {
  7249. if (this._stencilFuncRef === value) {
  7250. return;
  7251. }
  7252. this._stencilFuncRef = value;
  7253. this._isStencilFuncDirty = true;
  7254. },
  7255. enumerable: true,
  7256. configurable: true
  7257. });
  7258. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7259. get: function () {
  7260. return this._stencilFuncMask;
  7261. },
  7262. set: function (value) {
  7263. if (this._stencilFuncMask === value) {
  7264. return;
  7265. }
  7266. this._stencilFuncMask = value;
  7267. this._isStencilFuncDirty = true;
  7268. },
  7269. enumerable: true,
  7270. configurable: true
  7271. });
  7272. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7273. get: function () {
  7274. return this._stencilOpStencilFail;
  7275. },
  7276. set: function (value) {
  7277. if (this._stencilOpStencilFail === value) {
  7278. return;
  7279. }
  7280. this._stencilOpStencilFail = value;
  7281. this._isStencilOpDirty = true;
  7282. },
  7283. enumerable: true,
  7284. configurable: true
  7285. });
  7286. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7287. get: function () {
  7288. return this._stencilOpDepthFail;
  7289. },
  7290. set: function (value) {
  7291. if (this._stencilOpDepthFail === value) {
  7292. return;
  7293. }
  7294. this._stencilOpDepthFail = value;
  7295. this._isStencilOpDirty = true;
  7296. },
  7297. enumerable: true,
  7298. configurable: true
  7299. });
  7300. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7301. get: function () {
  7302. return this._stencilOpStencilDepthPass;
  7303. },
  7304. set: function (value) {
  7305. if (this._stencilOpStencilDepthPass === value) {
  7306. return;
  7307. }
  7308. this._stencilOpStencilDepthPass = value;
  7309. this._isStencilOpDirty = true;
  7310. },
  7311. enumerable: true,
  7312. configurable: true
  7313. });
  7314. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7315. get: function () {
  7316. return this._stencilMask;
  7317. },
  7318. set: function (value) {
  7319. if (this._stencilMask === value) {
  7320. return;
  7321. }
  7322. this._stencilMask = value;
  7323. this._isStencilMaskDirty = true;
  7324. },
  7325. enumerable: true,
  7326. configurable: true
  7327. });
  7328. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7329. get: function () {
  7330. return this._stencilTest;
  7331. },
  7332. set: function (value) {
  7333. if (this._stencilTest === value) {
  7334. return;
  7335. }
  7336. this._stencilTest = value;
  7337. this._isStencilTestDirty = true;
  7338. },
  7339. enumerable: true,
  7340. configurable: true
  7341. });
  7342. _StencilState.prototype.reset = function () {
  7343. this._stencilTest = false;
  7344. this._stencilMask = 0xFF;
  7345. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7346. this._stencilFuncRef = 1;
  7347. this._stencilFuncMask = 0xFF;
  7348. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7349. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7350. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7351. this._isStencilTestDirty = true;
  7352. this._isStencilMaskDirty = true;
  7353. this._isStencilFuncDirty = true;
  7354. this._isStencilOpDirty = true;
  7355. };
  7356. _StencilState.prototype.apply = function (gl) {
  7357. if (!this.isDirty) {
  7358. return;
  7359. }
  7360. // Stencil test
  7361. if (this._isStencilTestDirty) {
  7362. if (this.stencilTest) {
  7363. gl.enable(gl.STENCIL_TEST);
  7364. }
  7365. else {
  7366. gl.disable(gl.STENCIL_TEST);
  7367. }
  7368. this._isStencilTestDirty = false;
  7369. }
  7370. // Stencil mask
  7371. if (this._isStencilMaskDirty) {
  7372. gl.stencilMask(this.stencilMask);
  7373. this._isStencilMaskDirty = false;
  7374. }
  7375. // Stencil func
  7376. if (this._isStencilFuncDirty) {
  7377. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7378. this._isStencilFuncDirty = false;
  7379. }
  7380. // Stencil op
  7381. if (this._isStencilOpDirty) {
  7382. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7383. this._isStencilOpDirty = false;
  7384. }
  7385. };
  7386. return _StencilState;
  7387. }());
  7388. Internals._StencilState = _StencilState;
  7389. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7390. })(BABYLON || (BABYLON = {}));
  7391. //# sourceMappingURL=babylon.stencilState.js.map
  7392. var BABYLON;
  7393. (function (BABYLON) {
  7394. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7395. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7396. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7397. gl.compileShader(shader);
  7398. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7399. throw new Error(gl.getShaderInfoLog(shader));
  7400. }
  7401. return shader;
  7402. };
  7403. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7404. var magFilter = gl.NEAREST;
  7405. var minFilter = gl.NEAREST;
  7406. switch (samplingMode) {
  7407. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7408. magFilter = gl.LINEAR;
  7409. if (generateMipMaps) {
  7410. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7411. }
  7412. else {
  7413. minFilter = gl.LINEAR;
  7414. }
  7415. break;
  7416. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7417. magFilter = gl.LINEAR;
  7418. if (generateMipMaps) {
  7419. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7420. }
  7421. else {
  7422. minFilter = gl.LINEAR;
  7423. }
  7424. break;
  7425. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7426. magFilter = gl.NEAREST;
  7427. if (generateMipMaps) {
  7428. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7429. }
  7430. else {
  7431. minFilter = gl.NEAREST;
  7432. }
  7433. break;
  7434. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7435. magFilter = gl.NEAREST;
  7436. if (generateMipMaps) {
  7437. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7438. }
  7439. else {
  7440. minFilter = gl.NEAREST;
  7441. }
  7442. break;
  7443. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7444. magFilter = gl.NEAREST;
  7445. if (generateMipMaps) {
  7446. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7447. }
  7448. else {
  7449. minFilter = gl.LINEAR;
  7450. }
  7451. break;
  7452. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7453. magFilter = gl.NEAREST;
  7454. if (generateMipMaps) {
  7455. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7456. }
  7457. else {
  7458. minFilter = gl.LINEAR;
  7459. }
  7460. break;
  7461. case BABYLON.Texture.NEAREST_LINEAR:
  7462. magFilter = gl.NEAREST;
  7463. minFilter = gl.LINEAR;
  7464. break;
  7465. case BABYLON.Texture.NEAREST_NEAREST:
  7466. magFilter = gl.NEAREST;
  7467. minFilter = gl.NEAREST;
  7468. break;
  7469. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7470. magFilter = gl.LINEAR;
  7471. if (generateMipMaps) {
  7472. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7473. }
  7474. else {
  7475. minFilter = gl.NEAREST;
  7476. }
  7477. break;
  7478. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7479. magFilter = gl.LINEAR;
  7480. if (generateMipMaps) {
  7481. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7482. }
  7483. else {
  7484. minFilter = gl.NEAREST;
  7485. }
  7486. break;
  7487. case BABYLON.Texture.LINEAR_LINEAR:
  7488. magFilter = gl.LINEAR;
  7489. minFilter = gl.LINEAR;
  7490. break;
  7491. case BABYLON.Texture.LINEAR_NEAREST:
  7492. magFilter = gl.LINEAR;
  7493. minFilter = gl.NEAREST;
  7494. break;
  7495. }
  7496. return {
  7497. min: minFilter,
  7498. mag: magFilter
  7499. };
  7500. };
  7501. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7502. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7503. var img;
  7504. var onload = function () {
  7505. loadedImages[index] = img;
  7506. loadedImages._internalCount++;
  7507. if (scene) {
  7508. scene._removePendingData(img);
  7509. }
  7510. if (loadedImages._internalCount === 6) {
  7511. onfinish(loadedImages);
  7512. }
  7513. };
  7514. var onerror = function () {
  7515. if (scene) {
  7516. scene._removePendingData(img);
  7517. }
  7518. if (onErrorCallBack) {
  7519. onErrorCallBack();
  7520. }
  7521. };
  7522. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7523. if (scene) {
  7524. scene._addPendingData(img);
  7525. }
  7526. };
  7527. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7528. if (onError === void 0) { onError = null; }
  7529. var loadedImages = [];
  7530. loadedImages._internalCount = 0;
  7531. for (var index = 0; index < 6; index++) {
  7532. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7533. }
  7534. };
  7535. var BufferPointer = (function () {
  7536. function BufferPointer() {
  7537. }
  7538. return BufferPointer;
  7539. }());
  7540. var InstancingAttributeInfo = (function () {
  7541. function InstancingAttributeInfo() {
  7542. }
  7543. return InstancingAttributeInfo;
  7544. }());
  7545. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7546. /**
  7547. * Define options used to create a render target texture
  7548. */
  7549. var RenderTargetCreationOptions = (function () {
  7550. function RenderTargetCreationOptions() {
  7551. }
  7552. return RenderTargetCreationOptions;
  7553. }());
  7554. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7555. /**
  7556. * Regroup several parameters relative to the browser in use
  7557. */
  7558. var EngineCapabilities = (function () {
  7559. function EngineCapabilities() {
  7560. }
  7561. return EngineCapabilities;
  7562. }());
  7563. BABYLON.EngineCapabilities = EngineCapabilities;
  7564. /**
  7565. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7566. */
  7567. var Engine = (function () {
  7568. /**
  7569. * @constructor
  7570. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7571. * @param {boolean} [antialias] - enable antialias
  7572. * @param options - further options to be sent to the getContext function
  7573. */
  7574. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7575. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7576. var _this = this;
  7577. // Public members
  7578. this.forcePOTTextures = false;
  7579. this.isFullscreen = false;
  7580. this.isPointerLock = false;
  7581. this.cullBackFaces = true;
  7582. this.renderEvenInBackground = true;
  7583. this.preventCacheWipeBetweenFrames = false;
  7584. // To enable/disable IDB support and avoid XHR on .manifest
  7585. this.enableOfflineSupport = false;
  7586. this.scenes = new Array();
  7587. this.postProcesses = new Array();
  7588. // Observables
  7589. /**
  7590. * Observable event triggered each time the rendering canvas is resized
  7591. */
  7592. this.onResizeObservable = new BABYLON.Observable();
  7593. /**
  7594. * Observable event triggered each time the canvas loses focus
  7595. */
  7596. this.onCanvasBlurObservable = new BABYLON.Observable();
  7597. /**
  7598. * Observable event triggered each time the canvas gains focus
  7599. */
  7600. this.onCanvasFocusObservable = new BABYLON.Observable();
  7601. /**
  7602. * Observable event triggered each time the canvas receives pointerout event
  7603. */
  7604. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7605. // Uniform buffers list
  7606. this.disableUniformBuffers = false;
  7607. this._uniformBuffers = new Array();
  7608. this._windowIsBackground = false;
  7609. this._webGLVersion = 1.0;
  7610. this._badOS = false;
  7611. this._badDesktopOS = false;
  7612. this._colorWrite = true;
  7613. this._drawCalls = new BABYLON.PerfCounter();
  7614. this._renderingQueueLaunched = false;
  7615. this._activeRenderLoops = [];
  7616. // Deterministic lockstepMaxSteps
  7617. this._deterministicLockstep = false;
  7618. this._lockstepMaxSteps = 4;
  7619. // Lost context
  7620. this.onContextLostObservable = new BABYLON.Observable();
  7621. this.onContextRestoredObservable = new BABYLON.Observable();
  7622. this._contextWasLost = false;
  7623. this._doNotHandleContextLost = false;
  7624. // FPS
  7625. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7626. this._fps = 60;
  7627. this._deltaTime = 0;
  7628. /**
  7629. * Turn this value on if you want to pause FPS computation when in background
  7630. */
  7631. this.disablePerformanceMonitorInBackground = false;
  7632. // States
  7633. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7634. this._stencilState = new BABYLON.Internals._StencilState();
  7635. this._alphaState = new BABYLON.Internals._AlphaState();
  7636. this._alphaMode = Engine.ALPHA_DISABLE;
  7637. // Cache
  7638. this._internalTexturesCache = new Array();
  7639. this._maxTextureChannels = 16;
  7640. this._activeTexturesCache = {};
  7641. this._compiledEffects = {};
  7642. this._vertexAttribArraysEnabled = [];
  7643. this._uintIndicesCurrentlySet = false;
  7644. this._currentBoundBuffer = new Array();
  7645. this._currentBufferPointers = new Array();
  7646. this._currentInstanceLocations = new Array();
  7647. this._currentInstanceBuffers = new Array();
  7648. this._vaoRecordInProgress = false;
  7649. this._mustWipeVertexAttributes = false;
  7650. // Hardware supported Compressed Textures
  7651. this._texturesSupported = new Array();
  7652. this._onVRFullScreenTriggered = function () {
  7653. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7654. //get the old size before we change
  7655. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7656. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7657. //get the width and height, change the render size
  7658. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7659. var width, height;
  7660. _this.setHardwareScalingLevel(1);
  7661. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7662. }
  7663. else {
  7664. //When the specs are implemented, need to uncomment this.
  7665. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7666. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7667. _this._vrDisplayEnabled = undefined;
  7668. }
  7669. };
  7670. var canvas;
  7671. Engine.Instances.push(this);
  7672. options = options || {};
  7673. if (canvasOrContext.getContext) {
  7674. canvas = canvasOrContext;
  7675. this._renderingCanvas = canvas;
  7676. if (antialias != null) {
  7677. options.antialias = antialias;
  7678. }
  7679. if (options.deterministicLockstep === undefined) {
  7680. options.deterministicLockstep = false;
  7681. }
  7682. if (options.lockstepMaxSteps === undefined) {
  7683. options.lockstepMaxSteps = 4;
  7684. }
  7685. if (options.preserveDrawingBuffer === undefined) {
  7686. options.preserveDrawingBuffer = false;
  7687. }
  7688. if (options.audioEngine === undefined) {
  7689. options.audioEngine = true;
  7690. }
  7691. if (options.stencil === undefined) {
  7692. options.stencil = true;
  7693. }
  7694. this._deterministicLockstep = options.deterministicLockstep;
  7695. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7696. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7697. // GL
  7698. if (!options.disableWebGL2Support) {
  7699. try {
  7700. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7701. if (this._gl) {
  7702. this._webGLVersion = 2.0;
  7703. }
  7704. }
  7705. catch (e) {
  7706. // Do nothing
  7707. }
  7708. }
  7709. if (!this._gl) {
  7710. if (!canvas) {
  7711. throw new Error("The provided canvas is null or undefined.");
  7712. }
  7713. try {
  7714. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7715. }
  7716. catch (e) {
  7717. throw new Error("WebGL not supported");
  7718. }
  7719. }
  7720. if (!this._gl) {
  7721. throw new Error("WebGL not supported");
  7722. }
  7723. this._onCanvasFocus = function () {
  7724. _this.onCanvasFocusObservable.notifyObservers(_this);
  7725. };
  7726. this._onCanvasBlur = function () {
  7727. _this.onCanvasBlurObservable.notifyObservers(_this);
  7728. };
  7729. canvas.addEventListener("focus", this._onCanvasFocus);
  7730. canvas.addEventListener("blur", this._onCanvasBlur);
  7731. this._onBlur = function () {
  7732. if (_this.disablePerformanceMonitorInBackground) {
  7733. _this._performanceMonitor.disable();
  7734. }
  7735. _this._windowIsBackground = true;
  7736. };
  7737. this._onFocus = function () {
  7738. if (_this.disablePerformanceMonitorInBackground) {
  7739. _this._performanceMonitor.enable();
  7740. }
  7741. _this._windowIsBackground = false;
  7742. };
  7743. this._onCanvasPointerOut = function () {
  7744. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7745. };
  7746. window.addEventListener("blur", this._onBlur);
  7747. window.addEventListener("focus", this._onFocus);
  7748. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7749. // Context lost
  7750. if (!this._doNotHandleContextLost) {
  7751. this._onContextLost = function (evt) {
  7752. evt.preventDefault();
  7753. _this._contextWasLost = true;
  7754. BABYLON.Tools.Warn("WebGL context lost.");
  7755. _this.onContextLostObservable.notifyObservers(_this);
  7756. };
  7757. this._onContextRestored = function (evt) {
  7758. // Adding a timeout to avoid race condition at browser level
  7759. setTimeout(function () {
  7760. // Rebuild gl context
  7761. _this._initGLContext();
  7762. // Rebuild effects
  7763. _this._rebuildEffects();
  7764. // Rebuild textures
  7765. _this._rebuildInternalTextures();
  7766. // Rebuild buffers
  7767. _this._rebuildBuffers();
  7768. // Cache
  7769. _this.wipeCaches(true);
  7770. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7771. _this.onContextRestoredObservable.notifyObservers(_this);
  7772. _this._contextWasLost = false;
  7773. }, 0);
  7774. };
  7775. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7776. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7777. }
  7778. }
  7779. else {
  7780. this._gl = canvasOrContext;
  7781. this._renderingCanvas = this._gl.canvas;
  7782. if (this._gl.renderbufferStorageMultisample) {
  7783. this._webGLVersion = 2.0;
  7784. }
  7785. options.stencil = this._gl.getContextAttributes().stencil;
  7786. }
  7787. // Viewport
  7788. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7789. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7790. this.resize();
  7791. this._isStencilEnable = options.stencil;
  7792. this._initGLContext();
  7793. if (canvas) {
  7794. // Fullscreen
  7795. this._onFullscreenChange = function () {
  7796. if (document.fullscreen !== undefined) {
  7797. _this.isFullscreen = document.fullscreen;
  7798. }
  7799. else if (document.mozFullScreen !== undefined) {
  7800. _this.isFullscreen = document.mozFullScreen;
  7801. }
  7802. else if (document.webkitIsFullScreen !== undefined) {
  7803. _this.isFullscreen = document.webkitIsFullScreen;
  7804. }
  7805. else if (document.msIsFullScreen !== undefined) {
  7806. _this.isFullscreen = document.msIsFullScreen;
  7807. }
  7808. // Pointer lock
  7809. if (_this.isFullscreen && _this._pointerLockRequested) {
  7810. canvas.requestPointerLock = canvas.requestPointerLock ||
  7811. canvas.msRequestPointerLock ||
  7812. canvas.mozRequestPointerLock ||
  7813. canvas.webkitRequestPointerLock;
  7814. if (canvas.requestPointerLock) {
  7815. canvas.requestPointerLock();
  7816. }
  7817. }
  7818. };
  7819. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7820. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7821. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7822. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7823. // Pointer lock
  7824. this._onPointerLockChange = function () {
  7825. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7826. document.webkitPointerLockElement === canvas ||
  7827. document.msPointerLockElement === canvas ||
  7828. document.pointerLockElement === canvas);
  7829. };
  7830. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7831. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7832. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7833. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7834. this._onVRDisplayPointerRestricted = function () {
  7835. canvas.requestPointerLock();
  7836. };
  7837. this._onVRDisplayPointerUnrestricted = function () {
  7838. document.exitPointerLock();
  7839. };
  7840. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7841. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7842. }
  7843. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7844. Engine.audioEngine = new BABYLON.AudioEngine();
  7845. }
  7846. // Prepare buffer pointers
  7847. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7848. this._currentBufferPointers[i] = new BufferPointer();
  7849. }
  7850. // Load WebVR Devices
  7851. if (options.autoEnableWebVR) {
  7852. this.initWebVR();
  7853. }
  7854. // Detect if we are running on a faulty buggy OS.
  7855. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7856. // Detect if we are running on a faulty buggy desktop OS.
  7857. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7858. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7859. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7860. }
  7861. Object.defineProperty(Engine, "LastCreatedEngine", {
  7862. get: function () {
  7863. if (Engine.Instances.length === 0) {
  7864. return null;
  7865. }
  7866. return Engine.Instances[Engine.Instances.length - 1];
  7867. },
  7868. enumerable: true,
  7869. configurable: true
  7870. });
  7871. Object.defineProperty(Engine, "LastCreatedScene", {
  7872. get: function () {
  7873. var lastCreatedEngine = Engine.LastCreatedEngine;
  7874. if (!lastCreatedEngine) {
  7875. return null;
  7876. }
  7877. if (lastCreatedEngine.scenes.length === 0) {
  7878. return null;
  7879. }
  7880. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7881. },
  7882. enumerable: true,
  7883. configurable: true
  7884. });
  7885. /**
  7886. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7887. */
  7888. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7889. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7890. var engine = Engine.Instances[engineIndex];
  7891. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7892. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7893. }
  7894. }
  7895. };
  7896. Object.defineProperty(Engine, "NEVER", {
  7897. get: function () {
  7898. return Engine._NEVER;
  7899. },
  7900. enumerable: true,
  7901. configurable: true
  7902. });
  7903. Object.defineProperty(Engine, "ALWAYS", {
  7904. get: function () {
  7905. return Engine._ALWAYS;
  7906. },
  7907. enumerable: true,
  7908. configurable: true
  7909. });
  7910. Object.defineProperty(Engine, "LESS", {
  7911. get: function () {
  7912. return Engine._LESS;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. Object.defineProperty(Engine, "EQUAL", {
  7918. get: function () {
  7919. return Engine._EQUAL;
  7920. },
  7921. enumerable: true,
  7922. configurable: true
  7923. });
  7924. Object.defineProperty(Engine, "LEQUAL", {
  7925. get: function () {
  7926. return Engine._LEQUAL;
  7927. },
  7928. enumerable: true,
  7929. configurable: true
  7930. });
  7931. Object.defineProperty(Engine, "GREATER", {
  7932. get: function () {
  7933. return Engine._GREATER;
  7934. },
  7935. enumerable: true,
  7936. configurable: true
  7937. });
  7938. Object.defineProperty(Engine, "GEQUAL", {
  7939. get: function () {
  7940. return Engine._GEQUAL;
  7941. },
  7942. enumerable: true,
  7943. configurable: true
  7944. });
  7945. Object.defineProperty(Engine, "NOTEQUAL", {
  7946. get: function () {
  7947. return Engine._NOTEQUAL;
  7948. },
  7949. enumerable: true,
  7950. configurable: true
  7951. });
  7952. Object.defineProperty(Engine, "KEEP", {
  7953. get: function () {
  7954. return Engine._KEEP;
  7955. },
  7956. enumerable: true,
  7957. configurable: true
  7958. });
  7959. Object.defineProperty(Engine, "REPLACE", {
  7960. get: function () {
  7961. return Engine._REPLACE;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. Object.defineProperty(Engine, "INCR", {
  7967. get: function () {
  7968. return Engine._INCR;
  7969. },
  7970. enumerable: true,
  7971. configurable: true
  7972. });
  7973. Object.defineProperty(Engine, "DECR", {
  7974. get: function () {
  7975. return Engine._DECR;
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. Object.defineProperty(Engine, "INVERT", {
  7981. get: function () {
  7982. return Engine._INVERT;
  7983. },
  7984. enumerable: true,
  7985. configurable: true
  7986. });
  7987. Object.defineProperty(Engine, "INCR_WRAP", {
  7988. get: function () {
  7989. return Engine._INCR_WRAP;
  7990. },
  7991. enumerable: true,
  7992. configurable: true
  7993. });
  7994. Object.defineProperty(Engine, "DECR_WRAP", {
  7995. get: function () {
  7996. return Engine._DECR_WRAP;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8002. get: function () {
  8003. return Engine._ALPHA_DISABLE;
  8004. },
  8005. enumerable: true,
  8006. configurable: true
  8007. });
  8008. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8009. get: function () {
  8010. return Engine._ALPHA_ONEONE;
  8011. },
  8012. enumerable: true,
  8013. configurable: true
  8014. });
  8015. Object.defineProperty(Engine, "ALPHA_ADD", {
  8016. get: function () {
  8017. return Engine._ALPHA_ADD;
  8018. },
  8019. enumerable: true,
  8020. configurable: true
  8021. });
  8022. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8023. get: function () {
  8024. return Engine._ALPHA_COMBINE;
  8025. },
  8026. enumerable: true,
  8027. configurable: true
  8028. });
  8029. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8030. get: function () {
  8031. return Engine._ALPHA_SUBTRACT;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8037. get: function () {
  8038. return Engine._ALPHA_MULTIPLY;
  8039. },
  8040. enumerable: true,
  8041. configurable: true
  8042. });
  8043. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8044. get: function () {
  8045. return Engine._ALPHA_MAXIMIZED;
  8046. },
  8047. enumerable: true,
  8048. configurable: true
  8049. });
  8050. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8051. get: function () {
  8052. return Engine._ALPHA_PREMULTIPLIED;
  8053. },
  8054. enumerable: true,
  8055. configurable: true
  8056. });
  8057. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8058. get: function () {
  8059. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8060. },
  8061. enumerable: true,
  8062. configurable: true
  8063. });
  8064. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8065. get: function () {
  8066. return Engine._ALPHA_INTERPOLATE;
  8067. },
  8068. enumerable: true,
  8069. configurable: true
  8070. });
  8071. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8072. get: function () {
  8073. return Engine._ALPHA_SCREENMODE;
  8074. },
  8075. enumerable: true,
  8076. configurable: true
  8077. });
  8078. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8079. get: function () {
  8080. return Engine._DELAYLOADSTATE_NONE;
  8081. },
  8082. enumerable: true,
  8083. configurable: true
  8084. });
  8085. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8086. get: function () {
  8087. return Engine._DELAYLOADSTATE_LOADED;
  8088. },
  8089. enumerable: true,
  8090. configurable: true
  8091. });
  8092. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8093. get: function () {
  8094. return Engine._DELAYLOADSTATE_LOADING;
  8095. },
  8096. enumerable: true,
  8097. configurable: true
  8098. });
  8099. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8100. get: function () {
  8101. return Engine._DELAYLOADSTATE_NOTLOADED;
  8102. },
  8103. enumerable: true,
  8104. configurable: true
  8105. });
  8106. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8107. get: function () {
  8108. return Engine._TEXTUREFORMAT_ALPHA;
  8109. },
  8110. enumerable: true,
  8111. configurable: true
  8112. });
  8113. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8114. get: function () {
  8115. return Engine._TEXTUREFORMAT_LUMINANCE;
  8116. },
  8117. enumerable: true,
  8118. configurable: true
  8119. });
  8120. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8121. get: function () {
  8122. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8123. },
  8124. enumerable: true,
  8125. configurable: true
  8126. });
  8127. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8128. get: function () {
  8129. return Engine._TEXTUREFORMAT_RGB;
  8130. },
  8131. enumerable: true,
  8132. configurable: true
  8133. });
  8134. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8135. get: function () {
  8136. return Engine._TEXTUREFORMAT_RGBA;
  8137. },
  8138. enumerable: true,
  8139. configurable: true
  8140. });
  8141. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8142. get: function () {
  8143. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8144. },
  8145. enumerable: true,
  8146. configurable: true
  8147. });
  8148. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8149. get: function () {
  8150. return Engine._TEXTURETYPE_FLOAT;
  8151. },
  8152. enumerable: true,
  8153. configurable: true
  8154. });
  8155. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8156. get: function () {
  8157. return Engine._TEXTURETYPE_HALF_FLOAT;
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8163. get: function () {
  8164. return Engine._SCALEMODE_FLOOR;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8170. get: function () {
  8171. return Engine._SCALEMODE_NEAREST;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8177. get: function () {
  8178. return Engine._SCALEMODE_CEILING;
  8179. },
  8180. enumerable: true,
  8181. configurable: true
  8182. });
  8183. Object.defineProperty(Engine, "Version", {
  8184. get: function () {
  8185. return "3.1-alpha";
  8186. },
  8187. enumerable: true,
  8188. configurable: true
  8189. });
  8190. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8191. get: function () {
  8192. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8193. },
  8194. enumerable: true,
  8195. configurable: true
  8196. });
  8197. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8198. get: function () {
  8199. return this._webGLVersion < 2 || this.forcePOTTextures;
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. Object.defineProperty(Engine.prototype, "badOS", {
  8205. get: function () {
  8206. return this._badOS;
  8207. },
  8208. enumerable: true,
  8209. configurable: true
  8210. });
  8211. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8212. get: function () {
  8213. return this._badDesktopOS;
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8219. get: function () {
  8220. return this._performanceMonitor;
  8221. },
  8222. enumerable: true,
  8223. configurable: true
  8224. });
  8225. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8226. get: function () {
  8227. return this._texturesSupported;
  8228. },
  8229. enumerable: true,
  8230. configurable: true
  8231. });
  8232. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8233. get: function () {
  8234. return this._textureFormatInUse;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Object.defineProperty(Engine.prototype, "currentViewport", {
  8240. get: function () {
  8241. return this._cachedViewport;
  8242. },
  8243. enumerable: true,
  8244. configurable: true
  8245. });
  8246. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8247. // Empty texture
  8248. get: function () {
  8249. if (!this._emptyTexture) {
  8250. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8251. }
  8252. return this._emptyTexture;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8258. get: function () {
  8259. if (!this._emptyCubeTexture) {
  8260. var faceData = new Uint8Array(4);
  8261. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8262. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8263. }
  8264. return this._emptyCubeTexture;
  8265. },
  8266. enumerable: true,
  8267. configurable: true
  8268. });
  8269. Engine.prototype._rebuildInternalTextures = function () {
  8270. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8271. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8272. var internalTexture = currentState_1[_i];
  8273. internalTexture._rebuild();
  8274. }
  8275. };
  8276. Engine.prototype._rebuildEffects = function () {
  8277. for (var key in this._compiledEffects) {
  8278. var effect = this._compiledEffects[key];
  8279. effect._prepareEffect();
  8280. }
  8281. BABYLON.Effect.ResetCache();
  8282. };
  8283. Engine.prototype._rebuildBuffers = function () {
  8284. // Index / Vertex
  8285. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8286. var scene = _a[_i];
  8287. scene.resetCachedMaterial();
  8288. scene._rebuildGeometries();
  8289. scene._rebuildTextures();
  8290. }
  8291. // Uniforms
  8292. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8293. var uniformBuffer = _c[_b];
  8294. uniformBuffer._rebuild();
  8295. }
  8296. };
  8297. Engine.prototype._initGLContext = function () {
  8298. // Caps
  8299. this._caps = new EngineCapabilities();
  8300. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8301. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8302. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8303. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8304. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8305. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8306. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8307. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8308. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8309. // Infos
  8310. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8311. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8312. if (rendererInfo != null) {
  8313. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8314. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8315. }
  8316. if (!this._glVendor) {
  8317. this._glVendor = "Unknown vendor";
  8318. }
  8319. if (!this._glRenderer) {
  8320. this._glRenderer = "Unknown renderer";
  8321. }
  8322. // Constants
  8323. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8324. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8325. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8326. this._gl.DEPTH24_STENCIL8 = 35056;
  8327. // Extensions
  8328. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8329. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8330. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8331. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8332. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8333. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8334. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8335. 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');
  8336. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8337. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8338. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8339. this._caps.highPrecisionShaderSupported = true;
  8340. // Checks if some of the format renders first to allow the use of webgl inspector.
  8341. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8342. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8343. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8344. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8345. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8346. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8347. if (this._webGLVersion > 1) {
  8348. this._gl.HALF_FLOAT_OES = 0x140B;
  8349. }
  8350. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8351. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8352. // Draw buffers
  8353. if (this._webGLVersion > 1) {
  8354. this._caps.drawBuffersExtension = true;
  8355. }
  8356. else {
  8357. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8358. if (drawBuffersExtension !== null) {
  8359. this._caps.drawBuffersExtension = true;
  8360. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8361. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8362. for (var i = 0; i < 16; i++) {
  8363. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8364. }
  8365. }
  8366. else {
  8367. this._caps.drawBuffersExtension = false;
  8368. }
  8369. }
  8370. // Depth Texture
  8371. if (this._webGLVersion > 1) {
  8372. this._caps.depthTextureExtension = true;
  8373. }
  8374. else {
  8375. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8376. if (depthTextureExtension != null) {
  8377. this._caps.depthTextureExtension = true;
  8378. }
  8379. }
  8380. // Vertex array object
  8381. if (this._webGLVersion > 1) {
  8382. this._caps.vertexArrayObject = true;
  8383. }
  8384. else {
  8385. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8386. if (vertexArrayObjectExtension != null) {
  8387. this._caps.vertexArrayObject = true;
  8388. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8389. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8390. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8391. }
  8392. else {
  8393. this._caps.vertexArrayObject = false;
  8394. }
  8395. }
  8396. // Instances count
  8397. if (this._webGLVersion > 1) {
  8398. this._caps.instancedArrays = true;
  8399. }
  8400. else {
  8401. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8402. if (instanceExtension != null) {
  8403. this._caps.instancedArrays = true;
  8404. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8405. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8406. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8407. }
  8408. else {
  8409. this._caps.instancedArrays = false;
  8410. }
  8411. }
  8412. // Intelligently add supported compressed formats in order to check for.
  8413. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8414. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8415. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8416. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8417. if (this._caps.astc)
  8418. this.texturesSupported.push('-astc.ktx');
  8419. if (this._caps.s3tc)
  8420. this.texturesSupported.push('-dxt.ktx');
  8421. if (this._caps.pvrtc)
  8422. this.texturesSupported.push('-pvrtc.ktx');
  8423. if (this._caps.etc2)
  8424. this.texturesSupported.push('-etc2.ktx');
  8425. if (this._caps.etc1)
  8426. this.texturesSupported.push('-etc1.ktx');
  8427. if (this._gl.getShaderPrecisionFormat) {
  8428. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8429. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8430. }
  8431. // Depth buffer
  8432. this.setDepthBuffer(true);
  8433. this.setDepthFunctionToLessOrEqual();
  8434. this.setDepthWrite(true);
  8435. };
  8436. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8437. get: function () {
  8438. return this._webGLVersion;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8444. /**
  8445. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8446. */
  8447. get: function () {
  8448. return this._isStencilEnable;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Engine.prototype._prepareWorkingCanvas = function () {
  8454. if (this._workingCanvas) {
  8455. return;
  8456. }
  8457. this._workingCanvas = document.createElement("canvas");
  8458. this._workingContext = this._workingCanvas.getContext("2d");
  8459. };
  8460. Engine.prototype.resetTextureCache = function () {
  8461. for (var key in this._activeTexturesCache) {
  8462. this._activeTexturesCache[key] = null;
  8463. }
  8464. };
  8465. Engine.prototype.isDeterministicLockStep = function () {
  8466. return this._deterministicLockstep;
  8467. };
  8468. Engine.prototype.getLockstepMaxSteps = function () {
  8469. return this._lockstepMaxSteps;
  8470. };
  8471. Engine.prototype.getGlInfo = function () {
  8472. return {
  8473. vendor: this._glVendor,
  8474. renderer: this._glRenderer,
  8475. version: this._glVersion
  8476. };
  8477. };
  8478. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8479. if (useScreen === void 0) { useScreen = false; }
  8480. var viewport = camera.viewport;
  8481. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8482. };
  8483. Engine.prototype.getRenderWidth = function (useScreen) {
  8484. if (useScreen === void 0) { useScreen = false; }
  8485. if (!useScreen && this._currentRenderTarget) {
  8486. return this._currentRenderTarget.width;
  8487. }
  8488. return this._gl.drawingBufferWidth;
  8489. };
  8490. Engine.prototype.getRenderHeight = function (useScreen) {
  8491. if (useScreen === void 0) { useScreen = false; }
  8492. if (!useScreen && this._currentRenderTarget) {
  8493. return this._currentRenderTarget.height;
  8494. }
  8495. return this._gl.drawingBufferHeight;
  8496. };
  8497. Engine.prototype.getRenderingCanvas = function () {
  8498. return this._renderingCanvas;
  8499. };
  8500. Engine.prototype.getRenderingCanvasClientRect = function () {
  8501. return this._renderingCanvas.getBoundingClientRect();
  8502. };
  8503. Engine.prototype.setHardwareScalingLevel = function (level) {
  8504. this._hardwareScalingLevel = level;
  8505. this.resize();
  8506. };
  8507. Engine.prototype.getHardwareScalingLevel = function () {
  8508. return this._hardwareScalingLevel;
  8509. };
  8510. Engine.prototype.getLoadedTexturesCache = function () {
  8511. return this._internalTexturesCache;
  8512. };
  8513. Engine.prototype.getCaps = function () {
  8514. return this._caps;
  8515. };
  8516. Object.defineProperty(Engine.prototype, "drawCalls", {
  8517. /** The number of draw calls submitted last frame */
  8518. get: function () {
  8519. return this._drawCalls.current;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8525. get: function () {
  8526. return this._drawCalls;
  8527. },
  8528. enumerable: true,
  8529. configurable: true
  8530. });
  8531. Engine.prototype.getDepthFunction = function () {
  8532. return this._depthCullingState.depthFunc;
  8533. };
  8534. Engine.prototype.setDepthFunction = function (depthFunc) {
  8535. this._depthCullingState.depthFunc = depthFunc;
  8536. };
  8537. Engine.prototype.setDepthFunctionToGreater = function () {
  8538. this._depthCullingState.depthFunc = this._gl.GREATER;
  8539. };
  8540. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8541. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8542. };
  8543. Engine.prototype.setDepthFunctionToLess = function () {
  8544. this._depthCullingState.depthFunc = this._gl.LESS;
  8545. };
  8546. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8547. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8548. };
  8549. Engine.prototype.getStencilBuffer = function () {
  8550. return this._stencilState.stencilTest;
  8551. };
  8552. Engine.prototype.setStencilBuffer = function (enable) {
  8553. this._stencilState.stencilTest = enable;
  8554. };
  8555. Engine.prototype.getStencilMask = function () {
  8556. return this._stencilState.stencilMask;
  8557. };
  8558. Engine.prototype.setStencilMask = function (mask) {
  8559. this._stencilState.stencilMask = mask;
  8560. };
  8561. Engine.prototype.getStencilFunction = function () {
  8562. return this._stencilState.stencilFunc;
  8563. };
  8564. Engine.prototype.getStencilFunctionReference = function () {
  8565. return this._stencilState.stencilFuncRef;
  8566. };
  8567. Engine.prototype.getStencilFunctionMask = function () {
  8568. return this._stencilState.stencilFuncMask;
  8569. };
  8570. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8571. this._stencilState.stencilFunc = stencilFunc;
  8572. };
  8573. Engine.prototype.setStencilFunctionReference = function (reference) {
  8574. this._stencilState.stencilFuncRef = reference;
  8575. };
  8576. Engine.prototype.setStencilFunctionMask = function (mask) {
  8577. this._stencilState.stencilFuncMask = mask;
  8578. };
  8579. Engine.prototype.getStencilOperationFail = function () {
  8580. return this._stencilState.stencilOpStencilFail;
  8581. };
  8582. Engine.prototype.getStencilOperationDepthFail = function () {
  8583. return this._stencilState.stencilOpDepthFail;
  8584. };
  8585. Engine.prototype.getStencilOperationPass = function () {
  8586. return this._stencilState.stencilOpStencilDepthPass;
  8587. };
  8588. Engine.prototype.setStencilOperationFail = function (operation) {
  8589. this._stencilState.stencilOpStencilFail = operation;
  8590. };
  8591. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8592. this._stencilState.stencilOpDepthFail = operation;
  8593. };
  8594. Engine.prototype.setStencilOperationPass = function (operation) {
  8595. this._stencilState.stencilOpStencilDepthPass = operation;
  8596. };
  8597. Engine.prototype.setDitheringState = function (value) {
  8598. if (value) {
  8599. this._gl.enable(this._gl.DITHER);
  8600. }
  8601. else {
  8602. this._gl.disable(this._gl.DITHER);
  8603. }
  8604. };
  8605. /**
  8606. * stop executing a render loop function and remove it from the execution array
  8607. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8608. */
  8609. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8610. if (!renderFunction) {
  8611. this._activeRenderLoops = [];
  8612. return;
  8613. }
  8614. var index = this._activeRenderLoops.indexOf(renderFunction);
  8615. if (index >= 0) {
  8616. this._activeRenderLoops.splice(index, 1);
  8617. }
  8618. };
  8619. Engine.prototype._renderLoop = function () {
  8620. if (!this._contextWasLost) {
  8621. var shouldRender = true;
  8622. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8623. shouldRender = false;
  8624. }
  8625. if (shouldRender) {
  8626. // Start new frame
  8627. this.beginFrame();
  8628. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8629. var renderFunction = this._activeRenderLoops[index];
  8630. renderFunction();
  8631. }
  8632. // Present
  8633. this.endFrame();
  8634. }
  8635. }
  8636. if (this._activeRenderLoops.length > 0) {
  8637. // Register new frame
  8638. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8639. }
  8640. else {
  8641. this._renderingQueueLaunched = false;
  8642. }
  8643. };
  8644. /**
  8645. * Register and execute a render loop. The engine can have more than one render function.
  8646. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8647. * @example
  8648. * engine.runRenderLoop(function () {
  8649. * scene.render()
  8650. * })
  8651. */
  8652. Engine.prototype.runRenderLoop = function (renderFunction) {
  8653. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8654. return;
  8655. }
  8656. this._activeRenderLoops.push(renderFunction);
  8657. if (!this._renderingQueueLaunched) {
  8658. this._renderingQueueLaunched = true;
  8659. this._bindedRenderFunction = this._renderLoop.bind(this);
  8660. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8661. }
  8662. };
  8663. /**
  8664. * Toggle full screen mode.
  8665. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8666. * @param {any} options - an options object to be sent to the requestFullscreen function
  8667. */
  8668. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8669. if (this.isFullscreen) {
  8670. BABYLON.Tools.ExitFullscreen();
  8671. }
  8672. else {
  8673. this._pointerLockRequested = requestPointerLock;
  8674. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8675. }
  8676. };
  8677. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8678. if (stencil === void 0) { stencil = false; }
  8679. this.applyStates();
  8680. var mode = 0;
  8681. if (backBuffer && color) {
  8682. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8683. mode |= this._gl.COLOR_BUFFER_BIT;
  8684. }
  8685. if (depth) {
  8686. this._gl.clearDepth(1.0);
  8687. mode |= this._gl.DEPTH_BUFFER_BIT;
  8688. }
  8689. if (stencil) {
  8690. this._gl.clearStencil(0);
  8691. mode |= this._gl.STENCIL_BUFFER_BIT;
  8692. }
  8693. this._gl.clear(mode);
  8694. };
  8695. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8696. var gl = this._gl;
  8697. // Save state
  8698. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8699. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8700. // Change state
  8701. gl.enable(gl.SCISSOR_TEST);
  8702. gl.scissor(x, y, width, height);
  8703. // Clear
  8704. this.clear(clearColor, true, true, true);
  8705. // Restore state
  8706. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8707. if (curScissor === true) {
  8708. gl.enable(gl.SCISSOR_TEST);
  8709. }
  8710. else {
  8711. gl.disable(gl.SCISSOR_TEST);
  8712. }
  8713. };
  8714. /**
  8715. * Set the WebGL's viewport
  8716. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8717. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8718. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8719. */
  8720. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8721. var width = requiredWidth || this.getRenderWidth();
  8722. var height = requiredHeight || this.getRenderHeight();
  8723. var x = viewport.x || 0;
  8724. var y = viewport.y || 0;
  8725. this._cachedViewport = viewport;
  8726. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8727. };
  8728. /**
  8729. * Directly set the WebGL Viewport
  8730. * The x, y, width & height are directly passed to the WebGL call
  8731. * @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.
  8732. */
  8733. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8734. var currentViewport = this._cachedViewport;
  8735. this._cachedViewport = null;
  8736. this._gl.viewport(x, y, width, height);
  8737. return currentViewport;
  8738. };
  8739. Engine.prototype.beginFrame = function () {
  8740. this._measureFps();
  8741. };
  8742. Engine.prototype.endFrame = function () {
  8743. //force a flush in case we are using a bad OS.
  8744. if (this._badOS) {
  8745. this.flushFramebuffer();
  8746. }
  8747. //submit frame to the vr device, if enabled
  8748. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8749. this._vrDisplayEnabled.submitFrame();
  8750. }
  8751. };
  8752. /**
  8753. * resize the view according to the canvas' size.
  8754. * @example
  8755. * window.addEventListener("resize", function () {
  8756. * engine.resize();
  8757. * });
  8758. */
  8759. Engine.prototype.resize = function () {
  8760. // We're not resizing the size of the canvas while in VR mode & presenting
  8761. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8762. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8763. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8764. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8765. }
  8766. };
  8767. /**
  8768. * force a specific size of the canvas
  8769. * @param {number} width - the new canvas' width
  8770. * @param {number} height - the new canvas' height
  8771. */
  8772. Engine.prototype.setSize = function (width, height) {
  8773. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8774. return;
  8775. }
  8776. this._renderingCanvas.width = width;
  8777. this._renderingCanvas.height = height;
  8778. for (var index = 0; index < this.scenes.length; index++) {
  8779. var scene = this.scenes[index];
  8780. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8781. var cam = scene.cameras[camIndex];
  8782. cam._currentRenderId = 0;
  8783. }
  8784. }
  8785. if (this.onResizeObservable.hasObservers) {
  8786. this.onResizeObservable.notifyObservers(this);
  8787. }
  8788. };
  8789. //WebVR functions
  8790. Engine.prototype.isVRDevicePresent = function (callback) {
  8791. this.getVRDevice(null, function (device) {
  8792. callback(device !== null);
  8793. });
  8794. };
  8795. Engine.prototype.getVRDevice = function (name, callback) {
  8796. if (!this.vrDisplaysPromise) {
  8797. callback(null);
  8798. return;
  8799. }
  8800. this.vrDisplaysPromise.then(function (devices) {
  8801. if (devices.length > 0) {
  8802. if (name) {
  8803. var found = devices.some(function (device) {
  8804. if (device.displayName === name) {
  8805. callback(device);
  8806. return true;
  8807. }
  8808. else {
  8809. return false;
  8810. }
  8811. });
  8812. if (!found) {
  8813. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8814. callback(devices[0]);
  8815. }
  8816. }
  8817. else {
  8818. //choose the first one
  8819. callback(devices[0]);
  8820. }
  8821. }
  8822. else {
  8823. BABYLON.Tools.Error("No WebVR devices found!");
  8824. callback(null);
  8825. }
  8826. });
  8827. };
  8828. Engine.prototype.initWebVR = function () {
  8829. if (!this.vrDisplaysPromise) {
  8830. this._getVRDisplays();
  8831. }
  8832. };
  8833. Engine.prototype.enableVR = function (vrDevice) {
  8834. this._vrDisplayEnabled = vrDevice;
  8835. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8836. };
  8837. Engine.prototype.disableVR = function () {
  8838. if (this._vrDisplayEnabled) {
  8839. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8840. }
  8841. };
  8842. Engine.prototype._getVRDisplays = function () {
  8843. var _this = this;
  8844. var getWebVRDevices = function (devices) {
  8845. _this._vrDisplays = devices.filter(function (device) {
  8846. return device instanceof VRDisplay;
  8847. });
  8848. return _this._vrDisplays;
  8849. };
  8850. if (navigator.getVRDisplays) {
  8851. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8852. }
  8853. };
  8854. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8855. if (this._currentRenderTarget) {
  8856. this.unBindFramebuffer(this._currentRenderTarget);
  8857. }
  8858. this._currentRenderTarget = texture;
  8859. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8860. var gl = this._gl;
  8861. if (texture.isCube) {
  8862. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8863. }
  8864. if (this._cachedViewport && !forceFullscreenViewport) {
  8865. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8866. }
  8867. else {
  8868. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8869. }
  8870. this.wipeCaches();
  8871. };
  8872. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8873. if (this._currentFramebuffer !== framebuffer) {
  8874. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8875. this._currentFramebuffer = framebuffer;
  8876. }
  8877. };
  8878. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8879. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8880. this._currentRenderTarget = null;
  8881. // If MSAA, we need to bitblt back to main texture
  8882. var gl = this._gl;
  8883. if (texture._MSAAFramebuffer) {
  8884. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8885. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8886. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8887. }
  8888. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8889. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8890. gl.generateMipmap(gl.TEXTURE_2D);
  8891. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8892. }
  8893. if (onBeforeUnbind) {
  8894. if (texture._MSAAFramebuffer) {
  8895. // Bind the correct framebuffer
  8896. this.bindUnboundFramebuffer(texture._framebuffer);
  8897. }
  8898. onBeforeUnbind();
  8899. }
  8900. this.bindUnboundFramebuffer(null);
  8901. };
  8902. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8903. if (texture.generateMipMaps) {
  8904. var gl = this._gl;
  8905. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8906. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8907. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8908. }
  8909. };
  8910. Engine.prototype.flushFramebuffer = function () {
  8911. this._gl.flush();
  8912. };
  8913. Engine.prototype.restoreDefaultFramebuffer = function () {
  8914. if (this._currentRenderTarget) {
  8915. this.unBindFramebuffer(this._currentRenderTarget);
  8916. }
  8917. else {
  8918. this.bindUnboundFramebuffer(null);
  8919. }
  8920. if (this._cachedViewport) {
  8921. this.setViewport(this._cachedViewport);
  8922. }
  8923. this.wipeCaches();
  8924. };
  8925. // UBOs
  8926. Engine.prototype.createUniformBuffer = function (elements) {
  8927. var ubo = this._gl.createBuffer();
  8928. this.bindUniformBuffer(ubo);
  8929. if (elements instanceof Float32Array) {
  8930. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8931. }
  8932. else {
  8933. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8934. }
  8935. this.bindUniformBuffer(null);
  8936. ubo.references = 1;
  8937. return ubo;
  8938. };
  8939. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8940. var ubo = this._gl.createBuffer();
  8941. this.bindUniformBuffer(ubo);
  8942. if (elements instanceof Float32Array) {
  8943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8944. }
  8945. else {
  8946. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8947. }
  8948. this.bindUniformBuffer(null);
  8949. ubo.references = 1;
  8950. return ubo;
  8951. };
  8952. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8953. this.bindUniformBuffer(uniformBuffer);
  8954. if (offset === undefined) {
  8955. offset = 0;
  8956. }
  8957. if (count === undefined) {
  8958. if (elements instanceof Float32Array) {
  8959. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8960. }
  8961. else {
  8962. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8963. }
  8964. }
  8965. else {
  8966. if (elements instanceof Float32Array) {
  8967. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8968. }
  8969. else {
  8970. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8971. }
  8972. }
  8973. this.bindUniformBuffer(null);
  8974. };
  8975. // VBOs
  8976. Engine.prototype._resetVertexBufferBinding = function () {
  8977. this.bindArrayBuffer(null);
  8978. this._cachedVertexBuffers = null;
  8979. };
  8980. Engine.prototype.createVertexBuffer = function (vertices) {
  8981. var vbo = this._gl.createBuffer();
  8982. this.bindArrayBuffer(vbo);
  8983. if (vertices instanceof Float32Array) {
  8984. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8985. }
  8986. else {
  8987. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8988. }
  8989. this._resetVertexBufferBinding();
  8990. vbo.references = 1;
  8991. return vbo;
  8992. };
  8993. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8994. var vbo = this._gl.createBuffer();
  8995. this.bindArrayBuffer(vbo);
  8996. if (vertices instanceof Float32Array) {
  8997. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8998. }
  8999. else {
  9000. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9001. }
  9002. this._resetVertexBufferBinding();
  9003. vbo.references = 1;
  9004. return vbo;
  9005. };
  9006. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9007. this.bindArrayBuffer(vertexBuffer);
  9008. if (offset === undefined) {
  9009. offset = 0;
  9010. }
  9011. if (count === undefined) {
  9012. if (vertices instanceof Float32Array) {
  9013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9014. }
  9015. else {
  9016. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9017. }
  9018. }
  9019. else {
  9020. if (vertices instanceof Float32Array) {
  9021. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9022. }
  9023. else {
  9024. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9025. }
  9026. }
  9027. this._resetVertexBufferBinding();
  9028. };
  9029. Engine.prototype._resetIndexBufferBinding = function () {
  9030. this.bindIndexBuffer(null);
  9031. this._cachedIndexBuffer = null;
  9032. };
  9033. Engine.prototype.createIndexBuffer = function (indices) {
  9034. var vbo = this._gl.createBuffer();
  9035. this.bindIndexBuffer(vbo);
  9036. // Check for 32 bits indices
  9037. var arrayBuffer;
  9038. var need32Bits = false;
  9039. if (indices instanceof Uint16Array) {
  9040. arrayBuffer = indices;
  9041. }
  9042. else {
  9043. //check 32 bit support
  9044. if (this._caps.uintIndices) {
  9045. if (indices instanceof Uint32Array) {
  9046. arrayBuffer = indices;
  9047. need32Bits = true;
  9048. }
  9049. else {
  9050. //number[] or Int32Array, check if 32 bit is necessary
  9051. for (var index = 0; index < indices.length; index++) {
  9052. if (indices[index] > 65535) {
  9053. need32Bits = true;
  9054. break;
  9055. }
  9056. }
  9057. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9058. }
  9059. }
  9060. else {
  9061. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9062. arrayBuffer = new Uint16Array(indices);
  9063. }
  9064. }
  9065. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9066. this._resetIndexBufferBinding();
  9067. vbo.references = 1;
  9068. vbo.is32Bits = need32Bits;
  9069. return vbo;
  9070. };
  9071. Engine.prototype.bindArrayBuffer = function (buffer) {
  9072. if (!this._vaoRecordInProgress) {
  9073. this._unbindVertexArrayObject();
  9074. }
  9075. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9076. };
  9077. Engine.prototype.bindUniformBuffer = function (buffer) {
  9078. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9079. };
  9080. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9081. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9082. };
  9083. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9084. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9085. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9086. };
  9087. ;
  9088. Engine.prototype.bindIndexBuffer = function (buffer) {
  9089. if (!this._vaoRecordInProgress) {
  9090. this._unbindVertexArrayObject();
  9091. }
  9092. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9093. };
  9094. Engine.prototype.bindBuffer = function (buffer, target) {
  9095. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9096. this._gl.bindBuffer(target, buffer);
  9097. this._currentBoundBuffer[target] = buffer;
  9098. }
  9099. };
  9100. Engine.prototype.updateArrayBuffer = function (data) {
  9101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9102. };
  9103. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9104. var pointer = this._currentBufferPointers[indx];
  9105. var changed = false;
  9106. if (!pointer.active) {
  9107. changed = true;
  9108. pointer.active = true;
  9109. pointer.index = indx;
  9110. pointer.size = size;
  9111. pointer.type = type;
  9112. pointer.normalized = normalized;
  9113. pointer.stride = stride;
  9114. pointer.offset = offset;
  9115. pointer.buffer = buffer;
  9116. }
  9117. else {
  9118. if (pointer.buffer !== buffer) {
  9119. pointer.buffer = buffer;
  9120. changed = true;
  9121. }
  9122. if (pointer.size !== size) {
  9123. pointer.size = size;
  9124. changed = true;
  9125. }
  9126. if (pointer.type !== type) {
  9127. pointer.type = type;
  9128. changed = true;
  9129. }
  9130. if (pointer.normalized !== normalized) {
  9131. pointer.normalized = normalized;
  9132. changed = true;
  9133. }
  9134. if (pointer.stride !== stride) {
  9135. pointer.stride = stride;
  9136. changed = true;
  9137. }
  9138. if (pointer.offset !== offset) {
  9139. pointer.offset = offset;
  9140. changed = true;
  9141. }
  9142. }
  9143. if (changed || this._vaoRecordInProgress) {
  9144. this.bindArrayBuffer(buffer);
  9145. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9146. }
  9147. };
  9148. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9149. if (indexBuffer == null) {
  9150. return;
  9151. }
  9152. if (this._cachedIndexBuffer !== indexBuffer) {
  9153. this._cachedIndexBuffer = indexBuffer;
  9154. this.bindIndexBuffer(indexBuffer);
  9155. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9156. }
  9157. };
  9158. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9159. var attributes = effect.getAttributesNames();
  9160. if (!this._vaoRecordInProgress) {
  9161. this._unbindVertexArrayObject();
  9162. }
  9163. this.unbindAllAttributes();
  9164. for (var index = 0; index < attributes.length; index++) {
  9165. var order = effect.getAttributeLocation(index);
  9166. if (order >= 0) {
  9167. var vertexBuffer = vertexBuffers[attributes[index]];
  9168. if (!vertexBuffer) {
  9169. continue;
  9170. }
  9171. this._gl.enableVertexAttribArray(order);
  9172. if (!this._vaoRecordInProgress) {
  9173. this._vertexAttribArraysEnabled[order] = true;
  9174. }
  9175. var buffer = vertexBuffer.getBuffer();
  9176. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9177. if (vertexBuffer.getIsInstanced()) {
  9178. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9179. if (!this._vaoRecordInProgress) {
  9180. this._currentInstanceLocations.push(order);
  9181. this._currentInstanceBuffers.push(buffer);
  9182. }
  9183. }
  9184. }
  9185. }
  9186. };
  9187. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9188. var vao = this._gl.createVertexArray();
  9189. this._vaoRecordInProgress = true;
  9190. this._gl.bindVertexArray(vao);
  9191. this._mustWipeVertexAttributes = true;
  9192. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9193. this.bindIndexBuffer(indexBuffer);
  9194. this._vaoRecordInProgress = false;
  9195. this._gl.bindVertexArray(null);
  9196. return vao;
  9197. };
  9198. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9199. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9200. this._cachedVertexArrayObject = vertexArrayObject;
  9201. this._gl.bindVertexArray(vertexArrayObject);
  9202. this._cachedVertexBuffers = null;
  9203. this._cachedIndexBuffer = null;
  9204. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9205. this._mustWipeVertexAttributes = true;
  9206. }
  9207. };
  9208. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9209. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9210. this._cachedVertexBuffers = vertexBuffer;
  9211. this._cachedEffectForVertexBuffers = effect;
  9212. var attributesCount = effect.getAttributesCount();
  9213. this._unbindVertexArrayObject();
  9214. this.unbindAllAttributes();
  9215. var offset = 0;
  9216. for (var index = 0; index < attributesCount; index++) {
  9217. if (index < vertexDeclaration.length) {
  9218. var order = effect.getAttributeLocation(index);
  9219. if (order >= 0) {
  9220. this._gl.enableVertexAttribArray(order);
  9221. this._vertexAttribArraysEnabled[order] = true;
  9222. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9223. }
  9224. offset += vertexDeclaration[index] * 4;
  9225. }
  9226. }
  9227. }
  9228. this._bindIndexBufferWithCache(indexBuffer);
  9229. };
  9230. Engine.prototype._unbindVertexArrayObject = function () {
  9231. if (!this._cachedVertexArrayObject) {
  9232. return;
  9233. }
  9234. this._cachedVertexArrayObject = null;
  9235. this._gl.bindVertexArray(null);
  9236. };
  9237. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9238. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9239. this._cachedVertexBuffers = vertexBuffers;
  9240. this._cachedEffectForVertexBuffers = effect;
  9241. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9242. }
  9243. this._bindIndexBufferWithCache(indexBuffer);
  9244. };
  9245. Engine.prototype.unbindInstanceAttributes = function () {
  9246. var boundBuffer;
  9247. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9248. var instancesBuffer = this._currentInstanceBuffers[i];
  9249. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9250. boundBuffer = instancesBuffer;
  9251. this.bindArrayBuffer(instancesBuffer);
  9252. }
  9253. var offsetLocation = this._currentInstanceLocations[i];
  9254. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9255. }
  9256. this._currentInstanceBuffers.length = 0;
  9257. this._currentInstanceLocations.length = 0;
  9258. };
  9259. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9260. this._gl.deleteVertexArray(vao);
  9261. };
  9262. Engine.prototype._releaseBuffer = function (buffer) {
  9263. buffer.references--;
  9264. if (buffer.references === 0) {
  9265. this._gl.deleteBuffer(buffer);
  9266. return true;
  9267. }
  9268. return false;
  9269. };
  9270. Engine.prototype.createInstancesBuffer = function (capacity) {
  9271. var buffer = this._gl.createBuffer();
  9272. buffer.capacity = capacity;
  9273. this.bindArrayBuffer(buffer);
  9274. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9275. return buffer;
  9276. };
  9277. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9278. this._gl.deleteBuffer(buffer);
  9279. };
  9280. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9281. this.bindArrayBuffer(instancesBuffer);
  9282. if (data) {
  9283. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9284. }
  9285. if (offsetLocations[0].index !== undefined) {
  9286. var stride = 0;
  9287. for (var i = 0; i < offsetLocations.length; i++) {
  9288. var ai = offsetLocations[i];
  9289. stride += ai.attributeSize * 4;
  9290. }
  9291. for (var i = 0; i < offsetLocations.length; i++) {
  9292. var ai = offsetLocations[i];
  9293. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9294. this._gl.enableVertexAttribArray(ai.index);
  9295. this._vertexAttribArraysEnabled[ai.index] = true;
  9296. }
  9297. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9298. this._gl.vertexAttribDivisor(ai.index, 1);
  9299. this._currentInstanceLocations.push(ai.index);
  9300. this._currentInstanceBuffers.push(instancesBuffer);
  9301. }
  9302. }
  9303. else {
  9304. for (var index = 0; index < 4; index++) {
  9305. var offsetLocation = offsetLocations[index];
  9306. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9307. this._gl.enableVertexAttribArray(offsetLocation);
  9308. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9309. }
  9310. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9311. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9312. this._currentInstanceLocations.push(offsetLocation);
  9313. this._currentInstanceBuffers.push(instancesBuffer);
  9314. }
  9315. }
  9316. };
  9317. Engine.prototype.applyStates = function () {
  9318. this._depthCullingState.apply(this._gl);
  9319. this._stencilState.apply(this._gl);
  9320. this._alphaState.apply(this._gl);
  9321. };
  9322. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9323. // Apply states
  9324. this.applyStates();
  9325. this._drawCalls.addCount(1, false);
  9326. // Render
  9327. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9328. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9329. if (instancesCount) {
  9330. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9331. return;
  9332. }
  9333. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9334. };
  9335. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9336. // Apply states
  9337. this.applyStates();
  9338. this._drawCalls.addCount(1, false);
  9339. if (instancesCount) {
  9340. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9341. return;
  9342. }
  9343. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9344. };
  9345. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9346. // Apply states
  9347. this.applyStates();
  9348. this._drawCalls.addCount(1, false);
  9349. if (instancesCount) {
  9350. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9351. return;
  9352. }
  9353. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9354. };
  9355. // Shaders
  9356. Engine.prototype._releaseEffect = function (effect) {
  9357. if (this._compiledEffects[effect._key]) {
  9358. delete this._compiledEffects[effect._key];
  9359. if (effect.getProgram()) {
  9360. this._gl.deleteProgram(effect.getProgram());
  9361. }
  9362. }
  9363. };
  9364. /**
  9365. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9366. * @param samplers An array of string used to represent textures
  9367. */
  9368. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9369. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9370. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9371. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9372. if (this._compiledEffects[name]) {
  9373. var compiledEffect = this._compiledEffects[name];
  9374. if (onCompiled && compiledEffect.isReady()) {
  9375. onCompiled(compiledEffect);
  9376. }
  9377. return compiledEffect;
  9378. }
  9379. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9380. effect._key = name;
  9381. this._compiledEffects[name] = effect;
  9382. return effect;
  9383. };
  9384. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9385. if (uniformsNames === void 0) { uniformsNames = []; }
  9386. if (samplers === void 0) { samplers = []; }
  9387. if (defines === void 0) { defines = ""; }
  9388. return this.createEffect({
  9389. vertex: "particles",
  9390. fragmentElement: fragmentName
  9391. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9392. };
  9393. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9394. context = context || this._gl;
  9395. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9396. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9397. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9398. var shaderProgram = context.createProgram();
  9399. context.attachShader(shaderProgram, vertexShader);
  9400. context.attachShader(shaderProgram, fragmentShader);
  9401. context.linkProgram(shaderProgram);
  9402. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9403. if (!linked) {
  9404. context.validateProgram(shaderProgram);
  9405. var error = context.getProgramInfoLog(shaderProgram);
  9406. if (error) {
  9407. throw new Error(error);
  9408. }
  9409. }
  9410. context.deleteShader(vertexShader);
  9411. context.deleteShader(fragmentShader);
  9412. return shaderProgram;
  9413. };
  9414. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9415. var results = [];
  9416. for (var index = 0; index < uniformsNames.length; index++) {
  9417. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9418. }
  9419. return results;
  9420. };
  9421. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9422. var results = [];
  9423. for (var index = 0; index < attributesNames.length; index++) {
  9424. try {
  9425. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9426. }
  9427. catch (e) {
  9428. results.push(-1);
  9429. }
  9430. }
  9431. return results;
  9432. };
  9433. Engine.prototype.enableEffect = function (effect) {
  9434. // Use program
  9435. this.setProgram(effect.getProgram());
  9436. this._currentEffect = effect;
  9437. if (effect.onBind) {
  9438. effect.onBind(effect);
  9439. }
  9440. effect.onBindObservable.notifyObservers(effect);
  9441. };
  9442. Engine.prototype.setIntArray = function (uniform, array) {
  9443. if (!uniform)
  9444. return;
  9445. this._gl.uniform1iv(uniform, array);
  9446. };
  9447. Engine.prototype.setIntArray2 = function (uniform, array) {
  9448. if (!uniform || array.length % 2 !== 0)
  9449. return;
  9450. this._gl.uniform2iv(uniform, array);
  9451. };
  9452. Engine.prototype.setIntArray3 = function (uniform, array) {
  9453. if (!uniform || array.length % 3 !== 0)
  9454. return;
  9455. this._gl.uniform3iv(uniform, array);
  9456. };
  9457. Engine.prototype.setIntArray4 = function (uniform, array) {
  9458. if (!uniform || array.length % 4 !== 0)
  9459. return;
  9460. this._gl.uniform4iv(uniform, array);
  9461. };
  9462. Engine.prototype.setFloatArray = function (uniform, array) {
  9463. if (!uniform)
  9464. return;
  9465. this._gl.uniform1fv(uniform, array);
  9466. };
  9467. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9468. if (!uniform || array.length % 2 !== 0)
  9469. return;
  9470. this._gl.uniform2fv(uniform, array);
  9471. };
  9472. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9473. if (!uniform || array.length % 3 !== 0)
  9474. return;
  9475. this._gl.uniform3fv(uniform, array);
  9476. };
  9477. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9478. if (!uniform || array.length % 4 !== 0)
  9479. return;
  9480. this._gl.uniform4fv(uniform, array);
  9481. };
  9482. Engine.prototype.setArray = function (uniform, array) {
  9483. if (!uniform)
  9484. return;
  9485. this._gl.uniform1fv(uniform, array);
  9486. };
  9487. Engine.prototype.setArray2 = function (uniform, array) {
  9488. if (!uniform || array.length % 2 !== 0)
  9489. return;
  9490. this._gl.uniform2fv(uniform, array);
  9491. };
  9492. Engine.prototype.setArray3 = function (uniform, array) {
  9493. if (!uniform || array.length % 3 !== 0)
  9494. return;
  9495. this._gl.uniform3fv(uniform, array);
  9496. };
  9497. Engine.prototype.setArray4 = function (uniform, array) {
  9498. if (!uniform || array.length % 4 !== 0)
  9499. return;
  9500. this._gl.uniform4fv(uniform, array);
  9501. };
  9502. Engine.prototype.setMatrices = function (uniform, matrices) {
  9503. if (!uniform)
  9504. return;
  9505. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9506. };
  9507. Engine.prototype.setMatrix = function (uniform, matrix) {
  9508. if (!uniform)
  9509. return;
  9510. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9511. };
  9512. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9513. if (!uniform)
  9514. return;
  9515. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9516. };
  9517. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9518. if (!uniform)
  9519. return;
  9520. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9521. };
  9522. Engine.prototype.setFloat = function (uniform, value) {
  9523. if (!uniform)
  9524. return;
  9525. this._gl.uniform1f(uniform, value);
  9526. };
  9527. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9528. if (!uniform)
  9529. return;
  9530. this._gl.uniform2f(uniform, x, y);
  9531. };
  9532. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9533. if (!uniform)
  9534. return;
  9535. this._gl.uniform3f(uniform, x, y, z);
  9536. };
  9537. Engine.prototype.setBool = function (uniform, bool) {
  9538. if (!uniform)
  9539. return;
  9540. this._gl.uniform1i(uniform, bool);
  9541. };
  9542. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9543. if (!uniform)
  9544. return;
  9545. this._gl.uniform4f(uniform, x, y, z, w);
  9546. };
  9547. Engine.prototype.setColor3 = function (uniform, color3) {
  9548. if (!uniform)
  9549. return;
  9550. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9551. };
  9552. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9553. if (!uniform)
  9554. return;
  9555. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9556. };
  9557. // States
  9558. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9559. if (zOffset === void 0) { zOffset = 0; }
  9560. if (reverseSide === void 0) { reverseSide = false; }
  9561. // Culling
  9562. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9563. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9564. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9565. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9566. if (culling) {
  9567. this._depthCullingState.cullFace = cullFace;
  9568. this._depthCullingState.cull = true;
  9569. }
  9570. else {
  9571. this._depthCullingState.cull = false;
  9572. }
  9573. }
  9574. // Z offset
  9575. this.setZOffset(zOffset);
  9576. };
  9577. Engine.prototype.setZOffset = function (value) {
  9578. this._depthCullingState.zOffset = value;
  9579. };
  9580. Engine.prototype.getZOffset = function () {
  9581. return this._depthCullingState.zOffset;
  9582. };
  9583. Engine.prototype.setDepthBuffer = function (enable) {
  9584. this._depthCullingState.depthTest = enable;
  9585. };
  9586. Engine.prototype.getDepthWrite = function () {
  9587. return this._depthCullingState.depthMask;
  9588. };
  9589. Engine.prototype.setDepthWrite = function (enable) {
  9590. this._depthCullingState.depthMask = enable;
  9591. };
  9592. Engine.prototype.setColorWrite = function (enable) {
  9593. this._gl.colorMask(enable, enable, enable, enable);
  9594. this._colorWrite = enable;
  9595. };
  9596. Engine.prototype.getColorWrite = function () {
  9597. return this._colorWrite;
  9598. };
  9599. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9600. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9601. };
  9602. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9603. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9604. if (this._alphaMode === mode) {
  9605. return;
  9606. }
  9607. switch (mode) {
  9608. case Engine.ALPHA_DISABLE:
  9609. this._alphaState.alphaBlend = false;
  9610. break;
  9611. case Engine.ALPHA_PREMULTIPLIED:
  9612. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9613. this._alphaState.alphaBlend = true;
  9614. break;
  9615. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9616. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9617. this._alphaState.alphaBlend = true;
  9618. break;
  9619. case Engine.ALPHA_COMBINE:
  9620. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9621. this._alphaState.alphaBlend = true;
  9622. break;
  9623. case Engine.ALPHA_ONEONE:
  9624. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9625. this._alphaState.alphaBlend = true;
  9626. break;
  9627. case Engine.ALPHA_ADD:
  9628. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9629. this._alphaState.alphaBlend = true;
  9630. break;
  9631. case Engine.ALPHA_SUBTRACT:
  9632. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9633. this._alphaState.alphaBlend = true;
  9634. break;
  9635. case Engine.ALPHA_MULTIPLY:
  9636. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9637. this._alphaState.alphaBlend = true;
  9638. break;
  9639. case Engine.ALPHA_MAXIMIZED:
  9640. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9641. this._alphaState.alphaBlend = true;
  9642. break;
  9643. case Engine.ALPHA_INTERPOLATE:
  9644. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9645. this._alphaState.alphaBlend = true;
  9646. break;
  9647. case Engine.ALPHA_SCREENMODE:
  9648. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9649. this._alphaState.alphaBlend = true;
  9650. break;
  9651. }
  9652. if (!noDepthWriteChange) {
  9653. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9654. }
  9655. this._alphaMode = mode;
  9656. };
  9657. Engine.prototype.getAlphaMode = function () {
  9658. return this._alphaMode;
  9659. };
  9660. Engine.prototype.setAlphaTesting = function (enable) {
  9661. this._alphaTest = enable;
  9662. };
  9663. Engine.prototype.getAlphaTesting = function () {
  9664. return !!this._alphaTest;
  9665. };
  9666. // Textures
  9667. Engine.prototype.wipeCaches = function (bruteForce) {
  9668. if (this.preventCacheWipeBetweenFrames) {
  9669. return;
  9670. }
  9671. this.resetTextureCache();
  9672. this._currentEffect = null;
  9673. // 6/8/2017: deltakosh: Should not be required anymore.
  9674. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9675. if (bruteForce) {
  9676. this._currentProgram = null;
  9677. this._stencilState.reset();
  9678. this._depthCullingState.reset();
  9679. this.setDepthFunctionToLessOrEqual();
  9680. this._alphaState.reset();
  9681. }
  9682. this._cachedVertexBuffers = null;
  9683. this._cachedIndexBuffer = null;
  9684. this._cachedEffectForVertexBuffers = null;
  9685. this._unbindVertexArrayObject();
  9686. this.bindIndexBuffer(null);
  9687. this.bindArrayBuffer(null);
  9688. };
  9689. /**
  9690. * Set the compressed texture format to use, based on the formats you have, and the formats
  9691. * supported by the hardware / browser.
  9692. *
  9693. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9694. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9695. * to API arguments needed to compressed textures. This puts the burden on the container
  9696. * generator to house the arcane code for determining these for current & future formats.
  9697. *
  9698. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9699. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9700. *
  9701. * Note: The result of this call is not taken into account when a texture is base64.
  9702. *
  9703. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9704. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9705. *
  9706. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9707. * @returns The extension selected.
  9708. */
  9709. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9710. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9711. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9712. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9713. return this._textureFormatInUse = this._texturesSupported[i];
  9714. }
  9715. }
  9716. }
  9717. // actively set format to nothing, to allow this to be called more than once
  9718. // and possibly fail the 2nd time
  9719. return this._textureFormatInUse = null;
  9720. };
  9721. Engine.prototype._createTexture = function () {
  9722. return this._gl.createTexture();
  9723. };
  9724. /**
  9725. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9726. * @param {string} urlArg- This contains one of the following:
  9727. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9728. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9729. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9730. *
  9731. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9732. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9733. * @param {Scene} scene- Needed for loading to the correct scene.
  9734. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9735. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9736. * @param {callback} onError- Optional callback to be called upon failure.
  9737. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9738. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9739. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9740. *
  9741. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9742. */
  9743. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9744. var _this = this;
  9745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9746. if (onLoad === void 0) { onLoad = null; }
  9747. if (onError === void 0) { onError = null; }
  9748. if (buffer === void 0) { buffer = null; }
  9749. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9750. var fromData = url.substr(0, 5) === "data:";
  9751. var fromBlob = url.substr(0, 5) === "blob:";
  9752. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9753. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9754. // establish the file extension, if possible
  9755. var lastDot = url.lastIndexOf('.');
  9756. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9757. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9758. var isTGA = (extension === ".tga");
  9759. // determine if a ktx file should be substituted
  9760. var isKTX = false;
  9761. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9762. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9763. isKTX = true;
  9764. }
  9765. if (scene) {
  9766. scene._addPendingData(texture);
  9767. }
  9768. texture.url = url;
  9769. texture.generateMipMaps = !noMipmap;
  9770. texture.samplingMode = samplingMode;
  9771. texture.invertY = invertY;
  9772. if (!this._doNotHandleContextLost) {
  9773. // Keep a link to the buffer only if we plan to handle context lost
  9774. texture._buffer = buffer;
  9775. }
  9776. if (onLoad) {
  9777. texture.onLoadedObservable.add(onLoad);
  9778. }
  9779. if (!fallBack)
  9780. this._internalTexturesCache.push(texture);
  9781. var onerror = function () {
  9782. if (scene) {
  9783. scene._removePendingData(texture);
  9784. }
  9785. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9786. if (isKTX) {
  9787. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9788. }
  9789. else if (onError) {
  9790. onError();
  9791. }
  9792. };
  9793. var callback;
  9794. // processing for non-image formats
  9795. if (isKTX || isTGA || isDDS) {
  9796. if (isKTX) {
  9797. callback = function (data) {
  9798. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9799. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9800. ktx.uploadLevels(_this._gl, !noMipmap);
  9801. return false;
  9802. }, samplingMode);
  9803. };
  9804. }
  9805. else if (isTGA) {
  9806. callback = function (arrayBuffer) {
  9807. var data = new Uint8Array(arrayBuffer);
  9808. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9809. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9810. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9811. return false;
  9812. }, samplingMode);
  9813. };
  9814. }
  9815. else if (isDDS) {
  9816. callback = function (data) {
  9817. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9818. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9819. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9820. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9821. return false;
  9822. }, samplingMode);
  9823. };
  9824. }
  9825. if (!buffer) {
  9826. BABYLON.Tools.LoadFile(url, function (data) {
  9827. callback(data);
  9828. }, null, scene ? scene.database : null, true, onerror);
  9829. }
  9830. else {
  9831. callback(buffer);
  9832. }
  9833. // image format processing
  9834. }
  9835. else {
  9836. var onload = function (img) {
  9837. if (fromBlob && !_this._doNotHandleContextLost) {
  9838. // We need to store the image if we need to rebuild the texture
  9839. // in case of a webgl context lost
  9840. texture._buffer = img;
  9841. }
  9842. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9843. var gl = _this._gl;
  9844. var isPot = (img.width === potWidth && img.height === potHeight);
  9845. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9846. if (isPot) {
  9847. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9848. return false;
  9849. }
  9850. // Using shaders to rescale because canvas.drawImage is lossy
  9851. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9852. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9853. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9858. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9859. _this._releaseTexture(source);
  9860. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9861. continuationCallback();
  9862. });
  9863. return true;
  9864. }, samplingMode);
  9865. };
  9866. if (!fromData || isBase64)
  9867. if (buffer instanceof HTMLImageElement) {
  9868. onload(buffer);
  9869. }
  9870. else {
  9871. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9872. }
  9873. else if (buffer instanceof Array || typeof buffer === "string")
  9874. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9875. else
  9876. onload(buffer);
  9877. }
  9878. return texture;
  9879. };
  9880. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9881. var _this = this;
  9882. var rtt = this.createRenderTargetTexture({
  9883. width: destination.width,
  9884. height: destination.height,
  9885. }, {
  9886. generateMipMaps: false,
  9887. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9888. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9889. generateDepthBuffer: false,
  9890. generateStencilBuffer: false
  9891. });
  9892. if (!this._rescalePostProcess) {
  9893. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9894. }
  9895. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9896. _this._rescalePostProcess.onApply = function (effect) {
  9897. effect._bindTexture("textureSampler", source);
  9898. };
  9899. var hostingScene = scene;
  9900. if (!hostingScene) {
  9901. hostingScene = _this.scenes[_this.scenes.length - 1];
  9902. }
  9903. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9904. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9905. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9906. _this.unBindFramebuffer(rtt);
  9907. _this._releaseTexture(rtt);
  9908. if (onComplete) {
  9909. onComplete();
  9910. }
  9911. });
  9912. };
  9913. Engine.prototype._getInternalFormat = function (format) {
  9914. var internalFormat = this._gl.RGBA;
  9915. switch (format) {
  9916. case Engine.TEXTUREFORMAT_ALPHA:
  9917. internalFormat = this._gl.ALPHA;
  9918. break;
  9919. case Engine.TEXTUREFORMAT_LUMINANCE:
  9920. internalFormat = this._gl.LUMINANCE;
  9921. break;
  9922. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9923. internalFormat = this._gl.LUMINANCE_ALPHA;
  9924. break;
  9925. case Engine.TEXTUREFORMAT_RGB:
  9926. internalFormat = this._gl.RGB;
  9927. break;
  9928. case Engine.TEXTUREFORMAT_RGBA:
  9929. internalFormat = this._gl.RGBA;
  9930. break;
  9931. }
  9932. return internalFormat;
  9933. };
  9934. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9935. if (compression === void 0) { compression = null; }
  9936. var internalFormat = this._getInternalFormat(format);
  9937. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9938. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9939. if (!this._doNotHandleContextLost) {
  9940. texture._bufferView = data;
  9941. texture.format = format;
  9942. texture.invertY = invertY;
  9943. texture._compression = compression;
  9944. }
  9945. if (texture.width % 4 !== 0) {
  9946. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9947. }
  9948. if (compression) {
  9949. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9950. }
  9951. else {
  9952. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9953. }
  9954. if (texture.generateMipMaps) {
  9955. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9956. }
  9957. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9958. this.resetTextureCache();
  9959. texture.isReady = true;
  9960. };
  9961. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9962. if (compression === void 0) { compression = null; }
  9963. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9964. texture.baseWidth = width;
  9965. texture.baseHeight = height;
  9966. texture.width = width;
  9967. texture.height = height;
  9968. texture.format = format;
  9969. texture.generateMipMaps = generateMipMaps;
  9970. texture.samplingMode = samplingMode;
  9971. texture.invertY = invertY;
  9972. texture._compression = compression;
  9973. if (!this._doNotHandleContextLost) {
  9974. texture._bufferView = data;
  9975. }
  9976. this.updateRawTexture(texture, data, format, invertY, compression);
  9977. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9978. // Filters
  9979. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9980. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9981. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9982. if (generateMipMaps) {
  9983. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9984. }
  9985. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9986. this._internalTexturesCache.push(texture);
  9987. return texture;
  9988. };
  9989. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9990. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9991. texture.baseWidth = width;
  9992. texture.baseHeight = height;
  9993. if (generateMipMaps) {
  9994. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9995. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9996. }
  9997. this.resetTextureCache();
  9998. texture.width = width;
  9999. texture.height = height;
  10000. texture.isReady = false;
  10001. texture.generateMipMaps = generateMipMaps;
  10002. texture.samplingMode = samplingMode;
  10003. this.updateTextureSamplingMode(samplingMode, texture);
  10004. this._internalTexturesCache.push(texture);
  10005. return texture;
  10006. };
  10007. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10008. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10009. if (texture.isCube) {
  10010. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10011. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10012. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10013. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10014. }
  10015. else {
  10016. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10017. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10018. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10019. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10020. }
  10021. texture.samplingMode = samplingMode;
  10022. };
  10023. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10024. if (premulAlpha === void 0) { premulAlpha = false; }
  10025. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10026. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10027. if (premulAlpha) {
  10028. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10029. }
  10030. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10031. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10032. if (texture.generateMipMaps) {
  10033. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10034. }
  10035. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10036. if (premulAlpha) {
  10037. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10038. }
  10039. this.resetTextureCache();
  10040. texture.isReady = true;
  10041. };
  10042. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10043. if (texture._isDisabled) {
  10044. return;
  10045. }
  10046. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10047. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10048. try {
  10049. // Testing video texture support
  10050. if (this._videoTextureSupported === undefined) {
  10051. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10052. if (this._gl.getError() !== 0) {
  10053. this._videoTextureSupported = false;
  10054. }
  10055. else {
  10056. this._videoTextureSupported = true;
  10057. }
  10058. }
  10059. // Copy video through the current working canvas if video texture is not supported
  10060. if (!this._videoTextureSupported) {
  10061. if (!texture._workingCanvas) {
  10062. texture._workingCanvas = document.createElement("canvas");
  10063. texture._workingContext = texture._workingCanvas.getContext("2d");
  10064. texture._workingCanvas.width = texture.width;
  10065. texture._workingCanvas.height = texture.height;
  10066. }
  10067. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10068. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10069. }
  10070. else {
  10071. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10072. }
  10073. if (texture.generateMipMaps) {
  10074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10075. }
  10076. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10077. this.resetTextureCache();
  10078. texture.isReady = true;
  10079. }
  10080. catch (ex) {
  10081. // Something unexpected
  10082. // Let's disable the texture
  10083. texture._isDisabled = true;
  10084. }
  10085. };
  10086. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10087. var fullOptions = new RenderTargetCreationOptions();
  10088. if (options !== undefined && typeof options === "object") {
  10089. fullOptions.generateMipMaps = options.generateMipMaps;
  10090. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10091. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10092. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10093. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10094. }
  10095. else {
  10096. fullOptions.generateMipMaps = options;
  10097. fullOptions.generateDepthBuffer = true;
  10098. fullOptions.generateStencilBuffer = false;
  10099. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10100. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10101. }
  10102. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10103. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10104. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10105. }
  10106. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10107. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10108. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10109. }
  10110. var gl = this._gl;
  10111. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10112. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10113. var width = size.width || size;
  10114. var height = size.height || size;
  10115. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10116. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10117. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10118. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10119. }
  10120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10121. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10124. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10125. // Create the framebuffer
  10126. var framebuffer = gl.createFramebuffer();
  10127. this.bindUnboundFramebuffer(framebuffer);
  10128. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10129. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10130. if (fullOptions.generateMipMaps) {
  10131. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10132. }
  10133. // Unbind
  10134. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10135. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10136. this.bindUnboundFramebuffer(null);
  10137. texture._framebuffer = framebuffer;
  10138. texture.baseWidth = width;
  10139. texture.baseHeight = height;
  10140. texture.width = width;
  10141. texture.height = height;
  10142. texture.isReady = true;
  10143. texture.samples = 1;
  10144. texture.generateMipMaps = fullOptions.generateMipMaps;
  10145. texture.samplingMode = fullOptions.samplingMode;
  10146. texture.type = fullOptions.type;
  10147. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10148. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10149. this.resetTextureCache();
  10150. this._internalTexturesCache.push(texture);
  10151. return texture;
  10152. };
  10153. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10154. var generateMipMaps = false;
  10155. var generateDepthBuffer = true;
  10156. var generateStencilBuffer = false;
  10157. var generateDepthTexture = false;
  10158. var textureCount = 1;
  10159. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10160. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10161. var types = [], samplingModes = [];
  10162. if (options !== undefined) {
  10163. generateMipMaps = options.generateMipMaps;
  10164. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10165. generateStencilBuffer = options.generateStencilBuffer;
  10166. generateDepthTexture = options.generateDepthTexture;
  10167. textureCount = options.textureCount || 1;
  10168. if (options.types) {
  10169. types = options.types;
  10170. }
  10171. if (options.samplingModes) {
  10172. samplingModes = options.samplingModes;
  10173. }
  10174. }
  10175. var gl = this._gl;
  10176. // Create the framebuffer
  10177. var framebuffer = gl.createFramebuffer();
  10178. this.bindUnboundFramebuffer(framebuffer);
  10179. var width = size.width || size;
  10180. var height = size.height || size;
  10181. var textures = [];
  10182. var attachments = [];
  10183. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10184. for (var i = 0; i < textureCount; i++) {
  10185. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10186. var type = types[i] || defaultType;
  10187. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10188. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10189. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10190. }
  10191. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10192. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10193. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10194. }
  10195. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10196. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10197. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10198. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10199. }
  10200. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10201. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10202. textures.push(texture);
  10203. attachments.push(attachment);
  10204. gl.activeTexture(gl["TEXTURE" + i]);
  10205. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10207. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10210. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10211. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10212. if (generateMipMaps) {
  10213. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10214. }
  10215. // Unbind
  10216. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10217. texture._framebuffer = framebuffer;
  10218. texture._depthStencilBuffer = depthStencilBuffer;
  10219. texture.baseWidth = width;
  10220. texture.baseHeight = height;
  10221. texture.width = width;
  10222. texture.height = height;
  10223. texture.isReady = true;
  10224. texture.samples = 1;
  10225. texture.generateMipMaps = generateMipMaps;
  10226. texture.samplingMode = samplingMode;
  10227. texture.type = type;
  10228. texture._generateDepthBuffer = generateDepthBuffer;
  10229. texture._generateStencilBuffer = generateStencilBuffer;
  10230. this._internalTexturesCache.push(texture);
  10231. }
  10232. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10233. // Depth texture
  10234. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10235. gl.activeTexture(gl.TEXTURE0);
  10236. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10241. 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);
  10242. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10243. depthTexture._framebuffer = framebuffer;
  10244. depthTexture.baseWidth = width;
  10245. depthTexture.baseHeight = height;
  10246. depthTexture.width = width;
  10247. depthTexture.height = height;
  10248. depthTexture.isReady = true;
  10249. depthTexture.samples = 1;
  10250. depthTexture.generateMipMaps = generateMipMaps;
  10251. depthTexture.samplingMode = gl.NEAREST;
  10252. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10253. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10254. textures.push(depthTexture);
  10255. this._internalTexturesCache.push(depthTexture);
  10256. }
  10257. gl.drawBuffers(attachments);
  10258. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10259. this.bindUnboundFramebuffer(null);
  10260. this.resetTextureCache();
  10261. return textures;
  10262. };
  10263. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10264. if (samples === void 0) { samples = 1; }
  10265. var depthStencilBuffer = null;
  10266. var gl = this._gl;
  10267. // Create the depth/stencil buffer
  10268. if (generateStencilBuffer) {
  10269. depthStencilBuffer = gl.createRenderbuffer();
  10270. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10271. if (samples > 1) {
  10272. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10273. }
  10274. else {
  10275. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10276. }
  10277. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10278. }
  10279. else if (generateDepthBuffer) {
  10280. depthStencilBuffer = gl.createRenderbuffer();
  10281. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10282. if (samples > 1) {
  10283. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10284. }
  10285. else {
  10286. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10287. }
  10288. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10289. }
  10290. return depthStencilBuffer;
  10291. };
  10292. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10293. if (this.webGLVersion < 2) {
  10294. return 1;
  10295. }
  10296. if (texture.samples === samples) {
  10297. return samples;
  10298. }
  10299. var gl = this._gl;
  10300. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10301. // Dispose previous render buffers
  10302. if (texture._depthStencilBuffer) {
  10303. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10304. }
  10305. if (texture._MSAAFramebuffer) {
  10306. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10307. }
  10308. if (texture._MSAARenderBuffer) {
  10309. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10310. }
  10311. if (samples > 1) {
  10312. texture._MSAAFramebuffer = gl.createFramebuffer();
  10313. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10314. var colorRenderbuffer = gl.createRenderbuffer();
  10315. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10316. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10317. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10318. texture._MSAARenderBuffer = colorRenderbuffer;
  10319. }
  10320. else {
  10321. this.bindUnboundFramebuffer(texture._framebuffer);
  10322. }
  10323. texture.samples = samples;
  10324. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10325. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10326. this.bindUnboundFramebuffer(null);
  10327. return samples;
  10328. };
  10329. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10330. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10331. };
  10332. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10333. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10334. };
  10335. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10336. var gl = this._gl;
  10337. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10338. var generateMipMaps = true;
  10339. var generateDepthBuffer = true;
  10340. var generateStencilBuffer = false;
  10341. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10342. if (options !== undefined) {
  10343. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10344. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10345. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10346. if (options.samplingMode !== undefined) {
  10347. samplingMode = options.samplingMode;
  10348. }
  10349. }
  10350. texture.isCube = true;
  10351. texture.generateMipMaps = generateMipMaps;
  10352. texture.samples = 1;
  10353. texture.samplingMode = samplingMode;
  10354. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10355. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10356. for (var face = 0; face < 6; face++) {
  10357. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10358. }
  10359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10360. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10361. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10363. // Create the framebuffer
  10364. var framebuffer = gl.createFramebuffer();
  10365. this.bindUnboundFramebuffer(framebuffer);
  10366. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10367. // Mipmaps
  10368. if (texture.generateMipMaps) {
  10369. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10370. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10371. }
  10372. // Unbind
  10373. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10374. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10375. this.bindUnboundFramebuffer(null);
  10376. texture._framebuffer = framebuffer;
  10377. texture.width = size;
  10378. texture.height = size;
  10379. texture.isReady = true;
  10380. this.resetTextureCache();
  10381. this._internalTexturesCache.push(texture);
  10382. return texture;
  10383. };
  10384. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10385. var _this = this;
  10386. if (onError === void 0) { onError = null; }
  10387. if (forcedExtension === void 0) { forcedExtension = null; }
  10388. var callback = function (loadData) {
  10389. if (!loadData) {
  10390. if (onLoad) {
  10391. onLoad(null);
  10392. }
  10393. return;
  10394. }
  10395. var texture = loadData.texture;
  10396. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10397. texture._lodGenerationScale = scale;
  10398. texture._lodGenerationOffset = offset;
  10399. if (_this._caps.textureLOD) {
  10400. // Do not add extra process if texture lod is supported.
  10401. if (onLoad) {
  10402. onLoad(texture);
  10403. }
  10404. return;
  10405. }
  10406. var mipSlices = 3;
  10407. var gl = _this._gl;
  10408. var width = loadData.width;
  10409. if (!width) {
  10410. return;
  10411. }
  10412. var textures = [];
  10413. for (var i = 0; i < mipSlices; i++) {
  10414. //compute LOD from even spacing in smoothness (matching shader calculation)
  10415. var smoothness = i / (mipSlices - 1);
  10416. var roughness = 1 - smoothness;
  10417. var minLODIndex = offset; // roughness = 0
  10418. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10419. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10420. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10421. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10422. glTextureFromLod.isCube = true;
  10423. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10428. if (loadData.isDDS) {
  10429. var info = loadData.info;
  10430. var data = loadData.data;
  10431. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10432. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10433. }
  10434. else {
  10435. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10436. }
  10437. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10438. // Wrap in a base texture for easy binding.
  10439. var lodTexture = new BABYLON.BaseTexture(scene);
  10440. lodTexture.isCube = true;
  10441. lodTexture._texture = glTextureFromLod;
  10442. glTextureFromLod.isReady = true;
  10443. textures.push(lodTexture);
  10444. }
  10445. texture._lodTextureHigh = textures[2];
  10446. texture._lodTextureMid = textures[1];
  10447. texture._lodTextureLow = textures[0];
  10448. if (onLoad) {
  10449. onLoad(texture);
  10450. }
  10451. };
  10452. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10453. };
  10454. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10455. var _this = this;
  10456. if (onLoad === void 0) { onLoad = null; }
  10457. if (onError === void 0) { onError = null; }
  10458. if (forcedExtension === void 0) { forcedExtension = null; }
  10459. var gl = this._gl;
  10460. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10461. texture.isCube = true;
  10462. texture.url = rootUrl;
  10463. texture.generateMipMaps = !noMipmap;
  10464. if (!this._doNotHandleContextLost) {
  10465. texture._extension = forcedExtension;
  10466. texture._files = files;
  10467. }
  10468. var isKTX = false;
  10469. var isDDS = false;
  10470. var lastDot = rootUrl.lastIndexOf('.');
  10471. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10472. if (this._textureFormatInUse) {
  10473. extension = this._textureFormatInUse;
  10474. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10475. isKTX = true;
  10476. }
  10477. else {
  10478. isDDS = (extension === ".dds");
  10479. }
  10480. if (isKTX) {
  10481. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10482. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10483. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10484. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10485. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10486. ktx.uploadLevels(_this._gl, !noMipmap);
  10487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10490. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10491. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10492. _this.resetTextureCache();
  10493. texture.width = ktx.pixelWidth;
  10494. texture.height = ktx.pixelHeight;
  10495. texture.isReady = true;
  10496. }, null, null, true, onError);
  10497. }
  10498. else if (isDDS) {
  10499. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10500. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10501. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10502. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10503. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10504. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10505. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10506. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10507. }
  10508. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10510. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10512. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10513. _this.resetTextureCache();
  10514. texture.width = info.width;
  10515. texture.height = info.height;
  10516. texture.isReady = true;
  10517. texture.type = info.textureType;
  10518. if (onLoad) {
  10519. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10520. }
  10521. }, null, null, true, onError);
  10522. }
  10523. else {
  10524. cascadeLoad(rootUrl, scene, function (imgs) {
  10525. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10526. var height = width;
  10527. _this._prepareWorkingCanvas();
  10528. _this._workingCanvas.width = width;
  10529. _this._workingCanvas.height = height;
  10530. var faces = [
  10531. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10532. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10533. ];
  10534. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10535. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10536. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10537. for (var index = 0; index < faces.length; index++) {
  10538. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10539. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10540. }
  10541. if (!noMipmap) {
  10542. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10543. }
  10544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10548. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10549. _this.resetTextureCache();
  10550. texture.width = width;
  10551. texture.height = height;
  10552. texture.isReady = true;
  10553. texture.format = format;
  10554. texture.onLoadedObservable.notifyObservers(texture);
  10555. texture.onLoadedObservable.clear();
  10556. if (onLoad) {
  10557. onLoad();
  10558. }
  10559. }, files, onError);
  10560. }
  10561. this._internalTexturesCache.push(texture);
  10562. return texture;
  10563. };
  10564. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10565. if (compression === void 0) { compression = null; }
  10566. if (level === void 0) { level = 0; }
  10567. texture._bufferViewArray = data;
  10568. texture.format = format;
  10569. texture.type = type;
  10570. texture.invertY = invertY;
  10571. texture._compression = compression;
  10572. var gl = this._gl;
  10573. var textureType = this._getWebGLTextureType(type);
  10574. var internalFormat = this._getInternalFormat(format);
  10575. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10576. var needConversion = false;
  10577. if (internalFormat === gl.RGB) {
  10578. internalFormat = gl.RGBA;
  10579. needConversion = true;
  10580. }
  10581. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10582. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10583. if (texture.width % 4 !== 0) {
  10584. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10585. }
  10586. // Data are known to be in +X +Y +Z -X -Y -Z
  10587. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10588. var faceData = data[faceIndex];
  10589. if (compression) {
  10590. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10591. }
  10592. else {
  10593. if (needConversion) {
  10594. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10595. }
  10596. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10597. }
  10598. }
  10599. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10600. if (isPot && texture.generateMipMaps && level === 0) {
  10601. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10602. }
  10603. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10604. this.resetTextureCache();
  10605. texture.isReady = true;
  10606. };
  10607. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10608. if (compression === void 0) { compression = null; }
  10609. var gl = this._gl;
  10610. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10611. texture.isCube = true;
  10612. texture.generateMipMaps = generateMipMaps;
  10613. texture.format = format;
  10614. texture.type = type;
  10615. if (!this._doNotHandleContextLost) {
  10616. texture._bufferViewArray = data;
  10617. }
  10618. var textureType = this._getWebGLTextureType(type);
  10619. var internalFormat = this._getInternalFormat(format);
  10620. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10621. var needConversion = false;
  10622. if (internalFormat === gl.RGB) {
  10623. internalFormat = gl.RGBA;
  10624. needConversion = true;
  10625. }
  10626. var width = size;
  10627. var height = width;
  10628. texture.width = width;
  10629. texture.height = height;
  10630. // Double check on POT to generate Mips.
  10631. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10632. if (!isPot) {
  10633. generateMipMaps = false;
  10634. }
  10635. // Upload data if needed. The texture won't be ready until then.
  10636. if (data) {
  10637. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10638. }
  10639. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10640. // Filters
  10641. if (data && generateMipMaps) {
  10642. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10643. }
  10644. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10647. }
  10648. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10649. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10650. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10651. }
  10652. else {
  10653. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10656. }
  10657. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10658. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10659. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10660. return texture;
  10661. };
  10662. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10663. var _this = this;
  10664. if (onLoad === void 0) { onLoad = null; }
  10665. if (onError === void 0) { onError = null; }
  10666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10667. if (invertY === void 0) { invertY = false; }
  10668. var gl = this._gl;
  10669. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10670. scene._addPendingData(texture);
  10671. texture.url = url;
  10672. this._internalTexturesCache.push(texture);
  10673. var onerror = function () {
  10674. scene._removePendingData(texture);
  10675. if (onError) {
  10676. onError();
  10677. }
  10678. };
  10679. var internalCallback = function (data) {
  10680. var width = texture.width;
  10681. var height = texture.height;
  10682. var faceDataArrays = callback(data);
  10683. if (mipmmapGenerator) {
  10684. var textureType = _this._getWebGLTextureType(type);
  10685. var internalFormat = _this._getInternalFormat(format);
  10686. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10687. var needConversion = false;
  10688. if (internalFormat === gl.RGB) {
  10689. internalFormat = gl.RGBA;
  10690. needConversion = true;
  10691. }
  10692. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10693. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10694. var mipData = mipmmapGenerator(faceDataArrays);
  10695. for (var level = 0; level < mipData.length; level++) {
  10696. var mipSize = width >> level;
  10697. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10698. var mipFaceData = mipData[level][faceIndex];
  10699. if (needConversion) {
  10700. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10701. }
  10702. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10703. }
  10704. }
  10705. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10706. }
  10707. else {
  10708. texture.generateMipMaps = !noMipmap;
  10709. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10710. }
  10711. texture.isReady = true;
  10712. _this.resetTextureCache();
  10713. scene._removePendingData(texture);
  10714. if (onLoad) {
  10715. onLoad();
  10716. }
  10717. };
  10718. BABYLON.Tools.LoadFile(url, function (data) {
  10719. internalCallback(data);
  10720. }, onerror, scene.database, true);
  10721. return texture;
  10722. };
  10723. ;
  10724. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10725. var gl = this._gl;
  10726. if (!gl) {
  10727. return;
  10728. }
  10729. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10730. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10732. if (!noMipmap && !isCompressed) {
  10733. gl.generateMipmap(gl.TEXTURE_2D);
  10734. }
  10735. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10736. this.resetTextureCache();
  10737. if (scene) {
  10738. scene._removePendingData(texture);
  10739. }
  10740. texture.onLoadedObservable.notifyObservers(texture);
  10741. texture.onLoadedObservable.clear();
  10742. };
  10743. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10744. var _this = this;
  10745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10746. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10747. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10748. var gl = this._gl;
  10749. if (!gl) {
  10750. return;
  10751. }
  10752. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10753. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10754. texture.baseWidth = width;
  10755. texture.baseHeight = height;
  10756. texture.width = potWidth;
  10757. texture.height = potHeight;
  10758. texture.isReady = true;
  10759. if (processFunction(potWidth, potHeight, function () {
  10760. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10761. })) {
  10762. // Returning as texture needs extra async steps
  10763. return;
  10764. }
  10765. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10766. };
  10767. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10768. // Create new RGBA data container.
  10769. var rgbaData;
  10770. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10771. rgbaData = new Float32Array(width * height * 4);
  10772. }
  10773. else {
  10774. rgbaData = new Uint32Array(width * height * 4);
  10775. }
  10776. // Convert each pixel.
  10777. for (var x = 0; x < width; x++) {
  10778. for (var y = 0; y < height; y++) {
  10779. var index = (y * width + x) * 3;
  10780. var newIndex = (y * width + x) * 4;
  10781. // Map Old Value to new value.
  10782. rgbaData[newIndex + 0] = rgbData[index + 0];
  10783. rgbaData[newIndex + 1] = rgbData[index + 1];
  10784. rgbaData[newIndex + 2] = rgbData[index + 2];
  10785. // Add fully opaque alpha channel.
  10786. rgbaData[newIndex + 3] = 1;
  10787. }
  10788. }
  10789. return rgbaData;
  10790. };
  10791. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10792. var gl = this._gl;
  10793. if (texture._framebuffer) {
  10794. gl.deleteFramebuffer(texture._framebuffer);
  10795. texture._framebuffer = null;
  10796. }
  10797. if (texture._depthStencilBuffer) {
  10798. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10799. texture._depthStencilBuffer = null;
  10800. }
  10801. if (texture._MSAAFramebuffer) {
  10802. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10803. texture._MSAAFramebuffer = null;
  10804. }
  10805. if (texture._MSAARenderBuffer) {
  10806. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10807. texture._MSAARenderBuffer = null;
  10808. }
  10809. };
  10810. Engine.prototype._releaseTexture = function (texture) {
  10811. var gl = this._gl;
  10812. this._releaseFramebufferObjects(texture);
  10813. gl.deleteTexture(texture._webGLTexture);
  10814. // Unbind channels
  10815. this.unbindAllTextures();
  10816. var index = this._internalTexturesCache.indexOf(texture);
  10817. if (index !== -1) {
  10818. this._internalTexturesCache.splice(index, 1);
  10819. }
  10820. // Integrated fixed lod samplers.
  10821. if (texture._lodTextureHigh) {
  10822. texture._lodTextureHigh.dispose();
  10823. }
  10824. if (texture._lodTextureMid) {
  10825. texture._lodTextureMid.dispose();
  10826. }
  10827. if (texture._lodTextureLow) {
  10828. texture._lodTextureLow.dispose();
  10829. }
  10830. };
  10831. Engine.prototype.setProgram = function (program) {
  10832. if (this._currentProgram !== program) {
  10833. this._gl.useProgram(program);
  10834. this._currentProgram = program;
  10835. }
  10836. };
  10837. Engine.prototype.bindSamplers = function (effect) {
  10838. this.setProgram(effect.getProgram());
  10839. var samplers = effect.getSamplers();
  10840. for (var index = 0; index < samplers.length; index++) {
  10841. var uniform = effect.getUniform(samplers[index]);
  10842. this._gl.uniform1i(uniform, index);
  10843. }
  10844. this._currentEffect = null;
  10845. };
  10846. Engine.prototype.activateTexture = function (texture) {
  10847. if (this._activeTexture !== texture) {
  10848. this._gl.activeTexture(texture);
  10849. this._activeTexture = texture;
  10850. }
  10851. };
  10852. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10853. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10854. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10855. this._activeTexturesCache[this._activeTexture] = texture;
  10856. }
  10857. };
  10858. Engine.prototype._bindTexture = function (channel, texture) {
  10859. if (channel < 0) {
  10860. return;
  10861. }
  10862. this.activateTexture(this._gl.TEXTURE0 + channel);
  10863. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10864. };
  10865. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10866. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10867. };
  10868. Engine.prototype.unbindAllTextures = function () {
  10869. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10870. this.activateTexture(this._gl["TEXTURE" + channel]);
  10871. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10872. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10873. }
  10874. };
  10875. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10876. if (channel < 0) {
  10877. return;
  10878. }
  10879. this._gl.uniform1i(uniform, channel);
  10880. this._setTexture(channel, texture);
  10881. };
  10882. Engine.prototype._setTexture = function (channel, texture) {
  10883. // Not ready?
  10884. if (!texture) {
  10885. if (this._activeTexturesCache[channel] != null) {
  10886. this.activateTexture(this._gl["TEXTURE" + channel]);
  10887. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10888. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10889. }
  10890. return;
  10891. }
  10892. // Video
  10893. var alreadyActivated = false;
  10894. if (texture.video) {
  10895. this.activateTexture(this._gl["TEXTURE" + channel]);
  10896. alreadyActivated = true;
  10897. texture.update();
  10898. }
  10899. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10900. texture.delayLoad();
  10901. return;
  10902. }
  10903. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10904. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10905. if (this._activeTexturesCache[channel] === internalTexture) {
  10906. return;
  10907. }
  10908. if (!alreadyActivated) {
  10909. this.activateTexture(this._gl["TEXTURE" + channel]);
  10910. }
  10911. if (internalTexture.isCube) {
  10912. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10913. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10914. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10915. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10916. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10917. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10918. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10919. }
  10920. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10921. }
  10922. else {
  10923. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10924. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10925. internalTexture._cachedWrapU = texture.wrapU;
  10926. switch (texture.wrapU) {
  10927. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10928. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10929. break;
  10930. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10931. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10932. break;
  10933. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10934. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10935. break;
  10936. }
  10937. }
  10938. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10939. internalTexture._cachedWrapV = texture.wrapV;
  10940. switch (texture.wrapV) {
  10941. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10942. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10943. break;
  10944. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10945. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10946. break;
  10947. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10948. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10949. break;
  10950. }
  10951. }
  10952. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10953. }
  10954. };
  10955. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10956. if (channel < 0) {
  10957. return;
  10958. }
  10959. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10960. this._textureUnits = new Int32Array(textures.length);
  10961. }
  10962. for (var i = 0; i < textures.length; i++) {
  10963. this._textureUnits[i] = channel + i;
  10964. }
  10965. this._gl.uniform1iv(uniform, this._textureUnits);
  10966. for (var index = 0; index < textures.length; index++) {
  10967. this._setTexture(channel + index, textures[index]);
  10968. }
  10969. };
  10970. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10971. var internalTexture = texture.getInternalTexture();
  10972. if (!internalTexture) {
  10973. return;
  10974. }
  10975. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10976. var value = texture.anisotropicFilteringLevel;
  10977. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10978. value = 1;
  10979. }
  10980. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10981. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10982. internalTexture._cachedAnisotropicFilteringLevel = value;
  10983. }
  10984. };
  10985. Engine.prototype.readPixels = function (x, y, width, height) {
  10986. var data = new Uint8Array(height * width * 4);
  10987. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10988. return data;
  10989. };
  10990. /**
  10991. * Add an externaly attached data from its key.
  10992. * This method call will fail and return false, if such key already exists.
  10993. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10994. * @param key the unique key that identifies the data
  10995. * @param data the data object to associate to the key for this Engine instance
  10996. * @return true if no such key were already present and the data was added successfully, false otherwise
  10997. */
  10998. Engine.prototype.addExternalData = function (key, data) {
  10999. if (!this._externalData) {
  11000. this._externalData = new BABYLON.StringDictionary();
  11001. }
  11002. return this._externalData.add(key, data);
  11003. };
  11004. /**
  11005. * Get an externaly attached data from its key
  11006. * @param key the unique key that identifies the data
  11007. * @return the associated data, if present (can be null), or undefined if not present
  11008. */
  11009. Engine.prototype.getExternalData = function (key) {
  11010. if (!this._externalData) {
  11011. this._externalData = new BABYLON.StringDictionary();
  11012. }
  11013. return this._externalData.get(key);
  11014. };
  11015. /**
  11016. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11017. * @param key the unique key that identifies the data
  11018. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11019. * @return the associated data, can be null if the factory returned null.
  11020. */
  11021. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11022. if (!this._externalData) {
  11023. this._externalData = new BABYLON.StringDictionary();
  11024. }
  11025. return this._externalData.getOrAddWithFactory(key, factory);
  11026. };
  11027. /**
  11028. * Remove an externaly attached data from the Engine instance
  11029. * @param key the unique key that identifies the data
  11030. * @return true if the data was successfully removed, false if it doesn't exist
  11031. */
  11032. Engine.prototype.removeExternalData = function (key) {
  11033. if (!this._externalData) {
  11034. this._externalData = new BABYLON.StringDictionary();
  11035. }
  11036. return this._externalData.remove(key);
  11037. };
  11038. Engine.prototype.unbindAllAttributes = function () {
  11039. if (this._mustWipeVertexAttributes) {
  11040. this._mustWipeVertexAttributes = false;
  11041. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11042. this._gl.disableVertexAttribArray(i);
  11043. this._vertexAttribArraysEnabled[i] = false;
  11044. this._currentBufferPointers[i].active = false;
  11045. }
  11046. return;
  11047. }
  11048. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11049. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11050. continue;
  11051. }
  11052. this._gl.disableVertexAttribArray(i);
  11053. this._vertexAttribArraysEnabled[i] = false;
  11054. this._currentBufferPointers[i].active = false;
  11055. }
  11056. };
  11057. Engine.prototype.releaseEffects = function () {
  11058. for (var name in this._compiledEffects) {
  11059. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11060. }
  11061. this._compiledEffects = {};
  11062. };
  11063. // Dispose
  11064. Engine.prototype.dispose = function () {
  11065. this.hideLoadingUI();
  11066. this.stopRenderLoop();
  11067. // Release postProcesses
  11068. while (this.postProcesses.length) {
  11069. this.postProcesses[0].dispose();
  11070. }
  11071. // Empty texture
  11072. if (this._emptyTexture) {
  11073. this._releaseTexture(this._emptyTexture);
  11074. this._emptyTexture = null;
  11075. }
  11076. if (this._emptyCubeTexture) {
  11077. this._releaseTexture(this._emptyCubeTexture);
  11078. this._emptyCubeTexture = null;
  11079. }
  11080. // Rescale PP
  11081. if (this._rescalePostProcess) {
  11082. this._rescalePostProcess.dispose();
  11083. }
  11084. // Release scenes
  11085. while (this.scenes.length) {
  11086. this.scenes[0].dispose();
  11087. }
  11088. // Release audio engine
  11089. if (Engine.audioEngine) {
  11090. Engine.audioEngine.dispose();
  11091. }
  11092. // Release effects
  11093. this.releaseEffects();
  11094. // Unbind
  11095. this.unbindAllAttributes();
  11096. if (this._dummyFramebuffer) {
  11097. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11098. }
  11099. this._gl = null;
  11100. //WebVR
  11101. this.disableVR();
  11102. // Events
  11103. window.removeEventListener("blur", this._onBlur);
  11104. window.removeEventListener("focus", this._onFocus);
  11105. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11106. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11107. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11108. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11109. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11110. if (!this._doNotHandleContextLost) {
  11111. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11112. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11113. }
  11114. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11115. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11116. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11117. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11118. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11119. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11120. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11121. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11122. // Remove from Instances
  11123. var index = Engine.Instances.indexOf(this);
  11124. if (index >= 0) {
  11125. Engine.Instances.splice(index, 1);
  11126. }
  11127. this._workingCanvas = null;
  11128. this._workingContext = null;
  11129. this._currentBufferPointers = null;
  11130. this._renderingCanvas = null;
  11131. this._currentProgram = null;
  11132. this.onResizeObservable.clear();
  11133. this.onCanvasBlurObservable.clear();
  11134. this.onCanvasFocusObservable.clear();
  11135. this.onCanvasPointerOutObservable.clear();
  11136. BABYLON.Effect.ResetCache();
  11137. };
  11138. // Loading screen
  11139. Engine.prototype.displayLoadingUI = function () {
  11140. var loadingScreen = this.loadingScreen;
  11141. if (loadingScreen) {
  11142. loadingScreen.displayLoadingUI();
  11143. }
  11144. };
  11145. Engine.prototype.hideLoadingUI = function () {
  11146. var loadingScreen = this.loadingScreen;
  11147. if (loadingScreen) {
  11148. loadingScreen.hideLoadingUI();
  11149. }
  11150. };
  11151. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11152. get: function () {
  11153. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11154. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11155. return this._loadingScreen;
  11156. },
  11157. set: function (loadingScreen) {
  11158. this._loadingScreen = loadingScreen;
  11159. },
  11160. enumerable: true,
  11161. configurable: true
  11162. });
  11163. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11164. set: function (text) {
  11165. this.loadingScreen.loadingUIText = text;
  11166. },
  11167. enumerable: true,
  11168. configurable: true
  11169. });
  11170. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11171. set: function (color) {
  11172. this.loadingScreen.loadingUIBackgroundColor = color;
  11173. },
  11174. enumerable: true,
  11175. configurable: true
  11176. });
  11177. Engine.prototype.attachContextLostEvent = function (callback) {
  11178. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11179. };
  11180. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11181. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11182. };
  11183. Engine.prototype.getVertexShaderSource = function (program) {
  11184. var shaders = this._gl.getAttachedShaders(program);
  11185. return this._gl.getShaderSource(shaders[0]);
  11186. };
  11187. Engine.prototype.getFragmentShaderSource = function (program) {
  11188. var shaders = this._gl.getAttachedShaders(program);
  11189. return this._gl.getShaderSource(shaders[1]);
  11190. };
  11191. Engine.prototype.getError = function () {
  11192. return this._gl.getError();
  11193. };
  11194. // FPS
  11195. Engine.prototype.getFps = function () {
  11196. return this._fps;
  11197. };
  11198. Engine.prototype.getDeltaTime = function () {
  11199. return this._deltaTime;
  11200. };
  11201. Engine.prototype._measureFps = function () {
  11202. this._performanceMonitor.sampleFrame();
  11203. this._fps = this._performanceMonitor.averageFPS;
  11204. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11205. };
  11206. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11207. if (faceIndex === void 0) { faceIndex = -1; }
  11208. var gl = this._gl;
  11209. if (!this._dummyFramebuffer) {
  11210. this._dummyFramebuffer = gl.createFramebuffer();
  11211. }
  11212. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11213. if (faceIndex > -1) {
  11214. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11215. }
  11216. else {
  11217. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11218. }
  11219. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11220. var buffer;
  11221. switch (readType) {
  11222. case gl.UNSIGNED_BYTE:
  11223. buffer = new Uint8Array(4 * width * height);
  11224. readType = gl.UNSIGNED_BYTE;
  11225. break;
  11226. default:
  11227. buffer = new Float32Array(4 * width * height);
  11228. readType = gl.FLOAT;
  11229. break;
  11230. }
  11231. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11232. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11233. return buffer;
  11234. };
  11235. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11236. if (this._webGLVersion > 1) {
  11237. return this._caps.colorBufferFloat;
  11238. }
  11239. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11240. };
  11241. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11242. if (this._webGLVersion > 1) {
  11243. return this._caps.colorBufferFloat;
  11244. }
  11245. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11246. };
  11247. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11248. Engine.prototype._canRenderToFramebuffer = function (type) {
  11249. var gl = this._gl;
  11250. //clear existing errors
  11251. while (gl.getError() !== gl.NO_ERROR) { }
  11252. var successful = true;
  11253. var texture = gl.createTexture();
  11254. gl.bindTexture(gl.TEXTURE_2D, texture);
  11255. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11258. var fb = gl.createFramebuffer();
  11259. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11260. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11261. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11262. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11263. successful = successful && (gl.getError() === gl.NO_ERROR);
  11264. //try render by clearing frame buffer's color buffer
  11265. if (successful) {
  11266. gl.clear(gl.COLOR_BUFFER_BIT);
  11267. successful = successful && (gl.getError() === gl.NO_ERROR);
  11268. }
  11269. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11270. if (successful) {
  11271. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11272. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11273. var readFormat = gl.RGBA;
  11274. var readType = gl.UNSIGNED_BYTE;
  11275. var buffer = new Uint8Array(4);
  11276. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11277. successful = successful && (gl.getError() === gl.NO_ERROR);
  11278. }
  11279. //clean up
  11280. gl.deleteTexture(texture);
  11281. gl.deleteFramebuffer(fb);
  11282. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11283. //clear accumulated errors
  11284. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11285. return successful;
  11286. };
  11287. Engine.prototype._getWebGLTextureType = function (type) {
  11288. if (type === Engine.TEXTURETYPE_FLOAT) {
  11289. return this._gl.FLOAT;
  11290. }
  11291. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11292. // Add Half Float Constant.
  11293. return this._gl.HALF_FLOAT_OES;
  11294. }
  11295. return this._gl.UNSIGNED_BYTE;
  11296. };
  11297. ;
  11298. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11299. if (this._webGLVersion === 1) {
  11300. return this._gl.RGBA;
  11301. }
  11302. if (type === Engine.TEXTURETYPE_FLOAT) {
  11303. return this._gl.RGBA32F;
  11304. }
  11305. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11306. return this._gl.RGBA16F;
  11307. }
  11308. return this._gl.RGBA;
  11309. };
  11310. ;
  11311. Engine.prototype.createQuery = function () {
  11312. return this._gl.createQuery();
  11313. };
  11314. Engine.prototype.deleteQuery = function (query) {
  11315. this._gl.deleteQuery(query);
  11316. return this;
  11317. };
  11318. Engine.prototype.isQueryResultAvailable = function (query) {
  11319. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11320. };
  11321. Engine.prototype.getQueryResult = function (query) {
  11322. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11323. };
  11324. Engine.prototype.beginQuery = function (algorithmType, query) {
  11325. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11326. this._gl.beginQuery(glAlgorithm, query);
  11327. };
  11328. Engine.prototype.endQuery = function (algorithmType) {
  11329. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11330. this._gl.endQuery(glAlgorithm);
  11331. return this;
  11332. };
  11333. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11334. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11335. };
  11336. // Statics
  11337. Engine.isSupported = function () {
  11338. try {
  11339. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11340. if (navigator.isCocoonJS) {
  11341. return true;
  11342. }
  11343. var tempcanvas = document.createElement("canvas");
  11344. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11345. return gl != null && !!window.WebGLRenderingContext;
  11346. }
  11347. catch (e) {
  11348. return false;
  11349. }
  11350. };
  11351. Engine.Instances = new Array();
  11352. // Const statics
  11353. Engine._ALPHA_DISABLE = 0;
  11354. Engine._ALPHA_ADD = 1;
  11355. Engine._ALPHA_COMBINE = 2;
  11356. Engine._ALPHA_SUBTRACT = 3;
  11357. Engine._ALPHA_MULTIPLY = 4;
  11358. Engine._ALPHA_MAXIMIZED = 5;
  11359. Engine._ALPHA_ONEONE = 6;
  11360. Engine._ALPHA_PREMULTIPLIED = 7;
  11361. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11362. Engine._ALPHA_INTERPOLATE = 9;
  11363. Engine._ALPHA_SCREENMODE = 10;
  11364. Engine._DELAYLOADSTATE_NONE = 0;
  11365. Engine._DELAYLOADSTATE_LOADED = 1;
  11366. Engine._DELAYLOADSTATE_LOADING = 2;
  11367. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11368. Engine._TEXTUREFORMAT_ALPHA = 0;
  11369. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11370. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11371. Engine._TEXTUREFORMAT_RGB = 4;
  11372. Engine._TEXTUREFORMAT_RGBA = 5;
  11373. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11374. Engine._TEXTURETYPE_FLOAT = 1;
  11375. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11376. // Depht or Stencil test Constants.
  11377. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11378. 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.
  11379. 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.
  11380. 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.
  11381. 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.
  11382. 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.
  11383. 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.
  11384. 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.
  11385. // Stencil Actions Constants.
  11386. Engine._KEEP = 0x1E00;
  11387. Engine._REPLACE = 0x1E01;
  11388. Engine._INCR = 0x1E02;
  11389. Engine._DECR = 0x1E03;
  11390. Engine._INVERT = 0x150A;
  11391. Engine._INCR_WRAP = 0x8507;
  11392. Engine._DECR_WRAP = 0x8508;
  11393. // Texture rescaling mode
  11394. Engine._SCALEMODE_FLOOR = 1;
  11395. Engine._SCALEMODE_NEAREST = 2;
  11396. Engine._SCALEMODE_CEILING = 3;
  11397. // Updatable statics so stick with vars here
  11398. Engine.CollisionsEpsilon = 0.001;
  11399. Engine.CodeRepository = "src/";
  11400. Engine.ShadersRepository = "src/Shaders/";
  11401. return Engine;
  11402. }());
  11403. BABYLON.Engine = Engine;
  11404. })(BABYLON || (BABYLON = {}));
  11405. //# sourceMappingURL=babylon.engine.js.map
  11406. /// <reference path="Tools\babylon.decorators.ts" />
  11407. var BABYLON;
  11408. (function (BABYLON) {
  11409. /**
  11410. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11411. */
  11412. var Node = (function () {
  11413. /**
  11414. * @constructor
  11415. * @param {string} name - the name and id to be given to this node
  11416. * @param {BABYLON.Scene} the scene this node will be added to
  11417. */
  11418. function Node(name, scene) {
  11419. this.state = "";
  11420. this.metadata = null;
  11421. this.doNotSerialize = false;
  11422. this.animations = new Array();
  11423. this._ranges = {};
  11424. this._childrenFlag = -1;
  11425. this._isEnabled = true;
  11426. this._isReady = true;
  11427. this._currentRenderId = -1;
  11428. this._parentRenderId = -1;
  11429. /**
  11430. * An event triggered when the mesh is disposed.
  11431. * @type {BABYLON.Observable}
  11432. */
  11433. this.onDisposeObservable = new BABYLON.Observable();
  11434. // Behaviors
  11435. this._behaviors = new Array();
  11436. this.name = name;
  11437. this.id = name;
  11438. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11439. this._initCache();
  11440. }
  11441. Object.defineProperty(Node.prototype, "parent", {
  11442. get: function () {
  11443. return this._parentNode;
  11444. },
  11445. set: function (parent) {
  11446. if (this._parentNode === parent) {
  11447. return;
  11448. }
  11449. if (this._parentNode) {
  11450. var index = this._parentNode._children.indexOf(this);
  11451. if (index !== -1) {
  11452. this._parentNode._children.splice(index, 1);
  11453. }
  11454. }
  11455. this._parentNode = parent;
  11456. if (this._parentNode) {
  11457. if (!this._parentNode._children) {
  11458. this._parentNode._children = new Array();
  11459. }
  11460. this._parentNode._children.push(this);
  11461. }
  11462. },
  11463. enumerable: true,
  11464. configurable: true
  11465. });
  11466. Node.prototype.getClassName = function () {
  11467. return "Node";
  11468. };
  11469. Object.defineProperty(Node.prototype, "onDispose", {
  11470. set: function (callback) {
  11471. if (this._onDisposeObserver) {
  11472. this.onDisposeObservable.remove(this._onDisposeObserver);
  11473. }
  11474. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11475. },
  11476. enumerable: true,
  11477. configurable: true
  11478. });
  11479. Node.prototype.getScene = function () {
  11480. return this._scene;
  11481. };
  11482. Node.prototype.getEngine = function () {
  11483. return this._scene.getEngine();
  11484. };
  11485. Node.prototype.addBehavior = function (behavior) {
  11486. var index = this._behaviors.indexOf(behavior);
  11487. if (index !== -1) {
  11488. return;
  11489. }
  11490. behavior.attach(this);
  11491. this._behaviors.push(behavior);
  11492. return this;
  11493. };
  11494. Node.prototype.removeBehavior = function (behavior) {
  11495. var index = this._behaviors.indexOf(behavior);
  11496. if (index === -1) {
  11497. return;
  11498. }
  11499. this._behaviors[index].detach();
  11500. this._behaviors.splice(index, 1);
  11501. return this;
  11502. };
  11503. Object.defineProperty(Node.prototype, "behaviors", {
  11504. get: function () {
  11505. return this._behaviors;
  11506. },
  11507. enumerable: true,
  11508. configurable: true
  11509. });
  11510. Node.prototype.getBehaviorByName = function (name) {
  11511. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11512. var behavior = _a[_i];
  11513. if (behavior.name === name) {
  11514. return behavior;
  11515. }
  11516. }
  11517. return null;
  11518. };
  11519. // override it in derived class
  11520. Node.prototype.getWorldMatrix = function () {
  11521. return BABYLON.Matrix.Identity();
  11522. };
  11523. // override it in derived class if you add new variables to the cache
  11524. // and call the parent class method
  11525. Node.prototype._initCache = function () {
  11526. this._cache = {};
  11527. this._cache.parent = undefined;
  11528. };
  11529. Node.prototype.updateCache = function (force) {
  11530. if (!force && this.isSynchronized())
  11531. return;
  11532. this._cache.parent = this.parent;
  11533. this._updateCache();
  11534. };
  11535. // override it in derived class if you add new variables to the cache
  11536. // and call the parent class method if !ignoreParentClass
  11537. Node.prototype._updateCache = function (ignoreParentClass) {
  11538. };
  11539. // override it in derived class if you add new variables to the cache
  11540. Node.prototype._isSynchronized = function () {
  11541. return true;
  11542. };
  11543. Node.prototype._markSyncedWithParent = function () {
  11544. this._parentRenderId = this.parent._currentRenderId;
  11545. };
  11546. Node.prototype.isSynchronizedWithParent = function () {
  11547. if (!this.parent) {
  11548. return true;
  11549. }
  11550. if (this._parentRenderId !== this.parent._currentRenderId) {
  11551. return false;
  11552. }
  11553. return this.parent.isSynchronized();
  11554. };
  11555. Node.prototype.isSynchronized = function (updateCache) {
  11556. var check = this.hasNewParent();
  11557. check = check || !this.isSynchronizedWithParent();
  11558. check = check || !this._isSynchronized();
  11559. if (updateCache)
  11560. this.updateCache(true);
  11561. return !check;
  11562. };
  11563. Node.prototype.hasNewParent = function (update) {
  11564. if (this._cache.parent === this.parent)
  11565. return false;
  11566. if (update)
  11567. this._cache.parent = this.parent;
  11568. return true;
  11569. };
  11570. /**
  11571. * Is this node ready to be used/rendered
  11572. * @return {boolean} is it ready
  11573. */
  11574. Node.prototype.isReady = function () {
  11575. return this._isReady;
  11576. };
  11577. /**
  11578. * Is this node enabled.
  11579. * If the node has a parent and is enabled, the parent will be inspected as well.
  11580. * @return {boolean} whether this node (and its parent) is enabled.
  11581. * @see setEnabled
  11582. */
  11583. Node.prototype.isEnabled = function () {
  11584. if (!this._isEnabled) {
  11585. return false;
  11586. }
  11587. if (this.parent) {
  11588. return this.parent.isEnabled();
  11589. }
  11590. return true;
  11591. };
  11592. /**
  11593. * Set the enabled state of this node.
  11594. * @param {boolean} value - the new enabled state
  11595. * @see isEnabled
  11596. */
  11597. Node.prototype.setEnabled = function (value) {
  11598. this._isEnabled = value;
  11599. };
  11600. /**
  11601. * Is this node a descendant of the given node.
  11602. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11603. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11604. * @see parent
  11605. */
  11606. Node.prototype.isDescendantOf = function (ancestor) {
  11607. if (this.parent) {
  11608. if (this.parent === ancestor) {
  11609. return true;
  11610. }
  11611. return this.parent.isDescendantOf(ancestor);
  11612. }
  11613. return false;
  11614. };
  11615. /**
  11616. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11617. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11618. * @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.
  11619. * @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.
  11620. */
  11621. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11622. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11623. if (!this._children) {
  11624. return;
  11625. }
  11626. for (var index = 0; index < this._children.length; index++) {
  11627. var item = this._children[index];
  11628. if (!predicate || predicate(item)) {
  11629. results.push(item);
  11630. }
  11631. if (!directDescendantsOnly) {
  11632. item._getDescendants(results, false, predicate);
  11633. }
  11634. }
  11635. };
  11636. /**
  11637. * Will return all nodes that have this node as ascendant.
  11638. * @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.
  11639. * @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.
  11640. * @return {BABYLON.Node[]} all children nodes of all types.
  11641. */
  11642. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11643. var results = [];
  11644. this._getDescendants(results, directDescendantsOnly, predicate);
  11645. return results;
  11646. };
  11647. /**
  11648. * Get all child-meshes of this node.
  11649. */
  11650. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11651. var results = [];
  11652. this._getDescendants(results, directDecendantsOnly, function (node) {
  11653. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11654. });
  11655. return results;
  11656. };
  11657. /**
  11658. * Get all direct children of this node.
  11659. */
  11660. Node.prototype.getChildren = function (predicate) {
  11661. return this.getDescendants(true, predicate);
  11662. };
  11663. Node.prototype._setReady = function (state) {
  11664. if (state === this._isReady) {
  11665. return;
  11666. }
  11667. if (!state) {
  11668. this._isReady = false;
  11669. return;
  11670. }
  11671. this._isReady = true;
  11672. if (this.onReady) {
  11673. this.onReady(this);
  11674. }
  11675. };
  11676. Node.prototype.getAnimationByName = function (name) {
  11677. for (var i = 0; i < this.animations.length; i++) {
  11678. var animation = this.animations[i];
  11679. if (animation.name === name) {
  11680. return animation;
  11681. }
  11682. }
  11683. return null;
  11684. };
  11685. Node.prototype.createAnimationRange = function (name, from, to) {
  11686. // check name not already in use
  11687. if (!this._ranges[name]) {
  11688. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11689. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11690. if (this.animations[i]) {
  11691. this.animations[i].createRange(name, from, to);
  11692. }
  11693. }
  11694. }
  11695. };
  11696. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11697. if (deleteFrames === void 0) { deleteFrames = true; }
  11698. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11699. if (this.animations[i]) {
  11700. this.animations[i].deleteRange(name, deleteFrames);
  11701. }
  11702. }
  11703. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11704. };
  11705. Node.prototype.getAnimationRange = function (name) {
  11706. return this._ranges[name];
  11707. };
  11708. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11709. var range = this.getAnimationRange(name);
  11710. if (!range) {
  11711. return null;
  11712. }
  11713. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11714. };
  11715. Node.prototype.serializeAnimationRanges = function () {
  11716. var serializationRanges = [];
  11717. for (var name in this._ranges) {
  11718. var range = {};
  11719. range.name = name;
  11720. range.from = this._ranges[name].from;
  11721. range.to = this._ranges[name].to;
  11722. serializationRanges.push(range);
  11723. }
  11724. return serializationRanges;
  11725. };
  11726. Node.prototype.dispose = function () {
  11727. this.parent = null;
  11728. // Callback
  11729. this.onDisposeObservable.notifyObservers(this);
  11730. this.onDisposeObservable.clear();
  11731. // Behaviors
  11732. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11733. var behavior = _a[_i];
  11734. behavior.detach();
  11735. }
  11736. this._behaviors = [];
  11737. };
  11738. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11739. if (parsedNode.ranges) {
  11740. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11741. var data = parsedNode.ranges[index];
  11742. node.createAnimationRange(data.name, data.from, data.to);
  11743. }
  11744. }
  11745. };
  11746. __decorate([
  11747. BABYLON.serialize()
  11748. ], Node.prototype, "name", void 0);
  11749. __decorate([
  11750. BABYLON.serialize()
  11751. ], Node.prototype, "id", void 0);
  11752. __decorate([
  11753. BABYLON.serialize()
  11754. ], Node.prototype, "uniqueId", void 0);
  11755. __decorate([
  11756. BABYLON.serialize()
  11757. ], Node.prototype, "state", void 0);
  11758. __decorate([
  11759. BABYLON.serialize()
  11760. ], Node.prototype, "metadata", void 0);
  11761. return Node;
  11762. }());
  11763. BABYLON.Node = Node;
  11764. })(BABYLON || (BABYLON = {}));
  11765. //# sourceMappingURL=babylon.node.js.map
  11766. var BABYLON;
  11767. (function (BABYLON) {
  11768. var BoundingSphere = (function () {
  11769. function BoundingSphere(minimum, maximum) {
  11770. this.minimum = minimum;
  11771. this.maximum = maximum;
  11772. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11773. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11774. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11775. this.radius = distance * 0.5;
  11776. this.centerWorld = BABYLON.Vector3.Zero();
  11777. this._update(BABYLON.Matrix.Identity());
  11778. }
  11779. // Methods
  11780. BoundingSphere.prototype._update = function (world) {
  11781. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11782. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11783. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11784. };
  11785. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11786. for (var i = 0; i < 6; i++) {
  11787. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11788. return false;
  11789. }
  11790. return true;
  11791. };
  11792. BoundingSphere.prototype.intersectsPoint = function (point) {
  11793. var x = this.centerWorld.x - point.x;
  11794. var y = this.centerWorld.y - point.y;
  11795. var z = this.centerWorld.z - point.z;
  11796. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11797. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11798. return false;
  11799. return true;
  11800. };
  11801. // Statics
  11802. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11803. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11804. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11805. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11806. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11807. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11808. return false;
  11809. return true;
  11810. };
  11811. return BoundingSphere;
  11812. }());
  11813. BABYLON.BoundingSphere = BoundingSphere;
  11814. })(BABYLON || (BABYLON = {}));
  11815. //# sourceMappingURL=babylon.boundingSphere.js.map
  11816. var BABYLON;
  11817. (function (BABYLON) {
  11818. var BoundingBox = (function () {
  11819. function BoundingBox(minimum, maximum) {
  11820. this.minimum = minimum;
  11821. this.maximum = maximum;
  11822. this.vectors = new Array();
  11823. this.vectorsWorld = new Array();
  11824. // Bounding vectors
  11825. this.vectors.push(this.minimum.clone());
  11826. this.vectors.push(this.maximum.clone());
  11827. this.vectors.push(this.minimum.clone());
  11828. this.vectors[2].x = this.maximum.x;
  11829. this.vectors.push(this.minimum.clone());
  11830. this.vectors[3].y = this.maximum.y;
  11831. this.vectors.push(this.minimum.clone());
  11832. this.vectors[4].z = this.maximum.z;
  11833. this.vectors.push(this.maximum.clone());
  11834. this.vectors[5].z = this.minimum.z;
  11835. this.vectors.push(this.maximum.clone());
  11836. this.vectors[6].x = this.minimum.x;
  11837. this.vectors.push(this.maximum.clone());
  11838. this.vectors[7].y = this.minimum.y;
  11839. // OBB
  11840. this.center = this.maximum.add(this.minimum).scale(0.5);
  11841. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11842. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11843. // World
  11844. for (var index = 0; index < this.vectors.length; index++) {
  11845. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11846. }
  11847. this.minimumWorld = BABYLON.Vector3.Zero();
  11848. this.maximumWorld = BABYLON.Vector3.Zero();
  11849. this.centerWorld = BABYLON.Vector3.Zero();
  11850. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11851. this._update(BABYLON.Matrix.Identity());
  11852. }
  11853. // Methods
  11854. BoundingBox.prototype.getWorldMatrix = function () {
  11855. return this._worldMatrix;
  11856. };
  11857. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11858. this._worldMatrix.copyFrom(matrix);
  11859. return this;
  11860. };
  11861. BoundingBox.prototype._update = function (world) {
  11862. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11863. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11864. for (var index = 0; index < this.vectors.length; index++) {
  11865. var v = this.vectorsWorld[index];
  11866. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11867. if (v.x < this.minimumWorld.x)
  11868. this.minimumWorld.x = v.x;
  11869. if (v.y < this.minimumWorld.y)
  11870. this.minimumWorld.y = v.y;
  11871. if (v.z < this.minimumWorld.z)
  11872. this.minimumWorld.z = v.z;
  11873. if (v.x > this.maximumWorld.x)
  11874. this.maximumWorld.x = v.x;
  11875. if (v.y > this.maximumWorld.y)
  11876. this.maximumWorld.y = v.y;
  11877. if (v.z > this.maximumWorld.z)
  11878. this.maximumWorld.z = v.z;
  11879. }
  11880. // Extend
  11881. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11882. this.extendSizeWorld.scaleInPlace(0.5);
  11883. // OBB
  11884. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11885. this.centerWorld.scaleInPlace(0.5);
  11886. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11887. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11888. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11889. this._worldMatrix = world;
  11890. };
  11891. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11892. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11893. };
  11894. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11895. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11896. };
  11897. BoundingBox.prototype.intersectsPoint = function (point) {
  11898. var delta = -BABYLON.Epsilon;
  11899. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11900. return false;
  11901. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11902. return false;
  11903. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11904. return false;
  11905. return true;
  11906. };
  11907. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11908. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11909. };
  11910. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11911. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11912. return false;
  11913. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11914. return false;
  11915. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11916. return false;
  11917. return true;
  11918. };
  11919. // Statics
  11920. BoundingBox.Intersects = function (box0, box1) {
  11921. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11922. return false;
  11923. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11924. return false;
  11925. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11926. return false;
  11927. return true;
  11928. };
  11929. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11930. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11931. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11932. return (num <= (sphereRadius * sphereRadius));
  11933. };
  11934. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11935. for (var p = 0; p < 6; p++) {
  11936. for (var i = 0; i < 8; i++) {
  11937. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11938. return false;
  11939. }
  11940. }
  11941. }
  11942. return true;
  11943. };
  11944. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11945. for (var p = 0; p < 6; p++) {
  11946. var inCount = 8;
  11947. for (var i = 0; i < 8; i++) {
  11948. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11949. --inCount;
  11950. }
  11951. else {
  11952. break;
  11953. }
  11954. }
  11955. if (inCount === 0)
  11956. return false;
  11957. }
  11958. return true;
  11959. };
  11960. return BoundingBox;
  11961. }());
  11962. BABYLON.BoundingBox = BoundingBox;
  11963. })(BABYLON || (BABYLON = {}));
  11964. //# sourceMappingURL=babylon.boundingBox.js.map
  11965. var BABYLON;
  11966. (function (BABYLON) {
  11967. var computeBoxExtents = function (axis, box) {
  11968. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11969. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11970. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11971. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11972. var r = r0 + r1 + r2;
  11973. return {
  11974. min: p - r,
  11975. max: p + r
  11976. };
  11977. };
  11978. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11979. var axisOverlap = function (axis, box0, box1) {
  11980. var result0 = computeBoxExtents(axis, box0);
  11981. var result1 = computeBoxExtents(axis, box1);
  11982. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11983. };
  11984. var BoundingInfo = (function () {
  11985. function BoundingInfo(minimum, maximum) {
  11986. this.minimum = minimum;
  11987. this.maximum = maximum;
  11988. this._isLocked = false;
  11989. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11990. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11991. }
  11992. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11993. get: function () {
  11994. return this._isLocked;
  11995. },
  11996. set: function (value) {
  11997. this._isLocked = value;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. // Methods
  12003. BoundingInfo.prototype.update = function (world) {
  12004. if (this._isLocked) {
  12005. return;
  12006. }
  12007. this.boundingBox._update(world);
  12008. this.boundingSphere._update(world);
  12009. };
  12010. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12011. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12012. return false;
  12013. return this.boundingBox.isInFrustum(frustumPlanes);
  12014. };
  12015. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12016. /**
  12017. * Gets the world distance between the min and max points of the bounding box
  12018. */
  12019. get: function () {
  12020. var boundingBox = this.boundingBox;
  12021. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12022. return size.length();
  12023. },
  12024. enumerable: true,
  12025. configurable: true
  12026. });
  12027. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12028. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12029. };
  12030. BoundingInfo.prototype._checkCollision = function (collider) {
  12031. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12032. };
  12033. BoundingInfo.prototype.intersectsPoint = function (point) {
  12034. if (!this.boundingSphere.centerWorld) {
  12035. return false;
  12036. }
  12037. if (!this.boundingSphere.intersectsPoint(point)) {
  12038. return false;
  12039. }
  12040. if (!this.boundingBox.intersectsPoint(point)) {
  12041. return false;
  12042. }
  12043. return true;
  12044. };
  12045. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12046. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12047. return false;
  12048. }
  12049. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12050. return false;
  12051. }
  12052. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12053. return false;
  12054. }
  12055. if (!precise) {
  12056. return true;
  12057. }
  12058. var box0 = this.boundingBox;
  12059. var box1 = boundingInfo.boundingBox;
  12060. if (!axisOverlap(box0.directions[0], box0, box1))
  12061. return false;
  12062. if (!axisOverlap(box0.directions[1], box0, box1))
  12063. return false;
  12064. if (!axisOverlap(box0.directions[2], box0, box1))
  12065. return false;
  12066. if (!axisOverlap(box1.directions[0], box0, box1))
  12067. return false;
  12068. if (!axisOverlap(box1.directions[1], box0, box1))
  12069. return false;
  12070. if (!axisOverlap(box1.directions[2], box0, box1))
  12071. return false;
  12072. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12073. return false;
  12074. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12075. return false;
  12076. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12077. return false;
  12078. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12079. return false;
  12080. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12081. return false;
  12082. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12083. return false;
  12084. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12085. return false;
  12086. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12087. return false;
  12088. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12089. return false;
  12090. return true;
  12091. };
  12092. return BoundingInfo;
  12093. }());
  12094. BABYLON.BoundingInfo = BoundingInfo;
  12095. })(BABYLON || (BABYLON = {}));
  12096. //# sourceMappingURL=babylon.boundingInfo.js.map
  12097. var BABYLON;
  12098. (function (BABYLON) {
  12099. var AbstractMesh = (function (_super) {
  12100. __extends(AbstractMesh, _super);
  12101. // Constructor
  12102. function AbstractMesh(name, scene) {
  12103. var _this = _super.call(this, name, scene) || this;
  12104. _this._facetNb = 0; // facet number
  12105. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12106. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12107. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12108. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12109. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12110. _this._subDiv = {
  12111. max: 1,
  12112. X: 1,
  12113. Y: 1,
  12114. Z: 1
  12115. };
  12116. // Events
  12117. /**
  12118. * An event triggered when this mesh collides with another one
  12119. * @type {BABYLON.Observable}
  12120. */
  12121. _this.onCollideObservable = new BABYLON.Observable();
  12122. /**
  12123. * An event triggered when the collision's position changes
  12124. * @type {BABYLON.Observable}
  12125. */
  12126. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12127. /**
  12128. * An event triggered after the world matrix is updated
  12129. * @type {BABYLON.Observable}
  12130. */
  12131. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12132. /**
  12133. * An event triggered when material is changed
  12134. * @type {BABYLON.Observable}
  12135. */
  12136. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12137. // Properties
  12138. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12139. _this.position = BABYLON.Vector3.Zero();
  12140. /**
  12141. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12142. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12143. * or
  12144. * 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.
  12145. * for more info check WebGl documentations
  12146. */
  12147. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12148. /**
  12149. * 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:
  12150. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12151. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12152. * 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.
  12153. */
  12154. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12155. /**
  12156. * 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.
  12157. * The default value is -1 which means don't break the query and wait till the result.
  12158. */
  12159. _this.occlusionRetryCount = -1;
  12160. _this._occlusionInternalRetryCounter = 0;
  12161. _this._isOccluded = false;
  12162. _this._isOcclusionQueryInProgress = false;
  12163. _this._rotation = BABYLON.Vector3.Zero();
  12164. _this._scaling = BABYLON.Vector3.One();
  12165. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12166. _this.visibility = 1.0;
  12167. _this.alphaIndex = Number.MAX_VALUE;
  12168. _this.infiniteDistance = false;
  12169. _this.isVisible = true;
  12170. _this.isPickable = true;
  12171. _this.showBoundingBox = false;
  12172. _this.showSubMeshesBoundingBox = false;
  12173. _this.isBlocker = false;
  12174. _this.enablePointerMoveEvents = false;
  12175. _this.renderingGroupId = 0;
  12176. _this._receiveShadows = false;
  12177. _this.renderOutline = false;
  12178. _this.outlineColor = BABYLON.Color3.Red();
  12179. _this.outlineWidth = 0.02;
  12180. _this.renderOverlay = false;
  12181. _this.overlayColor = BABYLON.Color3.Red();
  12182. _this.overlayAlpha = 0.5;
  12183. _this._hasVertexAlpha = false;
  12184. _this._useVertexColors = true;
  12185. _this._computeBonesUsingShaders = true;
  12186. _this._numBoneInfluencers = 4;
  12187. _this._applyFog = true;
  12188. _this.scalingDeterminant = 1;
  12189. _this.useOctreeForRenderingSelection = true;
  12190. _this.useOctreeForPicking = true;
  12191. _this.useOctreeForCollisions = true;
  12192. _this._layerMask = 0x0FFFFFFF;
  12193. /**
  12194. * True if the mesh must be rendered in any case.
  12195. */
  12196. _this.alwaysSelectAsActiveMesh = false;
  12197. // Collisions
  12198. _this._checkCollisions = false;
  12199. _this._collisionMask = -1;
  12200. _this._collisionGroup = -1;
  12201. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12202. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12203. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12204. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12205. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12206. // Edges
  12207. _this.edgesWidth = 1;
  12208. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12209. // Cache
  12210. _this._localWorld = BABYLON.Matrix.Zero();
  12211. _this._worldMatrix = BABYLON.Matrix.Zero();
  12212. _this._absolutePosition = BABYLON.Vector3.Zero();
  12213. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12214. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12215. _this._isDirty = false;
  12216. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12217. _this._isDisposed = false;
  12218. _this._renderId = 0;
  12219. _this._intersectionsInProgress = new Array();
  12220. _this._isWorldMatrixFrozen = false;
  12221. _this._unIndexed = false;
  12222. _this._lightSources = new Array();
  12223. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12224. if (collidedMesh === void 0) { collidedMesh = null; }
  12225. //TODO move this to the collision coordinator!
  12226. if (_this.getScene().workerCollisions)
  12227. newPosition.multiplyInPlace(_this._collider.radius);
  12228. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12229. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12230. _this.position.addInPlace(_this._diffPositionForCollisions);
  12231. }
  12232. if (collidedMesh) {
  12233. _this.onCollideObservable.notifyObservers(collidedMesh);
  12234. }
  12235. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12236. };
  12237. _this.getScene().addMesh(_this);
  12238. _this._resyncLightSources();
  12239. return _this;
  12240. }
  12241. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12242. get: function () {
  12243. return AbstractMesh._BILLBOARDMODE_NONE;
  12244. },
  12245. enumerable: true,
  12246. configurable: true
  12247. });
  12248. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12249. get: function () {
  12250. return AbstractMesh._BILLBOARDMODE_X;
  12251. },
  12252. enumerable: true,
  12253. configurable: true
  12254. });
  12255. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12256. get: function () {
  12257. return AbstractMesh._BILLBOARDMODE_Y;
  12258. },
  12259. enumerable: true,
  12260. configurable: true
  12261. });
  12262. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12263. get: function () {
  12264. return AbstractMesh._BILLBOARDMODE_Z;
  12265. },
  12266. enumerable: true,
  12267. configurable: true
  12268. });
  12269. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12270. get: function () {
  12271. return AbstractMesh._BILLBOARDMODE_ALL;
  12272. },
  12273. enumerable: true,
  12274. configurable: true
  12275. });
  12276. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12277. /**
  12278. * Read-only : the number of facets in the mesh
  12279. */
  12280. get: function () {
  12281. return this._facetNb;
  12282. },
  12283. enumerable: true,
  12284. configurable: true
  12285. });
  12286. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12287. /**
  12288. * The number (integer) of subdivisions per axis in the partioning space
  12289. */
  12290. get: function () {
  12291. return this._partitioningSubdivisions;
  12292. },
  12293. set: function (nb) {
  12294. this._partitioningSubdivisions = nb;
  12295. },
  12296. enumerable: true,
  12297. configurable: true
  12298. });
  12299. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12300. /**
  12301. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12302. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12303. */
  12304. get: function () {
  12305. return this._partitioningBBoxRatio;
  12306. },
  12307. set: function (ratio) {
  12308. this._partitioningBBoxRatio = ratio;
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12314. /**
  12315. * Read-only boolean : is the feature facetData enabled ?
  12316. */
  12317. get: function () {
  12318. return this._facetDataEnabled;
  12319. },
  12320. enumerable: true,
  12321. configurable: true
  12322. });
  12323. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12324. set: function (callback) {
  12325. if (this._onCollideObserver) {
  12326. this.onCollideObservable.remove(this._onCollideObserver);
  12327. }
  12328. this._onCollideObserver = this.onCollideObservable.add(callback);
  12329. },
  12330. enumerable: true,
  12331. configurable: true
  12332. });
  12333. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12334. set: function (callback) {
  12335. if (this._onCollisionPositionChangeObserver) {
  12336. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12337. }
  12338. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12339. },
  12340. enumerable: true,
  12341. configurable: true
  12342. });
  12343. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12344. /**
  12345. * 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.
  12346. */
  12347. get: function () {
  12348. return this._isOccluded;
  12349. },
  12350. set: function (value) {
  12351. this._isOccluded = value;
  12352. },
  12353. enumerable: true,
  12354. configurable: true
  12355. });
  12356. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12357. /**
  12358. * Flag to check the progress status of the query
  12359. */
  12360. get: function () {
  12361. return this._isOcclusionQueryInProgress;
  12362. },
  12363. enumerable: true,
  12364. configurable: true
  12365. });
  12366. Object.defineProperty(AbstractMesh.prototype, "material", {
  12367. get: function () {
  12368. return this._material;
  12369. },
  12370. set: function (value) {
  12371. if (this._material === value) {
  12372. return;
  12373. }
  12374. this._material = value;
  12375. if (this.onMaterialChangedObservable.hasObservers) {
  12376. this.onMaterialChangedObservable.notifyObservers(this);
  12377. }
  12378. if (!this.subMeshes) {
  12379. return;
  12380. }
  12381. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12382. var subMesh = _a[_i];
  12383. subMesh.setEffect(null);
  12384. }
  12385. },
  12386. enumerable: true,
  12387. configurable: true
  12388. });
  12389. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12390. get: function () {
  12391. return this._receiveShadows;
  12392. },
  12393. set: function (value) {
  12394. if (this._receiveShadows === value) {
  12395. return;
  12396. }
  12397. this._receiveShadows = value;
  12398. this._markSubMeshesAsLightDirty();
  12399. },
  12400. enumerable: true,
  12401. configurable: true
  12402. });
  12403. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12404. get: function () {
  12405. return this._hasVertexAlpha;
  12406. },
  12407. set: function (value) {
  12408. if (this._hasVertexAlpha === value) {
  12409. return;
  12410. }
  12411. this._hasVertexAlpha = value;
  12412. this._markSubMeshesAsAttributesDirty();
  12413. },
  12414. enumerable: true,
  12415. configurable: true
  12416. });
  12417. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12418. get: function () {
  12419. return this._useVertexColors;
  12420. },
  12421. set: function (value) {
  12422. if (this._useVertexColors === value) {
  12423. return;
  12424. }
  12425. this._useVertexColors = value;
  12426. this._markSubMeshesAsAttributesDirty();
  12427. },
  12428. enumerable: true,
  12429. configurable: true
  12430. });
  12431. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12432. get: function () {
  12433. return this._computeBonesUsingShaders;
  12434. },
  12435. set: function (value) {
  12436. if (this._computeBonesUsingShaders === value) {
  12437. return;
  12438. }
  12439. this._computeBonesUsingShaders = value;
  12440. this._markSubMeshesAsAttributesDirty();
  12441. },
  12442. enumerable: true,
  12443. configurable: true
  12444. });
  12445. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12446. get: function () {
  12447. return this._numBoneInfluencers;
  12448. },
  12449. set: function (value) {
  12450. if (this._numBoneInfluencers === value) {
  12451. return;
  12452. }
  12453. this._numBoneInfluencers = value;
  12454. this._markSubMeshesAsAttributesDirty();
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12460. get: function () {
  12461. return this._applyFog;
  12462. },
  12463. set: function (value) {
  12464. if (this._applyFog === value) {
  12465. return;
  12466. }
  12467. this._applyFog = value;
  12468. this._markSubMeshesAsMiscDirty();
  12469. },
  12470. enumerable: true,
  12471. configurable: true
  12472. });
  12473. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12474. get: function () {
  12475. return this._layerMask;
  12476. },
  12477. set: function (value) {
  12478. if (value === this._layerMask) {
  12479. return;
  12480. }
  12481. this._layerMask = value;
  12482. this._resyncLightSources();
  12483. },
  12484. enumerable: true,
  12485. configurable: true
  12486. });
  12487. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12488. get: function () {
  12489. return this._collisionMask;
  12490. },
  12491. set: function (mask) {
  12492. this._collisionMask = !isNaN(mask) ? mask : -1;
  12493. },
  12494. enumerable: true,
  12495. configurable: true
  12496. });
  12497. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12498. get: function () {
  12499. return this._collisionGroup;
  12500. },
  12501. set: function (mask) {
  12502. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12503. },
  12504. enumerable: true,
  12505. configurable: true
  12506. });
  12507. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12508. get: function () {
  12509. return null;
  12510. },
  12511. enumerable: true,
  12512. configurable: true
  12513. });
  12514. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12515. get: function () {
  12516. return this._skeleton;
  12517. },
  12518. set: function (value) {
  12519. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12520. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12521. }
  12522. if (value && value.needInitialSkinMatrix) {
  12523. value._registerMeshWithPoseMatrix(this);
  12524. }
  12525. this._skeleton = value;
  12526. if (!this._skeleton) {
  12527. this._bonesTransformMatrices = null;
  12528. }
  12529. this._markSubMeshesAsAttributesDirty();
  12530. },
  12531. enumerable: true,
  12532. configurable: true
  12533. });
  12534. /**
  12535. * Boolean : true if the mesh has been disposed.
  12536. */
  12537. AbstractMesh.prototype.isDisposed = function () {
  12538. return this._isDisposed;
  12539. };
  12540. /**
  12541. * Returns the string "AbstractMesh"
  12542. */
  12543. AbstractMesh.prototype.getClassName = function () {
  12544. return "AbstractMesh";
  12545. };
  12546. /**
  12547. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12548. */
  12549. AbstractMesh.prototype.toString = function (fullDetails) {
  12550. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12551. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12552. if (this._skeleton) {
  12553. ret += ", skeleton: " + this._skeleton.name;
  12554. }
  12555. if (fullDetails) {
  12556. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12557. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12558. }
  12559. return ret;
  12560. };
  12561. AbstractMesh.prototype._rebuild = function () {
  12562. if (this._occlusionQuery) {
  12563. this._occlusionQuery = null;
  12564. }
  12565. if (this._edgesRenderer) {
  12566. this._edgesRenderer._rebuild();
  12567. }
  12568. if (!this.subMeshes) {
  12569. return;
  12570. }
  12571. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12572. var subMesh = _a[_i];
  12573. subMesh._rebuild();
  12574. }
  12575. };
  12576. AbstractMesh.prototype._resyncLightSources = function () {
  12577. this._lightSources.length = 0;
  12578. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12579. var light = _a[_i];
  12580. if (!light.isEnabled()) {
  12581. continue;
  12582. }
  12583. if (light.canAffectMesh(this)) {
  12584. this._lightSources.push(light);
  12585. }
  12586. }
  12587. this._markSubMeshesAsLightDirty();
  12588. };
  12589. AbstractMesh.prototype._resyncLighSource = function (light) {
  12590. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12591. var index = this._lightSources.indexOf(light);
  12592. if (index === -1) {
  12593. if (!isIn) {
  12594. return;
  12595. }
  12596. this._lightSources.push(light);
  12597. }
  12598. else {
  12599. if (isIn) {
  12600. return;
  12601. }
  12602. this._lightSources.splice(index, 1);
  12603. }
  12604. this._markSubMeshesAsLightDirty();
  12605. };
  12606. AbstractMesh.prototype._removeLightSource = function (light) {
  12607. var index = this._lightSources.indexOf(light);
  12608. if (index === -1) {
  12609. return;
  12610. }
  12611. this._lightSources.splice(index, 1);
  12612. };
  12613. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12614. if (!this.subMeshes) {
  12615. return;
  12616. }
  12617. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12618. var subMesh = _a[_i];
  12619. if (subMesh._materialDefines) {
  12620. func(subMesh._materialDefines);
  12621. }
  12622. }
  12623. };
  12624. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12625. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12626. };
  12627. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12628. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12629. };
  12630. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12631. if (!this.subMeshes) {
  12632. return;
  12633. }
  12634. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12635. var subMesh = _a[_i];
  12636. var material = subMesh.getMaterial();
  12637. if (material) {
  12638. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12639. }
  12640. }
  12641. };
  12642. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12643. /**
  12644. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12645. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12646. * Default : (0.0, 0.0, 0.0)
  12647. */
  12648. get: function () {
  12649. return this._rotation;
  12650. },
  12651. set: function (newRotation) {
  12652. this._rotation = newRotation;
  12653. },
  12654. enumerable: true,
  12655. configurable: true
  12656. });
  12657. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12658. /**
  12659. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12660. * Default : (1.0, 1.0, 1.0)
  12661. */
  12662. get: function () {
  12663. return this._scaling;
  12664. },
  12665. set: function (newScaling) {
  12666. this._scaling = newScaling;
  12667. if (this.physicsImpostor) {
  12668. this.physicsImpostor.forceUpdate();
  12669. }
  12670. },
  12671. enumerable: true,
  12672. configurable: true
  12673. });
  12674. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12675. /**
  12676. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12677. * It's null by default.
  12678. * 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)
  12679. */
  12680. get: function () {
  12681. return this._rotationQuaternion;
  12682. },
  12683. set: function (quaternion) {
  12684. this._rotationQuaternion = quaternion;
  12685. //reset the rotation vector.
  12686. if (quaternion && this.rotation.length()) {
  12687. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12688. }
  12689. },
  12690. enumerable: true,
  12691. configurable: true
  12692. });
  12693. // Methods
  12694. /**
  12695. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12696. * Returns the AbstractMesh.
  12697. */
  12698. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12699. this._poseMatrix.copyFrom(matrix);
  12700. return this;
  12701. };
  12702. /**
  12703. * Returns the mesh Pose matrix.
  12704. * Returned object : Matrix
  12705. */
  12706. AbstractMesh.prototype.getPoseMatrix = function () {
  12707. return this._poseMatrix;
  12708. };
  12709. /**
  12710. * Disables the mesh edger rendering mode.
  12711. * Returns the AbstractMesh.
  12712. */
  12713. AbstractMesh.prototype.disableEdgesRendering = function () {
  12714. if (this._edgesRenderer !== undefined) {
  12715. this._edgesRenderer.dispose();
  12716. this._edgesRenderer = undefined;
  12717. }
  12718. return this;
  12719. };
  12720. /**
  12721. * Enables the edge rendering mode on the mesh.
  12722. * This mode makes the mesh edges visible.
  12723. * Returns the AbstractMesh.
  12724. */
  12725. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12726. if (epsilon === void 0) { epsilon = 0.95; }
  12727. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12728. this.disableEdgesRendering();
  12729. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12730. return this;
  12731. };
  12732. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12733. /**
  12734. * Returns true if the mesh is blocked. Used by the class Mesh.
  12735. * Returns the boolean `false` by default.
  12736. */
  12737. get: function () {
  12738. return false;
  12739. },
  12740. enumerable: true,
  12741. configurable: true
  12742. });
  12743. /**
  12744. * Returns the mesh itself by default, used by the class Mesh.
  12745. * Returned type : AbstractMesh
  12746. */
  12747. AbstractMesh.prototype.getLOD = function (camera) {
  12748. return this;
  12749. };
  12750. /**
  12751. * Returns 0 by default, used by the class Mesh.
  12752. * Returns an integer.
  12753. */
  12754. AbstractMesh.prototype.getTotalVertices = function () {
  12755. return 0;
  12756. };
  12757. /**
  12758. * Returns null by default, used by the class Mesh.
  12759. * Returned type : integer array
  12760. */
  12761. AbstractMesh.prototype.getIndices = function () {
  12762. return null;
  12763. };
  12764. /**
  12765. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12766. * Returned type : float array or Float32Array
  12767. */
  12768. AbstractMesh.prototype.getVerticesData = function (kind) {
  12769. return null;
  12770. };
  12771. /**
  12772. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12773. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12774. * The `data` are either a numeric array either a Float32Array.
  12775. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12776. * 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).
  12777. * Note that a new underlying VertexBuffer object is created each call.
  12778. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12779. *
  12780. * Possible `kind` values :
  12781. * - BABYLON.VertexBuffer.PositionKind
  12782. * - BABYLON.VertexBuffer.UVKind
  12783. * - BABYLON.VertexBuffer.UV2Kind
  12784. * - BABYLON.VertexBuffer.UV3Kind
  12785. * - BABYLON.VertexBuffer.UV4Kind
  12786. * - BABYLON.VertexBuffer.UV5Kind
  12787. * - BABYLON.VertexBuffer.UV6Kind
  12788. * - BABYLON.VertexBuffer.ColorKind
  12789. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12790. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12791. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12792. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12793. *
  12794. * Returns the Mesh.
  12795. */
  12796. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12797. return null;
  12798. };
  12799. /**
  12800. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12801. * If the mesh has no geometry, it is simply returned as it is.
  12802. * The `data` are either a numeric array either a Float32Array.
  12803. * No new underlying VertexBuffer object is created.
  12804. * 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.
  12805. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12806. *
  12807. * Possible `kind` values :
  12808. * - BABYLON.VertexBuffer.PositionKind
  12809. * - BABYLON.VertexBuffer.UVKind
  12810. * - BABYLON.VertexBuffer.UV2Kind
  12811. * - BABYLON.VertexBuffer.UV3Kind
  12812. * - BABYLON.VertexBuffer.UV4Kind
  12813. * - BABYLON.VertexBuffer.UV5Kind
  12814. * - BABYLON.VertexBuffer.UV6Kind
  12815. * - BABYLON.VertexBuffer.ColorKind
  12816. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12817. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12818. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12819. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12820. *
  12821. * Returns the Mesh.
  12822. */
  12823. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12824. return null;
  12825. };
  12826. /**
  12827. * Sets the mesh indices.
  12828. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12829. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12830. * This method creates a new index buffer each call.
  12831. * Returns the Mesh.
  12832. */
  12833. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12834. return null;
  12835. };
  12836. /** Returns false by default, used by the class Mesh.
  12837. * Returns a boolean
  12838. */
  12839. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12840. return false;
  12841. };
  12842. /**
  12843. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12844. * Returns a BoundingInfo
  12845. */
  12846. AbstractMesh.prototype.getBoundingInfo = function () {
  12847. if (this._masterMesh) {
  12848. return this._masterMesh.getBoundingInfo();
  12849. }
  12850. if (!this._boundingInfo) {
  12851. this._updateBoundingInfo();
  12852. }
  12853. return this._boundingInfo;
  12854. };
  12855. /**
  12856. * Sets a mesh new object BoundingInfo.
  12857. * Returns the AbstractMesh.
  12858. */
  12859. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12860. this._boundingInfo = boundingInfo;
  12861. return this;
  12862. };
  12863. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12864. get: function () {
  12865. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12866. },
  12867. enumerable: true,
  12868. configurable: true
  12869. });
  12870. AbstractMesh.prototype._preActivate = function () {
  12871. };
  12872. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12873. };
  12874. AbstractMesh.prototype._activate = function (renderId) {
  12875. this._renderId = renderId;
  12876. };
  12877. /**
  12878. * Returns the last update of the World matrix
  12879. * Returns a Matrix.
  12880. */
  12881. AbstractMesh.prototype.getWorldMatrix = function () {
  12882. if (this._masterMesh) {
  12883. return this._masterMesh.getWorldMatrix();
  12884. }
  12885. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12886. this.computeWorldMatrix();
  12887. }
  12888. return this._worldMatrix;
  12889. };
  12890. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12891. /**
  12892. * Returns directly the last state of the mesh World matrix.
  12893. * A Matrix is returned.
  12894. */
  12895. get: function () {
  12896. return this._worldMatrix;
  12897. },
  12898. enumerable: true,
  12899. configurable: true
  12900. });
  12901. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12902. /**
  12903. * Returns the current mesh absolute position.
  12904. * Retuns a Vector3.
  12905. */
  12906. get: function () {
  12907. return this._absolutePosition;
  12908. },
  12909. enumerable: true,
  12910. configurable: true
  12911. });
  12912. /**
  12913. * Prevents the World matrix to be computed any longer.
  12914. * Returns the AbstractMesh.
  12915. */
  12916. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12917. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12918. this.computeWorldMatrix(true);
  12919. this._isWorldMatrixFrozen = true;
  12920. return this;
  12921. };
  12922. /**
  12923. * Allows back the World matrix computation.
  12924. * Returns the AbstractMesh.
  12925. */
  12926. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12927. this._isWorldMatrixFrozen = false;
  12928. this.computeWorldMatrix(true);
  12929. return this;
  12930. };
  12931. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12932. /**
  12933. * True if the World matrix has been frozen.
  12934. * Returns a boolean.
  12935. */
  12936. get: function () {
  12937. return this._isWorldMatrixFrozen;
  12938. },
  12939. enumerable: true,
  12940. configurable: true
  12941. });
  12942. /**
  12943. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12944. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12945. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12946. * The passed axis is also normalized.
  12947. * Returns the AbstractMesh.
  12948. */
  12949. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12950. axis.normalize();
  12951. if (!this.rotationQuaternion) {
  12952. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12953. this.rotation = BABYLON.Vector3.Zero();
  12954. }
  12955. var rotationQuaternion;
  12956. if (!space || space === BABYLON.Space.LOCAL) {
  12957. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12958. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12959. }
  12960. else {
  12961. if (this.parent) {
  12962. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12963. invertParentWorldMatrix.invert();
  12964. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12965. }
  12966. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12967. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12968. }
  12969. return this;
  12970. };
  12971. /**
  12972. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12973. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12974. * The passed axis is also normalized.
  12975. * Returns the AbstractMesh.
  12976. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12977. */
  12978. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  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.copyFromFloats(0, 0, 0);
  12983. }
  12984. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12985. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12986. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12987. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12988. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12989. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12990. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12991. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12992. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12993. return this;
  12994. };
  12995. /**
  12996. * Translates the mesh along the axis vector for the passed distance in the given space.
  12997. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12998. * Returns the AbstractMesh.
  12999. */
  13000. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13001. var displacementVector = axis.scale(distance);
  13002. if (!space || space === BABYLON.Space.LOCAL) {
  13003. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13004. this.setPositionWithLocalVector(tempV3);
  13005. }
  13006. else {
  13007. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13008. }
  13009. return this;
  13010. };
  13011. /**
  13012. * Adds a rotation step to the mesh current rotation.
  13013. * x, y, z are Euler angles expressed in radians.
  13014. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13015. * This means this rotation is made in the mesh local space only.
  13016. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13017. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13018. * ```javascript
  13019. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13020. * ```
  13021. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13022. * 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.
  13023. * Returns the AbstractMesh.
  13024. */
  13025. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13026. var rotationQuaternion;
  13027. if (this.rotationQuaternion) {
  13028. rotationQuaternion = this.rotationQuaternion;
  13029. }
  13030. else {
  13031. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13032. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13033. }
  13034. var accumulation = BABYLON.Tmp.Quaternion[0];
  13035. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13036. rotationQuaternion.multiplyInPlace(accumulation);
  13037. if (!this.rotationQuaternion) {
  13038. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13039. }
  13040. return this;
  13041. };
  13042. /**
  13043. * Retuns the mesh absolute position in the World.
  13044. * Returns a Vector3.
  13045. */
  13046. AbstractMesh.prototype.getAbsolutePosition = function () {
  13047. this.computeWorldMatrix();
  13048. return this._absolutePosition;
  13049. };
  13050. /**
  13051. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13052. * Returns the AbstractMesh.
  13053. */
  13054. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13055. if (!absolutePosition) {
  13056. return;
  13057. }
  13058. var absolutePositionX;
  13059. var absolutePositionY;
  13060. var absolutePositionZ;
  13061. if (absolutePosition.x === undefined) {
  13062. if (arguments.length < 3) {
  13063. return;
  13064. }
  13065. absolutePositionX = arguments[0];
  13066. absolutePositionY = arguments[1];
  13067. absolutePositionZ = arguments[2];
  13068. }
  13069. else {
  13070. absolutePositionX = absolutePosition.x;
  13071. absolutePositionY = absolutePosition.y;
  13072. absolutePositionZ = absolutePosition.z;
  13073. }
  13074. if (this.parent) {
  13075. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13076. invertParentWorldMatrix.invert();
  13077. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13078. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13079. }
  13080. else {
  13081. this.position.x = absolutePositionX;
  13082. this.position.y = absolutePositionY;
  13083. this.position.z = absolutePositionZ;
  13084. }
  13085. return this;
  13086. };
  13087. // ================================== Point of View Movement =================================
  13088. /**
  13089. * Perform relative position change from the point of view of behind the front of the mesh.
  13090. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13091. * Supports definition of mesh facing forward or backward.
  13092. * @param {number} amountRight
  13093. * @param {number} amountUp
  13094. * @param {number} amountForward
  13095. *
  13096. * Returns the AbstractMesh.
  13097. */
  13098. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13099. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13100. return this;
  13101. };
  13102. /**
  13103. * Calculate relative position change from the point of view of behind the front of the mesh.
  13104. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13105. * Supports definition of mesh facing forward or backward.
  13106. * @param {number} amountRight
  13107. * @param {number} amountUp
  13108. * @param {number} amountForward
  13109. *
  13110. * Returns a new Vector3.
  13111. */
  13112. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13113. var rotMatrix = new BABYLON.Matrix();
  13114. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13115. rotQuaternion.toRotationMatrix(rotMatrix);
  13116. var translationDelta = BABYLON.Vector3.Zero();
  13117. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13118. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13119. return translationDelta;
  13120. };
  13121. // ================================== Point of View Rotation =================================
  13122. /**
  13123. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13124. * Supports definition of mesh facing forward or backward.
  13125. * @param {number} flipBack
  13126. * @param {number} twirlClockwise
  13127. * @param {number} tiltRight
  13128. *
  13129. * Returns the AbstractMesh.
  13130. */
  13131. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13132. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13133. return this;
  13134. };
  13135. /**
  13136. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13137. * Supports definition of mesh facing forward or backward.
  13138. * @param {number} flipBack
  13139. * @param {number} twirlClockwise
  13140. * @param {number} tiltRight
  13141. *
  13142. * Returns a new Vector3.
  13143. */
  13144. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13145. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13146. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13147. };
  13148. /**
  13149. * Sets a new pivot matrix to the mesh.
  13150. * Returns the AbstractMesh.
  13151. */
  13152. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13153. this._pivotMatrix = matrix;
  13154. this._cache.pivotMatrixUpdated = true;
  13155. return this;
  13156. };
  13157. /**
  13158. * Returns the mesh pivot matrix.
  13159. * Default : Identity.
  13160. * A Matrix is returned.
  13161. */
  13162. AbstractMesh.prototype.getPivotMatrix = function () {
  13163. return this._pivotMatrix;
  13164. };
  13165. AbstractMesh.prototype._isSynchronized = function () {
  13166. if (this._isDirty) {
  13167. return false;
  13168. }
  13169. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13170. return false;
  13171. if (this._cache.pivotMatrixUpdated) {
  13172. return false;
  13173. }
  13174. if (this.infiniteDistance) {
  13175. return false;
  13176. }
  13177. if (!this._cache.position.equals(this.position))
  13178. return false;
  13179. if (this.rotationQuaternion) {
  13180. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13181. return false;
  13182. }
  13183. if (!this._cache.rotation.equals(this.rotation))
  13184. return false;
  13185. if (!this._cache.scaling.equals(this.scaling))
  13186. return false;
  13187. return true;
  13188. };
  13189. AbstractMesh.prototype._initCache = function () {
  13190. _super.prototype._initCache.call(this);
  13191. this._cache.localMatrixUpdated = false;
  13192. this._cache.position = BABYLON.Vector3.Zero();
  13193. this._cache.scaling = BABYLON.Vector3.Zero();
  13194. this._cache.rotation = BABYLON.Vector3.Zero();
  13195. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13196. this._cache.billboardMode = -1;
  13197. };
  13198. AbstractMesh.prototype.markAsDirty = function (property) {
  13199. if (property === "rotation") {
  13200. this.rotationQuaternion = null;
  13201. }
  13202. this._currentRenderId = Number.MAX_VALUE;
  13203. this._isDirty = true;
  13204. return this;
  13205. };
  13206. /**
  13207. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13208. * Returns the AbstractMesh.
  13209. */
  13210. AbstractMesh.prototype._updateBoundingInfo = function () {
  13211. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13212. this._boundingInfo.update(this.worldMatrixFromCache);
  13213. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13214. return this;
  13215. };
  13216. /**
  13217. * Update a mesh's children BoundingInfo objects only.
  13218. * Returns the AbstractMesh.
  13219. */
  13220. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13221. if (!this.subMeshes) {
  13222. return;
  13223. }
  13224. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13225. var subMesh = this.subMeshes[subIndex];
  13226. if (!subMesh.IsGlobal) {
  13227. subMesh.updateBoundingInfo(matrix);
  13228. }
  13229. }
  13230. return this;
  13231. };
  13232. /**
  13233. * Computes the mesh World matrix and returns it.
  13234. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13235. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13236. * If the parameter `force`is set to `true`, the actual computation is done.
  13237. * Returns the mesh World Matrix.
  13238. */
  13239. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13240. if (this._isWorldMatrixFrozen) {
  13241. return this._worldMatrix;
  13242. }
  13243. if (!force && this.isSynchronized(true)) {
  13244. this._currentRenderId = this.getScene().getRenderId();
  13245. return this._worldMatrix;
  13246. }
  13247. this._cache.position.copyFrom(this.position);
  13248. this._cache.scaling.copyFrom(this.scaling);
  13249. this._cache.pivotMatrixUpdated = false;
  13250. this._cache.billboardMode = this.billboardMode;
  13251. this._currentRenderId = this.getScene().getRenderId();
  13252. this._isDirty = false;
  13253. // Scaling
  13254. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13255. // Rotation
  13256. //rotate, if quaternion is set and rotation was used
  13257. if (this.rotationQuaternion) {
  13258. var len = this.rotation.length();
  13259. if (len) {
  13260. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13261. this.rotation.copyFromFloats(0, 0, 0);
  13262. }
  13263. }
  13264. if (this.rotationQuaternion) {
  13265. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13266. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13267. }
  13268. else {
  13269. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13270. this._cache.rotation.copyFrom(this.rotation);
  13271. }
  13272. // Translation
  13273. if (this.infiniteDistance && !this.parent) {
  13274. var camera = this.getScene().activeCamera;
  13275. if (camera) {
  13276. var cameraWorldMatrix = camera.getWorldMatrix();
  13277. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13278. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13279. }
  13280. }
  13281. else {
  13282. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13283. }
  13284. // Composing transformations
  13285. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13286. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13287. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13288. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13289. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13290. // Need to decompose each rotation here
  13291. var currentPosition = BABYLON.Tmp.Vector3[3];
  13292. if (this.parent && this.parent.getWorldMatrix) {
  13293. if (this._meshToBoneReferal) {
  13294. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13295. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13296. }
  13297. else {
  13298. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13299. }
  13300. }
  13301. else {
  13302. currentPosition.copyFrom(this.position);
  13303. }
  13304. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13305. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13306. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13307. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13308. }
  13309. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13310. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13311. }
  13312. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13313. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13314. }
  13315. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13316. }
  13317. else {
  13318. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13319. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13320. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13321. }
  13322. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13323. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13324. }
  13325. // Local world
  13326. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13327. // Parent
  13328. if (this.parent && this.parent.getWorldMatrix) {
  13329. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13330. if (this._meshToBoneReferal) {
  13331. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13332. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13333. }
  13334. else {
  13335. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13336. }
  13337. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13338. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13339. this._worldMatrix.copyFrom(this._localWorld);
  13340. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13341. }
  13342. else {
  13343. if (this._meshToBoneReferal) {
  13344. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13345. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13346. }
  13347. else {
  13348. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13349. }
  13350. }
  13351. this._markSyncedWithParent();
  13352. }
  13353. else {
  13354. this._worldMatrix.copyFrom(this._localWorld);
  13355. }
  13356. // Bounding info
  13357. this._updateBoundingInfo();
  13358. // Absolute position
  13359. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13360. // Callbacks
  13361. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13362. if (!this._poseMatrix) {
  13363. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13364. }
  13365. return this._worldMatrix;
  13366. };
  13367. /**
  13368. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13369. * @param func: callback function to add
  13370. *
  13371. * Returns the AbstractMesh.
  13372. */
  13373. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13374. this.onAfterWorldMatrixUpdateObservable.add(func);
  13375. return this;
  13376. };
  13377. /**
  13378. * Removes a registered callback function.
  13379. * Returns the AbstractMesh.
  13380. */
  13381. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13382. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13383. return this;
  13384. };
  13385. /**
  13386. * Sets the mesh position in its local space.
  13387. * Returns the AbstractMesh.
  13388. */
  13389. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13390. this.computeWorldMatrix();
  13391. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13392. return this;
  13393. };
  13394. /**
  13395. * Returns the mesh position in the local space from the current World matrix values.
  13396. * Returns a new Vector3.
  13397. */
  13398. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13399. this.computeWorldMatrix();
  13400. var invLocalWorldMatrix = this._localWorld.clone();
  13401. invLocalWorldMatrix.invert();
  13402. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13403. };
  13404. /**
  13405. * Translates the mesh along the passed Vector3 in its local space.
  13406. * Returns the AbstractMesh.
  13407. */
  13408. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13409. this.computeWorldMatrix(true);
  13410. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13411. return this;
  13412. };
  13413. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13414. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13415. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13416. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13417. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13418. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13419. /// <returns>Mesh oriented towards targetMesh</returns>
  13420. if (yawCor === void 0) { yawCor = 0; }
  13421. if (pitchCor === void 0) { pitchCor = 0; }
  13422. if (rollCor === void 0) { rollCor = 0; }
  13423. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13424. var dv = AbstractMesh._lookAtVectorCache;
  13425. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13426. targetPoint.subtractToRef(pos, dv);
  13427. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13428. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13429. var pitch = Math.atan2(dv.y, len);
  13430. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13431. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13432. return this;
  13433. };
  13434. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13435. this._meshToBoneReferal = affectedMesh;
  13436. this.parent = bone;
  13437. if (bone.getWorldMatrix().determinant() < 0) {
  13438. this.scalingDeterminant *= -1;
  13439. }
  13440. return this;
  13441. };
  13442. AbstractMesh.prototype.detachFromBone = function () {
  13443. if (this.parent.getWorldMatrix().determinant() < 0) {
  13444. this.scalingDeterminant *= -1;
  13445. }
  13446. this._meshToBoneReferal = null;
  13447. this.parent = null;
  13448. return this;
  13449. };
  13450. /**
  13451. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13452. * A mesh is in the frustum if its bounding box intersects the frustum.
  13453. * Boolean returned.
  13454. */
  13455. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13456. return this._boundingInfo.isInFrustum(frustumPlanes);
  13457. };
  13458. /**
  13459. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13460. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13461. * Boolean returned.
  13462. */
  13463. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13464. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13465. ;
  13466. };
  13467. /**
  13468. * True if the mesh intersects another mesh or a SolidParticle object.
  13469. * 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)
  13470. * Returns a boolean.
  13471. */
  13472. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13473. if (!this._boundingInfo || !mesh._boundingInfo) {
  13474. return false;
  13475. }
  13476. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13477. };
  13478. /**
  13479. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13480. * Returns a boolean.
  13481. */
  13482. AbstractMesh.prototype.intersectsPoint = function (point) {
  13483. if (!this._boundingInfo) {
  13484. return false;
  13485. }
  13486. return this._boundingInfo.intersectsPoint(point);
  13487. };
  13488. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13489. return this.physicsImpostor;
  13490. };
  13491. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13492. if (!camera) {
  13493. camera = this.getScene().activeCamera;
  13494. }
  13495. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13496. };
  13497. /**
  13498. * Returns the distance from the mesh to the active camera.
  13499. * Returns a float.
  13500. */
  13501. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13502. if (!camera) {
  13503. camera = this.getScene().activeCamera;
  13504. }
  13505. return this.absolutePosition.subtract(camera.position).length();
  13506. };
  13507. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13508. if (!this.physicsImpostor) {
  13509. return;
  13510. }
  13511. this.physicsImpostor.applyImpulse(force, contactPoint);
  13512. return this;
  13513. };
  13514. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13515. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13516. return;
  13517. }
  13518. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13519. mainPivot: pivot1,
  13520. connectedPivot: pivot2,
  13521. nativeParams: options
  13522. });
  13523. return this;
  13524. };
  13525. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13526. // Collisions
  13527. /**
  13528. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13529. * Default `false`.
  13530. */
  13531. get: function () {
  13532. return this._checkCollisions;
  13533. },
  13534. set: function (collisionEnabled) {
  13535. this._checkCollisions = collisionEnabled;
  13536. if (this.getScene().workerCollisions) {
  13537. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13538. }
  13539. },
  13540. enumerable: true,
  13541. configurable: true
  13542. });
  13543. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13544. var globalPosition = this.getAbsolutePosition();
  13545. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13546. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13547. if (!this._collider) {
  13548. this._collider = new BABYLON.Collider();
  13549. }
  13550. this._collider.radius = this.ellipsoid;
  13551. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13552. return this;
  13553. };
  13554. // Submeshes octree
  13555. /**
  13556. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13557. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13558. * Returns an Octree of submeshes.
  13559. */
  13560. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13561. if (maxCapacity === void 0) { maxCapacity = 64; }
  13562. if (maxDepth === void 0) { maxDepth = 2; }
  13563. if (!this._submeshesOctree) {
  13564. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13565. }
  13566. this.computeWorldMatrix(true);
  13567. // Update octree
  13568. var bbox = this.getBoundingInfo().boundingBox;
  13569. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13570. return this._submeshesOctree;
  13571. };
  13572. // Collisions
  13573. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13574. this._generatePointsArray();
  13575. // Transformation
  13576. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13577. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13578. subMesh._lastColliderWorldVertices = [];
  13579. subMesh._trianglePlanes = [];
  13580. var start = subMesh.verticesStart;
  13581. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13582. for (var i = start; i < end; i++) {
  13583. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13584. }
  13585. }
  13586. // Collide
  13587. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13588. if (collider.collisionFound) {
  13589. collider.collidedMesh = this;
  13590. }
  13591. return this;
  13592. };
  13593. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13594. var subMeshes;
  13595. var len;
  13596. // Octrees
  13597. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13598. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13599. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13600. len = intersections.length;
  13601. subMeshes = intersections.data;
  13602. }
  13603. else {
  13604. subMeshes = this.subMeshes;
  13605. len = subMeshes.length;
  13606. }
  13607. for (var index = 0; index < len; index++) {
  13608. var subMesh = subMeshes[index];
  13609. // Bounding test
  13610. if (len > 1 && !subMesh._checkCollision(collider))
  13611. continue;
  13612. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13613. }
  13614. return this;
  13615. };
  13616. AbstractMesh.prototype._checkCollision = function (collider) {
  13617. // Bounding box test
  13618. if (!this._boundingInfo._checkCollision(collider))
  13619. return this;
  13620. // Transformation matrix
  13621. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13622. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13623. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13624. return this;
  13625. };
  13626. // Picking
  13627. AbstractMesh.prototype._generatePointsArray = function () {
  13628. return false;
  13629. };
  13630. /**
  13631. * Checks if the passed Ray intersects with the mesh.
  13632. * Returns an object PickingInfo.
  13633. */
  13634. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13635. var pickingInfo = new BABYLON.PickingInfo();
  13636. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13637. return pickingInfo;
  13638. }
  13639. if (!this._generatePointsArray()) {
  13640. return pickingInfo;
  13641. }
  13642. var intersectInfo = null;
  13643. // Octrees
  13644. var subMeshes;
  13645. var len;
  13646. if (this._submeshesOctree && this.useOctreeForPicking) {
  13647. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13648. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13649. len = intersections.length;
  13650. subMeshes = intersections.data;
  13651. }
  13652. else {
  13653. subMeshes = this.subMeshes;
  13654. len = subMeshes.length;
  13655. }
  13656. for (var index = 0; index < len; index++) {
  13657. var subMesh = subMeshes[index];
  13658. // Bounding test
  13659. if (len > 1 && !subMesh.canIntersects(ray))
  13660. continue;
  13661. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13662. if (currentIntersectInfo) {
  13663. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13664. intersectInfo = currentIntersectInfo;
  13665. intersectInfo.subMeshId = index;
  13666. if (fastCheck) {
  13667. break;
  13668. }
  13669. }
  13670. }
  13671. }
  13672. if (intersectInfo) {
  13673. // Get picked point
  13674. var world = this.getWorldMatrix();
  13675. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13676. var direction = ray.direction.clone();
  13677. direction = direction.scale(intersectInfo.distance);
  13678. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13679. var pickedPoint = worldOrigin.add(worldDirection);
  13680. // Return result
  13681. pickingInfo.hit = true;
  13682. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13683. pickingInfo.pickedPoint = pickedPoint;
  13684. pickingInfo.pickedMesh = this;
  13685. pickingInfo.bu = intersectInfo.bu;
  13686. pickingInfo.bv = intersectInfo.bv;
  13687. pickingInfo.faceId = intersectInfo.faceId;
  13688. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13689. return pickingInfo;
  13690. }
  13691. return pickingInfo;
  13692. };
  13693. /**
  13694. * Clones the mesh, used by the class Mesh.
  13695. * Just returns `null` for an AbstractMesh.
  13696. */
  13697. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13698. return null;
  13699. };
  13700. /**
  13701. * Disposes all the mesh submeshes.
  13702. * Returns the AbstractMesh.
  13703. */
  13704. AbstractMesh.prototype.releaseSubMeshes = function () {
  13705. if (this.subMeshes) {
  13706. while (this.subMeshes.length) {
  13707. this.subMeshes[0].dispose();
  13708. }
  13709. }
  13710. else {
  13711. this.subMeshes = new Array();
  13712. }
  13713. return this;
  13714. };
  13715. /**
  13716. * Disposes the AbstractMesh.
  13717. * Some internal references are kept for further use.
  13718. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13719. * Returns nothing.
  13720. */
  13721. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13722. var _this = this;
  13723. var index;
  13724. // Action manager
  13725. if (this.actionManager) {
  13726. this.actionManager.dispose();
  13727. this.actionManager = null;
  13728. }
  13729. // Skeleton
  13730. this.skeleton = null;
  13731. // Animations
  13732. this.getScene().stopAnimation(this);
  13733. // Physics
  13734. if (this.physicsImpostor) {
  13735. this.physicsImpostor.dispose();
  13736. }
  13737. // Intersections in progress
  13738. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13739. var other = this._intersectionsInProgress[index];
  13740. var pos = other._intersectionsInProgress.indexOf(this);
  13741. other._intersectionsInProgress.splice(pos, 1);
  13742. }
  13743. this._intersectionsInProgress = [];
  13744. // Lights
  13745. var lights = this.getScene().lights;
  13746. lights.forEach(function (light) {
  13747. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13748. if (meshIndex !== -1) {
  13749. light.includedOnlyMeshes.splice(meshIndex, 1);
  13750. }
  13751. meshIndex = light.excludedMeshes.indexOf(_this);
  13752. if (meshIndex !== -1) {
  13753. light.excludedMeshes.splice(meshIndex, 1);
  13754. }
  13755. // Shadow generators
  13756. var generator = light.getShadowGenerator();
  13757. if (generator) {
  13758. var shadowMap = generator.getShadowMap();
  13759. meshIndex = shadowMap.renderList.indexOf(_this);
  13760. if (meshIndex !== -1) {
  13761. shadowMap.renderList.splice(meshIndex, 1);
  13762. }
  13763. }
  13764. });
  13765. // Edges
  13766. if (this._edgesRenderer) {
  13767. this._edgesRenderer.dispose();
  13768. this._edgesRenderer = null;
  13769. }
  13770. // SubMeshes
  13771. if (this.getClassName() !== "InstancedMesh") {
  13772. this.releaseSubMeshes();
  13773. }
  13774. // Octree
  13775. var sceneOctree = this.getScene().selectionOctree;
  13776. if (sceneOctree) {
  13777. var index = sceneOctree.dynamicContent.indexOf(this);
  13778. if (index !== -1) {
  13779. sceneOctree.dynamicContent.splice(index, 1);
  13780. }
  13781. }
  13782. // Query
  13783. var engine = this.getScene().getEngine();
  13784. if (this._occlusionQuery) {
  13785. this._isOcclusionQueryInProgress = false;
  13786. engine.deleteQuery(this._occlusionQuery);
  13787. this._occlusionQuery = null;
  13788. }
  13789. // Engine
  13790. engine.wipeCaches();
  13791. // Remove from scene
  13792. this.getScene().removeMesh(this);
  13793. if (!doNotRecurse) {
  13794. // Particles
  13795. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13796. if (this.getScene().particleSystems[index].emitter === this) {
  13797. this.getScene().particleSystems[index].dispose();
  13798. index--;
  13799. }
  13800. }
  13801. // Children
  13802. var objects = this.getDescendants(true);
  13803. for (index = 0; index < objects.length; index++) {
  13804. objects[index].dispose();
  13805. }
  13806. }
  13807. else {
  13808. var childMeshes = this.getChildMeshes(true);
  13809. for (index = 0; index < childMeshes.length; index++) {
  13810. var child = childMeshes[index];
  13811. child.parent = null;
  13812. child.computeWorldMatrix(true);
  13813. }
  13814. }
  13815. // facet data
  13816. if (this._facetDataEnabled) {
  13817. this.disableFacetData();
  13818. }
  13819. this.onAfterWorldMatrixUpdateObservable.clear();
  13820. this.onCollideObservable.clear();
  13821. this.onCollisionPositionChangeObservable.clear();
  13822. this._isDisposed = true;
  13823. _super.prototype.dispose.call(this);
  13824. };
  13825. /**
  13826. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13827. * This Vector3 is expressed in the World space.
  13828. */
  13829. AbstractMesh.prototype.getDirection = function (localAxis) {
  13830. var result = BABYLON.Vector3.Zero();
  13831. this.getDirectionToRef(localAxis, result);
  13832. return result;
  13833. };
  13834. /**
  13835. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13836. * localAxis is expressed in the mesh local space.
  13837. * result is computed in the Wordl space from the mesh World matrix.
  13838. * Returns the AbstractMesh.
  13839. */
  13840. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13841. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13842. return this;
  13843. };
  13844. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13845. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13846. if (this.getScene().getRenderId() == 0) {
  13847. this.computeWorldMatrix(true);
  13848. }
  13849. var wm = this.getWorldMatrix();
  13850. if (space == BABYLON.Space.WORLD) {
  13851. var tmat = BABYLON.Tmp.Matrix[0];
  13852. wm.invertToRef(tmat);
  13853. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13854. }
  13855. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13856. this._pivotMatrix.m[12] = -point.x;
  13857. this._pivotMatrix.m[13] = -point.y;
  13858. this._pivotMatrix.m[14] = -point.z;
  13859. this._cache.pivotMatrixUpdated = true;
  13860. return this;
  13861. };
  13862. /**
  13863. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13864. */
  13865. AbstractMesh.prototype.getPivotPoint = function () {
  13866. var point = BABYLON.Vector3.Zero();
  13867. this.getPivotPointToRef(point);
  13868. return point;
  13869. };
  13870. /**
  13871. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13872. * Returns the AbstractMesh.
  13873. */
  13874. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13875. result.x = -this._pivotMatrix.m[12];
  13876. result.y = -this._pivotMatrix.m[13];
  13877. result.z = -this._pivotMatrix.m[14];
  13878. return this;
  13879. };
  13880. /**
  13881. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13882. */
  13883. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13884. var point = BABYLON.Vector3.Zero();
  13885. this.getAbsolutePivotPointToRef(point);
  13886. return point;
  13887. };
  13888. /**
  13889. * Defines the passed mesh as the parent of the current mesh.
  13890. * Returns the AbstractMesh.
  13891. */
  13892. AbstractMesh.prototype.setParent = function (mesh) {
  13893. var child = this;
  13894. var parent = mesh;
  13895. if (mesh == null) {
  13896. var rotation = BABYLON.Tmp.Quaternion[0];
  13897. var position = BABYLON.Tmp.Vector3[0];
  13898. var scale = BABYLON.Tmp.Vector3[1];
  13899. child.getWorldMatrix().decompose(scale, rotation, position);
  13900. if (child.rotationQuaternion) {
  13901. child.rotationQuaternion.copyFrom(rotation);
  13902. }
  13903. else {
  13904. rotation.toEulerAnglesToRef(child.rotation);
  13905. }
  13906. child.position.x = position.x;
  13907. child.position.y = position.y;
  13908. child.position.z = position.z;
  13909. }
  13910. else {
  13911. var rotation = BABYLON.Tmp.Quaternion[0];
  13912. var position = BABYLON.Tmp.Vector3[0];
  13913. var scale = BABYLON.Tmp.Vector3[1];
  13914. var m1 = BABYLON.Tmp.Matrix[0];
  13915. var m2 = BABYLON.Tmp.Matrix[1];
  13916. parent.getWorldMatrix().decompose(scale, rotation, position);
  13917. rotation.toRotationMatrix(m1);
  13918. m2.setTranslation(position);
  13919. m2.multiplyToRef(m1, m1);
  13920. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13921. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13922. m.decompose(scale, rotation, position);
  13923. if (child.rotationQuaternion) {
  13924. child.rotationQuaternion.copyFrom(rotation);
  13925. }
  13926. else {
  13927. rotation.toEulerAnglesToRef(child.rotation);
  13928. }
  13929. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13930. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13931. m.decompose(scale, rotation, position);
  13932. child.position.x = position.x;
  13933. child.position.y = position.y;
  13934. child.position.z = position.z;
  13935. }
  13936. child.parent = parent;
  13937. return this;
  13938. };
  13939. /**
  13940. * Adds the passed mesh as a child to the current mesh.
  13941. * Returns the AbstractMesh.
  13942. */
  13943. AbstractMesh.prototype.addChild = function (mesh) {
  13944. mesh.setParent(this);
  13945. return this;
  13946. };
  13947. /**
  13948. * Removes the passed mesh from the current mesh children list.
  13949. * Returns the AbstractMesh.
  13950. */
  13951. AbstractMesh.prototype.removeChild = function (mesh) {
  13952. mesh.setParent(null);
  13953. return this;
  13954. };
  13955. /**
  13956. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13957. * Returns the AbstractMesh.
  13958. */
  13959. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13960. result.x = this._pivotMatrix.m[12];
  13961. result.y = this._pivotMatrix.m[13];
  13962. result.z = this._pivotMatrix.m[14];
  13963. this.getPivotPointToRef(result);
  13964. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13965. return this;
  13966. };
  13967. // Facet data
  13968. /**
  13969. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13970. * Returns the AbstractMesh.
  13971. */
  13972. AbstractMesh.prototype._initFacetData = function () {
  13973. if (!this._facetNormals) {
  13974. this._facetNormals = new Array();
  13975. }
  13976. if (!this._facetPositions) {
  13977. this._facetPositions = new Array();
  13978. }
  13979. if (!this._facetPartitioning) {
  13980. this._facetPartitioning = new Array();
  13981. }
  13982. this._facetNb = this.getIndices().length / 3;
  13983. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13984. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13985. for (var f = 0; f < this._facetNb; f++) {
  13986. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13987. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13988. }
  13989. this._facetDataEnabled = true;
  13990. return this;
  13991. };
  13992. /**
  13993. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13994. * This method can be called within the render loop.
  13995. * 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.
  13996. * Returns the AbstractMesh.
  13997. */
  13998. AbstractMesh.prototype.updateFacetData = function () {
  13999. if (!this._facetDataEnabled) {
  14000. this._initFacetData();
  14001. }
  14002. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14003. var indices = this.getIndices();
  14004. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14005. var bInfo = this.getBoundingInfo();
  14006. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14007. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14008. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14009. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14010. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14011. this._subDiv.max = this._partitioningSubdivisions;
  14012. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14013. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14014. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14015. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14016. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14017. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14018. // set the parameters for ComputeNormals()
  14019. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14020. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14021. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14022. this._facetParameters.bInfo = bInfo;
  14023. this._facetParameters.bbSize = this._bbSize;
  14024. this._facetParameters.subDiv = this._subDiv;
  14025. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14026. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14027. return this;
  14028. };
  14029. /**
  14030. * Returns the facetLocalNormals array.
  14031. * The normals are expressed in the mesh local space.
  14032. */
  14033. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14034. if (!this._facetNormals) {
  14035. this.updateFacetData();
  14036. }
  14037. return this._facetNormals;
  14038. };
  14039. /**
  14040. * Returns the facetLocalPositions array.
  14041. * The facet positions are expressed in the mesh local space.
  14042. */
  14043. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14044. if (!this._facetPositions) {
  14045. this.updateFacetData();
  14046. }
  14047. return this._facetPositions;
  14048. };
  14049. /**
  14050. * Returns the facetLocalPartioning array.
  14051. */
  14052. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14053. if (!this._facetPartitioning) {
  14054. this.updateFacetData();
  14055. }
  14056. return this._facetPartitioning;
  14057. };
  14058. /**
  14059. * Returns the i-th facet position in the world system.
  14060. * This method allocates a new Vector3 per call.
  14061. */
  14062. AbstractMesh.prototype.getFacetPosition = function (i) {
  14063. var pos = BABYLON.Vector3.Zero();
  14064. this.getFacetPositionToRef(i, pos);
  14065. return pos;
  14066. };
  14067. /**
  14068. * Sets the reference Vector3 with the i-th facet position in the world system.
  14069. * Returns the AbstractMesh.
  14070. */
  14071. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14072. var localPos = (this.getFacetLocalPositions())[i];
  14073. var world = this.getWorldMatrix();
  14074. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14075. return this;
  14076. };
  14077. /**
  14078. * Returns the i-th facet normal in the world system.
  14079. * This method allocates a new Vector3 per call.
  14080. */
  14081. AbstractMesh.prototype.getFacetNormal = function (i) {
  14082. var norm = BABYLON.Vector3.Zero();
  14083. this.getFacetNormalToRef(i, norm);
  14084. return norm;
  14085. };
  14086. /**
  14087. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14088. * Returns the AbstractMesh.
  14089. */
  14090. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14091. var localNorm = (this.getFacetLocalNormals())[i];
  14092. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14093. return this;
  14094. };
  14095. /**
  14096. * 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).
  14097. */
  14098. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14099. var bInfo = this.getBoundingInfo();
  14100. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14101. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14102. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14103. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14104. return null;
  14105. }
  14106. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14107. };
  14108. /**
  14109. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14110. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14111. * 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.
  14112. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14113. * 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.
  14114. */
  14115. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14116. if (checkFace === void 0) { checkFace = false; }
  14117. if (facing === void 0) { facing = true; }
  14118. var world = this.getWorldMatrix();
  14119. var invMat = BABYLON.Tmp.Matrix[5];
  14120. world.invertToRef(invMat);
  14121. var invVect = BABYLON.Tmp.Vector3[8];
  14122. var closest = null;
  14123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14124. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14125. if (projected) {
  14126. // tranform the local computed projected vector to world coordinates
  14127. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14128. }
  14129. return closest;
  14130. };
  14131. /**
  14132. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14133. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14134. * 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.
  14135. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14136. * 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.
  14137. */
  14138. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14139. if (checkFace === void 0) { checkFace = false; }
  14140. if (facing === void 0) { facing = true; }
  14141. var closest = null;
  14142. var tmpx = 0.0;
  14143. var tmpy = 0.0;
  14144. var tmpz = 0.0;
  14145. var d = 0.0; // tmp dot facet normal * facet position
  14146. var t0 = 0.0;
  14147. var projx = 0.0;
  14148. var projy = 0.0;
  14149. var projz = 0.0;
  14150. // Get all the facets in the same partitioning block than (x, y, z)
  14151. var facetPositions = this.getFacetLocalPositions();
  14152. var facetNormals = this.getFacetLocalNormals();
  14153. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14154. if (!facetsInBlock) {
  14155. return null;
  14156. }
  14157. // Get the closest facet to (x, y, z)
  14158. var shortest = Number.MAX_VALUE; // init distance vars
  14159. var tmpDistance = shortest;
  14160. var fib; // current facet in the block
  14161. var norm; // current facet normal
  14162. var p0; // current facet barycenter position
  14163. // loop on all the facets in the current partitioning block
  14164. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14165. fib = facetsInBlock[idx];
  14166. norm = facetNormals[fib];
  14167. p0 = facetPositions[fib];
  14168. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14169. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14170. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14171. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14172. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14173. projx = x + norm.x * t0;
  14174. projy = y + norm.y * t0;
  14175. projz = z + norm.z * t0;
  14176. tmpx = projx - x;
  14177. tmpy = projy - y;
  14178. tmpz = projz - z;
  14179. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14180. if (tmpDistance < shortest) {
  14181. shortest = tmpDistance;
  14182. closest = fib;
  14183. if (projected) {
  14184. projected.x = projx;
  14185. projected.y = projy;
  14186. projected.z = projz;
  14187. }
  14188. }
  14189. }
  14190. }
  14191. return closest;
  14192. };
  14193. /**
  14194. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14195. */
  14196. AbstractMesh.prototype.getFacetDataParameters = function () {
  14197. return this._facetParameters;
  14198. };
  14199. /**
  14200. * Disables the feature FacetData and frees the related memory.
  14201. * Returns the AbstractMesh.
  14202. */
  14203. AbstractMesh.prototype.disableFacetData = function () {
  14204. if (this._facetDataEnabled) {
  14205. this._facetDataEnabled = false;
  14206. this._facetPositions = null;
  14207. this._facetNormals = null;
  14208. this._facetPartitioning = null;
  14209. this._facetParameters = null;
  14210. }
  14211. return this;
  14212. };
  14213. /**
  14214. * Creates new normals data for the mesh.
  14215. * @param updatable.
  14216. */
  14217. AbstractMesh.prototype.createNormals = function (updatable) {
  14218. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14219. var indices = this.getIndices();
  14220. var normals;
  14221. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14222. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14223. }
  14224. else {
  14225. normals = [];
  14226. }
  14227. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14228. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14229. };
  14230. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14231. var engine = this.getEngine();
  14232. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14233. this._isOccluded = false;
  14234. return;
  14235. }
  14236. if (this.isOcclusionQueryInProgress) {
  14237. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14238. if (isOcclusionQueryAvailable) {
  14239. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14240. this._isOcclusionQueryInProgress = false;
  14241. this._occlusionInternalRetryCounter = 0;
  14242. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14243. }
  14244. else {
  14245. this._occlusionInternalRetryCounter++;
  14246. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14247. this._isOcclusionQueryInProgress = false;
  14248. this._occlusionInternalRetryCounter = 0;
  14249. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14250. // if strict continue the last state of the object.
  14251. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14252. }
  14253. else {
  14254. return;
  14255. }
  14256. }
  14257. }
  14258. var scene = this.getScene();
  14259. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14260. if (!this._occlusionQuery) {
  14261. this._occlusionQuery = engine.createQuery();
  14262. }
  14263. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14264. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14265. engine.endQuery(this.occlusionQueryAlgorithmType);
  14266. this._isOcclusionQueryInProgress = true;
  14267. };
  14268. // Statics
  14269. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14270. AbstractMesh._BILLBOARDMODE_X = 1;
  14271. AbstractMesh._BILLBOARDMODE_Y = 2;
  14272. AbstractMesh._BILLBOARDMODE_Z = 4;
  14273. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14274. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14275. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14276. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14277. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14278. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14279. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14280. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14281. return AbstractMesh;
  14282. }(BABYLON.Node));
  14283. BABYLON.AbstractMesh = AbstractMesh;
  14284. })(BABYLON || (BABYLON = {}));
  14285. //# sourceMappingURL=babylon.abstractMesh.js.map
  14286. var BABYLON;
  14287. (function (BABYLON) {
  14288. var Light = (function (_super) {
  14289. __extends(Light, _super);
  14290. /**
  14291. * Creates a Light object in the scene.
  14292. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14293. */
  14294. function Light(name, scene) {
  14295. var _this = _super.call(this, name, scene) || this;
  14296. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14297. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14298. _this.intensity = 1.0;
  14299. _this.range = Number.MAX_VALUE;
  14300. /**
  14301. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14302. * of light.
  14303. */
  14304. _this._photometricScale = 1.0;
  14305. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14306. _this._radius = 0.00001;
  14307. _this.renderPriority = 0;
  14308. /**
  14309. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14310. * the current shadow generator.
  14311. */
  14312. _this.shadowEnabled = true;
  14313. _this._excludeWithLayerMask = 0;
  14314. _this._includeOnlyWithLayerMask = 0;
  14315. _this._lightmapMode = 0;
  14316. _this._excludedMeshesIds = new Array();
  14317. _this._includedOnlyMeshesIds = new Array();
  14318. _this.getScene().addLight(_this);
  14319. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14320. _this._buildUniformLayout();
  14321. _this.includedOnlyMeshes = new Array();
  14322. _this.excludedMeshes = new Array();
  14323. _this._resyncMeshes();
  14324. return _this;
  14325. }
  14326. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14327. /**
  14328. * If every light affecting the material is in this lightmapMode,
  14329. * material.lightmapTexture adds or multiplies
  14330. * (depends on material.useLightmapAsShadowmap)
  14331. * after every other light calculations.
  14332. */
  14333. get: function () {
  14334. return Light._LIGHTMAP_DEFAULT;
  14335. },
  14336. enumerable: true,
  14337. configurable: true
  14338. });
  14339. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14340. /**
  14341. * material.lightmapTexture as only diffuse lighting from this light
  14342. * adds pnly specular lighting from this light
  14343. * adds dynamic shadows
  14344. */
  14345. get: function () {
  14346. return Light._LIGHTMAP_SPECULAR;
  14347. },
  14348. enumerable: true,
  14349. configurable: true
  14350. });
  14351. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14352. /**
  14353. * material.lightmapTexture as only lighting
  14354. * no light calculation from this light
  14355. * only adds dynamic shadows from this light
  14356. */
  14357. get: function () {
  14358. return Light._LIGHTMAP_SHADOWSONLY;
  14359. },
  14360. enumerable: true,
  14361. configurable: true
  14362. });
  14363. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14364. /**
  14365. * Each light type uses the default quantity according to its type:
  14366. * point/spot lights use luminous intensity
  14367. * directional lights use illuminance
  14368. */
  14369. get: function () {
  14370. return Light._INTENSITYMODE_AUTOMATIC;
  14371. },
  14372. enumerable: true,
  14373. configurable: true
  14374. });
  14375. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14376. /**
  14377. * lumen (lm)
  14378. */
  14379. get: function () {
  14380. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14386. /**
  14387. * candela (lm/sr)
  14388. */
  14389. get: function () {
  14390. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14391. },
  14392. enumerable: true,
  14393. configurable: true
  14394. });
  14395. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14396. /**
  14397. * lux (lm/m^2)
  14398. */
  14399. get: function () {
  14400. return Light._INTENSITYMODE_ILLUMINANCE;
  14401. },
  14402. enumerable: true,
  14403. configurable: true
  14404. });
  14405. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14406. /**
  14407. * nit (cd/m^2)
  14408. */
  14409. get: function () {
  14410. return Light._INTENSITYMODE_LUMINANCE;
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14416. /**
  14417. * Light type const id of the point light.
  14418. */
  14419. get: function () {
  14420. return Light._LIGHTTYPEID_POINTLIGHT;
  14421. },
  14422. enumerable: true,
  14423. configurable: true
  14424. });
  14425. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14426. /**
  14427. * Light type const id of the directional light.
  14428. */
  14429. get: function () {
  14430. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14431. },
  14432. enumerable: true,
  14433. configurable: true
  14434. });
  14435. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14436. /**
  14437. * Light type const id of the spot light.
  14438. */
  14439. get: function () {
  14440. return Light._LIGHTTYPEID_SPOTLIGHT;
  14441. },
  14442. enumerable: true,
  14443. configurable: true
  14444. });
  14445. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14446. /**
  14447. * Light type const id of the hemispheric light.
  14448. */
  14449. get: function () {
  14450. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14451. },
  14452. enumerable: true,
  14453. configurable: true
  14454. });
  14455. Object.defineProperty(Light.prototype, "intensityMode", {
  14456. /**
  14457. * Gets the photometric scale used to interpret the intensity.
  14458. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14459. */
  14460. get: function () {
  14461. return this._intensityMode;
  14462. },
  14463. /**
  14464. * Sets the photometric scale used to interpret the intensity.
  14465. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14466. */
  14467. set: function (value) {
  14468. this._intensityMode = value;
  14469. this._computePhotometricScale();
  14470. },
  14471. enumerable: true,
  14472. configurable: true
  14473. });
  14474. ;
  14475. ;
  14476. Object.defineProperty(Light.prototype, "radius", {
  14477. /**
  14478. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14479. */
  14480. get: function () {
  14481. return this._radius;
  14482. },
  14483. /**
  14484. * sets the light radius used by PBR Materials to simulate soft area lights.
  14485. */
  14486. set: function (value) {
  14487. this._radius = value;
  14488. this._computePhotometricScale();
  14489. },
  14490. enumerable: true,
  14491. configurable: true
  14492. });
  14493. ;
  14494. ;
  14495. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14496. get: function () {
  14497. return this._includedOnlyMeshes;
  14498. },
  14499. set: function (value) {
  14500. this._includedOnlyMeshes = value;
  14501. this._hookArrayForIncludedOnly(value);
  14502. },
  14503. enumerable: true,
  14504. configurable: true
  14505. });
  14506. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14507. get: function () {
  14508. return this._excludedMeshes;
  14509. },
  14510. set: function (value) {
  14511. this._excludedMeshes = value;
  14512. this._hookArrayForExcluded(value);
  14513. },
  14514. enumerable: true,
  14515. configurable: true
  14516. });
  14517. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14518. get: function () {
  14519. return this._excludeWithLayerMask;
  14520. },
  14521. set: function (value) {
  14522. this._excludeWithLayerMask = value;
  14523. this._resyncMeshes();
  14524. },
  14525. enumerable: true,
  14526. configurable: true
  14527. });
  14528. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14529. get: function () {
  14530. return this._includeOnlyWithLayerMask;
  14531. },
  14532. set: function (value) {
  14533. this._includeOnlyWithLayerMask = value;
  14534. this._resyncMeshes();
  14535. },
  14536. enumerable: true,
  14537. configurable: true
  14538. });
  14539. Object.defineProperty(Light.prototype, "lightmapMode", {
  14540. get: function () {
  14541. return this._lightmapMode;
  14542. },
  14543. set: function (value) {
  14544. if (this._lightmapMode === value) {
  14545. return;
  14546. }
  14547. this._lightmapMode = value;
  14548. this._markMeshesAsLightDirty();
  14549. },
  14550. enumerable: true,
  14551. configurable: true
  14552. });
  14553. Light.prototype._buildUniformLayout = function () {
  14554. // Overridden
  14555. };
  14556. /**
  14557. * Returns the string "Light".
  14558. */
  14559. Light.prototype.getClassName = function () {
  14560. return "Light";
  14561. };
  14562. /**
  14563. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14564. */
  14565. Light.prototype.toString = function (fullDetails) {
  14566. var ret = "Name: " + this.name;
  14567. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14568. if (this.animations) {
  14569. for (var i = 0; i < this.animations.length; i++) {
  14570. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14571. }
  14572. }
  14573. if (fullDetails) {
  14574. }
  14575. return ret;
  14576. };
  14577. /**
  14578. * Set the enabled state of this node.
  14579. * @param {boolean} value - the new enabled state
  14580. * @see isEnabled
  14581. */
  14582. Light.prototype.setEnabled = function (value) {
  14583. _super.prototype.setEnabled.call(this, value);
  14584. this._resyncMeshes();
  14585. };
  14586. /**
  14587. * Returns the Light associated shadow generator.
  14588. */
  14589. Light.prototype.getShadowGenerator = function () {
  14590. return this._shadowGenerator;
  14591. };
  14592. /**
  14593. * Returns a Vector3, the absolute light position in the World.
  14594. */
  14595. Light.prototype.getAbsolutePosition = function () {
  14596. return BABYLON.Vector3.Zero();
  14597. };
  14598. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14599. };
  14600. Light.prototype._getWorldMatrix = function () {
  14601. return BABYLON.Matrix.Identity();
  14602. };
  14603. /**
  14604. * Boolean : True if the light will affect the passed mesh.
  14605. */
  14606. Light.prototype.canAffectMesh = function (mesh) {
  14607. if (!mesh) {
  14608. return true;
  14609. }
  14610. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14611. return false;
  14612. }
  14613. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14614. return false;
  14615. }
  14616. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14617. return false;
  14618. }
  14619. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14620. return false;
  14621. }
  14622. return true;
  14623. };
  14624. /**
  14625. * Returns the light World matrix.
  14626. */
  14627. Light.prototype.getWorldMatrix = function () {
  14628. this._currentRenderId = this.getScene().getRenderId();
  14629. var worldMatrix = this._getWorldMatrix();
  14630. if (this.parent && this.parent.getWorldMatrix) {
  14631. if (!this._parentedWorldMatrix) {
  14632. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14633. }
  14634. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14635. this._markSyncedWithParent();
  14636. return this._parentedWorldMatrix;
  14637. }
  14638. return worldMatrix;
  14639. };
  14640. /**
  14641. * Sort function to order lights for rendering.
  14642. * @param a First Light object to compare to second.
  14643. * @param b Second Light object to compare first.
  14644. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14645. */
  14646. Light.compareLightsPriority = function (a, b) {
  14647. //shadow-casting lights have priority over non-shadow-casting lights
  14648. //the renderPrioirty is a secondary sort criterion
  14649. if (a.shadowEnabled !== b.shadowEnabled) {
  14650. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14651. }
  14652. return b.renderPriority - a.renderPriority;
  14653. };
  14654. /**
  14655. * Disposes the light.
  14656. */
  14657. Light.prototype.dispose = function () {
  14658. if (this._shadowGenerator) {
  14659. this._shadowGenerator.dispose();
  14660. this._shadowGenerator = null;
  14661. }
  14662. // Animations
  14663. this.getScene().stopAnimation(this);
  14664. // Remove from meshes
  14665. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14666. var mesh = _a[_i];
  14667. mesh._removeLightSource(this);
  14668. }
  14669. this._uniformBuffer.dispose();
  14670. // Remove from scene
  14671. this.getScene().removeLight(this);
  14672. _super.prototype.dispose.call(this);
  14673. };
  14674. /**
  14675. * Returns the light type ID (integer).
  14676. */
  14677. Light.prototype.getTypeID = function () {
  14678. return 0;
  14679. };
  14680. /**
  14681. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14682. */
  14683. Light.prototype.getScaledIntensity = function () {
  14684. return this._photometricScale * this.intensity;
  14685. };
  14686. /**
  14687. * Returns a new Light object, named "name", from the current one.
  14688. */
  14689. Light.prototype.clone = function (name) {
  14690. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14691. };
  14692. /**
  14693. * Serializes the current light into a Serialization object.
  14694. * Returns the serialized object.
  14695. */
  14696. Light.prototype.serialize = function () {
  14697. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14698. // Type
  14699. serializationObject.type = this.getTypeID();
  14700. // Parent
  14701. if (this.parent) {
  14702. serializationObject.parentId = this.parent.id;
  14703. }
  14704. // Inclusion / exclusions
  14705. if (this.excludedMeshes.length > 0) {
  14706. serializationObject.excludedMeshesIds = [];
  14707. this.excludedMeshes.forEach(function (mesh) {
  14708. serializationObject.excludedMeshesIds.push(mesh.id);
  14709. });
  14710. }
  14711. if (this.includedOnlyMeshes.length > 0) {
  14712. serializationObject.includedOnlyMeshesIds = [];
  14713. this.includedOnlyMeshes.forEach(function (mesh) {
  14714. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14715. });
  14716. }
  14717. // Animations
  14718. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14719. serializationObject.ranges = this.serializeAnimationRanges();
  14720. return serializationObject;
  14721. };
  14722. /**
  14723. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14724. * This new light is named "name" and added to the passed scene.
  14725. */
  14726. Light.GetConstructorFromName = function (type, name, scene) {
  14727. switch (type) {
  14728. case 0:
  14729. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14730. case 1:
  14731. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14732. case 2:
  14733. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14734. case 3:
  14735. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14736. }
  14737. };
  14738. /**
  14739. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14740. */
  14741. Light.Parse = function (parsedLight, scene) {
  14742. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14743. // Inclusion / exclusions
  14744. if (parsedLight.excludedMeshesIds) {
  14745. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14746. }
  14747. if (parsedLight.includedOnlyMeshesIds) {
  14748. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14749. }
  14750. // Parent
  14751. if (parsedLight.parentId) {
  14752. light._waitingParentId = parsedLight.parentId;
  14753. }
  14754. // Animations
  14755. if (parsedLight.animations) {
  14756. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14757. var parsedAnimation = parsedLight.animations[animationIndex];
  14758. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14759. }
  14760. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14761. }
  14762. if (parsedLight.autoAnimate) {
  14763. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14764. }
  14765. return light;
  14766. };
  14767. Light.prototype._hookArrayForExcluded = function (array) {
  14768. var _this = this;
  14769. var oldPush = array.push;
  14770. array.push = function () {
  14771. var items = [];
  14772. for (var _i = 0; _i < arguments.length; _i++) {
  14773. items[_i] = arguments[_i];
  14774. }
  14775. var result = oldPush.apply(array, items);
  14776. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14777. var item = items_1[_a];
  14778. item._resyncLighSource(_this);
  14779. }
  14780. return result;
  14781. };
  14782. var oldSplice = array.splice;
  14783. array.splice = function (index, deleteCount) {
  14784. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14785. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14786. var item = deleted_1[_i];
  14787. item._resyncLighSource(_this);
  14788. }
  14789. return deleted;
  14790. };
  14791. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14792. var item = array_1[_i];
  14793. item._resyncLighSource(this);
  14794. }
  14795. };
  14796. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14797. var _this = this;
  14798. var oldPush = array.push;
  14799. array.push = function () {
  14800. var items = [];
  14801. for (var _i = 0; _i < arguments.length; _i++) {
  14802. items[_i] = arguments[_i];
  14803. }
  14804. var result = oldPush.apply(array, items);
  14805. _this._resyncMeshes();
  14806. return result;
  14807. };
  14808. var oldSplice = array.splice;
  14809. array.splice = function (index, deleteCount) {
  14810. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14811. _this._resyncMeshes();
  14812. return deleted;
  14813. };
  14814. this._resyncMeshes();
  14815. };
  14816. Light.prototype._resyncMeshes = function () {
  14817. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14818. var mesh = _a[_i];
  14819. mesh._resyncLighSource(this);
  14820. }
  14821. };
  14822. Light.prototype._markMeshesAsLightDirty = function () {
  14823. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14824. var mesh = _a[_i];
  14825. if (mesh._lightSources.indexOf(this) !== -1) {
  14826. mesh._markSubMeshesAsLightDirty();
  14827. }
  14828. }
  14829. };
  14830. /**
  14831. * Recomputes the cached photometric scale if needed.
  14832. */
  14833. Light.prototype._computePhotometricScale = function () {
  14834. this._photometricScale = this._getPhotometricScale();
  14835. this.getScene().resetCachedMaterial();
  14836. };
  14837. /**
  14838. * Returns the Photometric Scale according to the light type and intensity mode.
  14839. */
  14840. Light.prototype._getPhotometricScale = function () {
  14841. var photometricScale = 0.0;
  14842. var lightTypeID = this.getTypeID();
  14843. //get photometric mode
  14844. var photometricMode = this.intensityMode;
  14845. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14846. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14847. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14848. }
  14849. else {
  14850. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14851. }
  14852. }
  14853. //compute photometric scale
  14854. switch (lightTypeID) {
  14855. case Light.LIGHTTYPEID_POINTLIGHT:
  14856. case Light.LIGHTTYPEID_SPOTLIGHT:
  14857. switch (photometricMode) {
  14858. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14859. photometricScale = 1.0 / (4.0 * Math.PI);
  14860. break;
  14861. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14862. photometricScale = 1.0;
  14863. break;
  14864. case Light.INTENSITYMODE_LUMINANCE:
  14865. photometricScale = this.radius * this.radius;
  14866. break;
  14867. }
  14868. break;
  14869. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14870. switch (photometricMode) {
  14871. case Light.INTENSITYMODE_ILLUMINANCE:
  14872. photometricScale = 1.0;
  14873. break;
  14874. case Light.INTENSITYMODE_LUMINANCE:
  14875. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14876. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14877. var apexAngleRadians = this.radius;
  14878. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14879. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14880. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14881. photometricScale = solidAngle;
  14882. break;
  14883. }
  14884. break;
  14885. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14886. // No fall off in hemisperic light.
  14887. photometricScale = 1.0;
  14888. break;
  14889. }
  14890. return photometricScale;
  14891. };
  14892. Light.prototype._reorderLightsInScene = function () {
  14893. var scene = this.getScene();
  14894. if (this.renderPriority != 0) {
  14895. scene.requireLightSorting = true;
  14896. }
  14897. this.getScene().sortLightsByPriority();
  14898. };
  14899. //lightmapMode Consts
  14900. Light._LIGHTMAP_DEFAULT = 0;
  14901. Light._LIGHTMAP_SPECULAR = 1;
  14902. Light._LIGHTMAP_SHADOWSONLY = 2;
  14903. // Intensity Mode Consts
  14904. Light._INTENSITYMODE_AUTOMATIC = 0;
  14905. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14906. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14907. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14908. Light._INTENSITYMODE_LUMINANCE = 4;
  14909. // Light types ids const.
  14910. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14911. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14912. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14913. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14914. __decorate([
  14915. BABYLON.serializeAsColor3()
  14916. ], Light.prototype, "diffuse", void 0);
  14917. __decorate([
  14918. BABYLON.serializeAsColor3()
  14919. ], Light.prototype, "specular", void 0);
  14920. __decorate([
  14921. BABYLON.serialize()
  14922. ], Light.prototype, "intensity", void 0);
  14923. __decorate([
  14924. BABYLON.serialize()
  14925. ], Light.prototype, "range", void 0);
  14926. __decorate([
  14927. BABYLON.serialize()
  14928. ], Light.prototype, "intensityMode", null);
  14929. __decorate([
  14930. BABYLON.serialize()
  14931. ], Light.prototype, "radius", null);
  14932. __decorate([
  14933. BABYLON.serialize()
  14934. ], Light.prototype, "_renderPriority", void 0);
  14935. __decorate([
  14936. BABYLON.expandToProperty("_reorderLightsInScene")
  14937. ], Light.prototype, "renderPriority", void 0);
  14938. __decorate([
  14939. BABYLON.serialize()
  14940. ], Light.prototype, "shadowEnabled", void 0);
  14941. __decorate([
  14942. BABYLON.serialize("excludeWithLayerMask")
  14943. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14944. __decorate([
  14945. BABYLON.serialize("includeOnlyWithLayerMask")
  14946. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14947. __decorate([
  14948. BABYLON.serialize("lightmapMode")
  14949. ], Light.prototype, "_lightmapMode", void 0);
  14950. return Light;
  14951. }(BABYLON.Node));
  14952. BABYLON.Light = Light;
  14953. })(BABYLON || (BABYLON = {}));
  14954. //# sourceMappingURL=babylon.light.js.map
  14955. var BABYLON;
  14956. (function (BABYLON) {
  14957. var Camera = (function (_super) {
  14958. __extends(Camera, _super);
  14959. function Camera(name, position, scene) {
  14960. var _this = _super.call(this, name, scene) || this;
  14961. _this.upVector = BABYLON.Vector3.Up();
  14962. _this.orthoLeft = null;
  14963. _this.orthoRight = null;
  14964. _this.orthoBottom = null;
  14965. _this.orthoTop = null;
  14966. _this.fov = 0.8;
  14967. _this.minZ = 1;
  14968. _this.maxZ = 10000.0;
  14969. _this.inertia = 0.9;
  14970. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14971. _this.isIntermediate = false;
  14972. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14973. _this.layerMask = 0x0FFFFFFF;
  14974. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14975. // Camera rig members
  14976. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14977. _this._rigCameras = new Array();
  14978. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14979. _this.customRenderTargets = new Array();
  14980. // Observables
  14981. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14982. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14983. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14984. _this.onRestoreStateObservable = new BABYLON.Observable();
  14985. // Cache
  14986. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14987. _this._projectionMatrix = new BABYLON.Matrix();
  14988. _this._doNotComputeProjectionMatrix = false;
  14989. _this._postProcesses = new Array();
  14990. _this._transformMatrix = BABYLON.Matrix.Zero();
  14991. _this._activeMeshes = new BABYLON.SmartArray(256);
  14992. _this._globalPosition = BABYLON.Vector3.Zero();
  14993. _this._refreshFrustumPlanes = true;
  14994. _this.getScene().addCamera(_this);
  14995. if (!_this.getScene().activeCamera) {
  14996. _this.getScene().activeCamera = _this;
  14997. }
  14998. _this.position = position;
  14999. return _this;
  15000. }
  15001. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15002. get: function () {
  15003. return Camera._PERSPECTIVE_CAMERA;
  15004. },
  15005. enumerable: true,
  15006. configurable: true
  15007. });
  15008. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15009. get: function () {
  15010. return Camera._ORTHOGRAPHIC_CAMERA;
  15011. },
  15012. enumerable: true,
  15013. configurable: true
  15014. });
  15015. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15016. get: function () {
  15017. return Camera._FOVMODE_VERTICAL_FIXED;
  15018. },
  15019. enumerable: true,
  15020. configurable: true
  15021. });
  15022. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15023. get: function () {
  15024. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15025. },
  15026. enumerable: true,
  15027. configurable: true
  15028. });
  15029. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15030. get: function () {
  15031. return Camera._RIG_MODE_NONE;
  15032. },
  15033. enumerable: true,
  15034. configurable: true
  15035. });
  15036. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15037. get: function () {
  15038. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15039. },
  15040. enumerable: true,
  15041. configurable: true
  15042. });
  15043. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15044. get: function () {
  15045. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15046. },
  15047. enumerable: true,
  15048. configurable: true
  15049. });
  15050. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15051. get: function () {
  15052. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15053. },
  15054. enumerable: true,
  15055. configurable: true
  15056. });
  15057. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15058. get: function () {
  15059. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15060. },
  15061. enumerable: true,
  15062. configurable: true
  15063. });
  15064. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15065. get: function () {
  15066. return Camera._RIG_MODE_VR;
  15067. },
  15068. enumerable: true,
  15069. configurable: true
  15070. });
  15071. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15072. get: function () {
  15073. return Camera._RIG_MODE_WEBVR;
  15074. },
  15075. enumerable: true,
  15076. configurable: true
  15077. });
  15078. /**
  15079. * Store current camera state (fov, position, etc..)
  15080. */
  15081. Camera.prototype.storeState = function () {
  15082. this._stateStored = true;
  15083. this._storedFov = this.fov;
  15084. return this;
  15085. };
  15086. /**
  15087. * Restores the camera state values if it has been stored. You must call storeState() first
  15088. */
  15089. Camera.prototype._restoreStateValues = function () {
  15090. if (!this._stateStored) {
  15091. return false;
  15092. }
  15093. this.fov = this._storedFov;
  15094. return true;
  15095. };
  15096. /**
  15097. * Restored camera state. You must call storeState() first
  15098. */
  15099. Camera.prototype.restoreState = function () {
  15100. if (this._restoreStateValues()) {
  15101. this.onRestoreStateObservable.notifyObservers(this);
  15102. return true;
  15103. }
  15104. return false;
  15105. };
  15106. Camera.prototype.getClassName = function () {
  15107. return "Camera";
  15108. };
  15109. /**
  15110. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15111. */
  15112. Camera.prototype.toString = function (fullDetails) {
  15113. var ret = "Name: " + this.name;
  15114. ret += ", type: " + this.getClassName();
  15115. if (this.animations) {
  15116. for (var i = 0; i < this.animations.length; i++) {
  15117. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15118. }
  15119. }
  15120. if (fullDetails) {
  15121. }
  15122. return ret;
  15123. };
  15124. Object.defineProperty(Camera.prototype, "globalPosition", {
  15125. get: function () {
  15126. return this._globalPosition;
  15127. },
  15128. enumerable: true,
  15129. configurable: true
  15130. });
  15131. Camera.prototype.getActiveMeshes = function () {
  15132. return this._activeMeshes;
  15133. };
  15134. Camera.prototype.isActiveMesh = function (mesh) {
  15135. return (this._activeMeshes.indexOf(mesh) !== -1);
  15136. };
  15137. //Cache
  15138. Camera.prototype._initCache = function () {
  15139. _super.prototype._initCache.call(this);
  15140. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15141. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15142. this._cache.mode = undefined;
  15143. this._cache.minZ = undefined;
  15144. this._cache.maxZ = undefined;
  15145. this._cache.fov = undefined;
  15146. this._cache.fovMode = undefined;
  15147. this._cache.aspectRatio = undefined;
  15148. this._cache.orthoLeft = undefined;
  15149. this._cache.orthoRight = undefined;
  15150. this._cache.orthoBottom = undefined;
  15151. this._cache.orthoTop = undefined;
  15152. this._cache.renderWidth = undefined;
  15153. this._cache.renderHeight = undefined;
  15154. };
  15155. Camera.prototype._updateCache = function (ignoreParentClass) {
  15156. if (!ignoreParentClass) {
  15157. _super.prototype._updateCache.call(this);
  15158. }
  15159. var engine = this.getEngine();
  15160. this._cache.position.copyFrom(this.position);
  15161. this._cache.upVector.copyFrom(this.upVector);
  15162. this._cache.mode = this.mode;
  15163. this._cache.minZ = this.minZ;
  15164. this._cache.maxZ = this.maxZ;
  15165. this._cache.fov = this.fov;
  15166. this._cache.fovMode = this.fovMode;
  15167. this._cache.aspectRatio = engine.getAspectRatio(this);
  15168. this._cache.orthoLeft = this.orthoLeft;
  15169. this._cache.orthoRight = this.orthoRight;
  15170. this._cache.orthoBottom = this.orthoBottom;
  15171. this._cache.orthoTop = this.orthoTop;
  15172. this._cache.renderWidth = engine.getRenderWidth();
  15173. this._cache.renderHeight = engine.getRenderHeight();
  15174. };
  15175. Camera.prototype._updateFromScene = function () {
  15176. this.updateCache();
  15177. this.update();
  15178. };
  15179. // Synchronized
  15180. Camera.prototype._isSynchronized = function () {
  15181. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15182. };
  15183. Camera.prototype._isSynchronizedViewMatrix = function () {
  15184. if (!_super.prototype._isSynchronized.call(this))
  15185. return false;
  15186. return this._cache.position.equals(this.position)
  15187. && this._cache.upVector.equals(this.upVector)
  15188. && this.isSynchronizedWithParent();
  15189. };
  15190. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15191. var check = this._cache.mode === this.mode
  15192. && this._cache.minZ === this.minZ
  15193. && this._cache.maxZ === this.maxZ;
  15194. if (!check) {
  15195. return false;
  15196. }
  15197. var engine = this.getEngine();
  15198. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15199. check = this._cache.fov === this.fov
  15200. && this._cache.fovMode === this.fovMode
  15201. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15202. }
  15203. else {
  15204. check = this._cache.orthoLeft === this.orthoLeft
  15205. && this._cache.orthoRight === this.orthoRight
  15206. && this._cache.orthoBottom === this.orthoBottom
  15207. && this._cache.orthoTop === this.orthoTop
  15208. && this._cache.renderWidth === engine.getRenderWidth()
  15209. && this._cache.renderHeight === engine.getRenderHeight();
  15210. }
  15211. return check;
  15212. };
  15213. // Controls
  15214. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15215. };
  15216. Camera.prototype.detachControl = function (element) {
  15217. };
  15218. Camera.prototype.update = function () {
  15219. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15220. this._updateRigCameras();
  15221. }
  15222. this._checkInputs();
  15223. };
  15224. Camera.prototype._checkInputs = function () {
  15225. this.onAfterCheckInputsObservable.notifyObservers(this);
  15226. };
  15227. Object.defineProperty(Camera.prototype, "rigCameras", {
  15228. get: function () {
  15229. return this._rigCameras;
  15230. },
  15231. enumerable: true,
  15232. configurable: true
  15233. });
  15234. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15235. get: function () {
  15236. return this._rigPostProcess;
  15237. },
  15238. enumerable: true,
  15239. configurable: true
  15240. });
  15241. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15242. // invalidate framebuffer
  15243. if (this._postProcesses.length > 0) {
  15244. this._postProcesses[0].markTextureDirty();
  15245. }
  15246. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15247. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15248. var cam = this._rigCameras[i];
  15249. var rigPostProcess = cam._rigPostProcess;
  15250. // for VR rig, there does not have to be a post process
  15251. if (rigPostProcess) {
  15252. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15253. if (isPass) {
  15254. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15255. cam.isIntermediate = this._postProcesses.length === 0;
  15256. }
  15257. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15258. rigPostProcess.markTextureDirty();
  15259. }
  15260. else {
  15261. cam._postProcesses = this._postProcesses.slice(0);
  15262. }
  15263. }
  15264. };
  15265. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15266. if (insertAt === void 0) { insertAt = null; }
  15267. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15268. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15269. return 0;
  15270. }
  15271. if (insertAt == null || insertAt < 0) {
  15272. this._postProcesses.push(postProcess);
  15273. }
  15274. else {
  15275. this._postProcesses.splice(insertAt, 0, postProcess);
  15276. }
  15277. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15278. return this._postProcesses.indexOf(postProcess);
  15279. };
  15280. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15281. if (atIndices === void 0) { atIndices = null; }
  15282. var result = [];
  15283. var i;
  15284. var index;
  15285. if (!atIndices) {
  15286. var idx = this._postProcesses.indexOf(postProcess);
  15287. if (idx !== -1) {
  15288. this._postProcesses.splice(idx, 1);
  15289. }
  15290. }
  15291. else {
  15292. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15293. // iterate descending, so can just splice as we go
  15294. for (i = atIndices.length - 1; i >= 0; i--) {
  15295. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15296. result.push(i);
  15297. continue;
  15298. }
  15299. index = atIndices[i];
  15300. this._postProcesses.splice(index, 1);
  15301. }
  15302. }
  15303. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15304. return result;
  15305. };
  15306. Camera.prototype.getWorldMatrix = function () {
  15307. if (!this._worldMatrix) {
  15308. this._worldMatrix = BABYLON.Matrix.Identity();
  15309. }
  15310. var viewMatrix = this.getViewMatrix();
  15311. viewMatrix.invertToRef(this._worldMatrix);
  15312. return this._worldMatrix;
  15313. };
  15314. Camera.prototype._getViewMatrix = function () {
  15315. return BABYLON.Matrix.Identity();
  15316. };
  15317. Camera.prototype.getViewMatrix = function (force) {
  15318. if (!force && this._isSynchronizedViewMatrix()) {
  15319. return this._computedViewMatrix;
  15320. }
  15321. this._computedViewMatrix = this._getViewMatrix();
  15322. this._currentRenderId = this.getScene().getRenderId();
  15323. this._refreshFrustumPlanes = true;
  15324. if (!this.parent || !this.parent.getWorldMatrix) {
  15325. this._globalPosition.copyFrom(this.position);
  15326. }
  15327. else {
  15328. if (!this._worldMatrix) {
  15329. this._worldMatrix = BABYLON.Matrix.Identity();
  15330. }
  15331. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15332. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15333. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15334. this._computedViewMatrix.invert();
  15335. this._markSyncedWithParent();
  15336. }
  15337. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15338. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15339. }
  15340. this.onViewMatrixChangedObservable.notifyObservers(this);
  15341. return this._computedViewMatrix;
  15342. };
  15343. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15344. this._doNotComputeProjectionMatrix = true;
  15345. if (projection !== undefined) {
  15346. this._projectionMatrix = projection;
  15347. }
  15348. };
  15349. ;
  15350. Camera.prototype.unfreezeProjectionMatrix = function () {
  15351. this._doNotComputeProjectionMatrix = false;
  15352. };
  15353. ;
  15354. Camera.prototype.getProjectionMatrix = function (force) {
  15355. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15356. return this._projectionMatrix;
  15357. }
  15358. this._refreshFrustumPlanes = true;
  15359. var engine = this.getEngine();
  15360. var scene = this.getScene();
  15361. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15362. if (this.minZ <= 0) {
  15363. this.minZ = 0.1;
  15364. }
  15365. if (scene.useRightHandedSystem) {
  15366. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15367. }
  15368. else {
  15369. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15370. }
  15371. }
  15372. else {
  15373. var halfWidth = engine.getRenderWidth() / 2.0;
  15374. var halfHeight = engine.getRenderHeight() / 2.0;
  15375. if (scene.useRightHandedSystem) {
  15376. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15377. }
  15378. else {
  15379. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15380. }
  15381. }
  15382. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15383. return this._projectionMatrix;
  15384. };
  15385. Camera.prototype.getTranformationMatrix = function () {
  15386. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15387. return this._transformMatrix;
  15388. };
  15389. Camera.prototype.updateFrustumPlanes = function () {
  15390. if (!this._refreshFrustumPlanes) {
  15391. return;
  15392. }
  15393. this.getTranformationMatrix();
  15394. if (!this._frustumPlanes) {
  15395. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15396. }
  15397. else {
  15398. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15399. }
  15400. this._refreshFrustumPlanes = false;
  15401. };
  15402. Camera.prototype.isInFrustum = function (target) {
  15403. this.updateFrustumPlanes();
  15404. return target.isInFrustum(this._frustumPlanes);
  15405. };
  15406. Camera.prototype.isCompletelyInFrustum = function (target) {
  15407. this.updateFrustumPlanes();
  15408. return target.isCompletelyInFrustum(this._frustumPlanes);
  15409. };
  15410. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15411. if (length === void 0) { length = 100; }
  15412. if (!transform) {
  15413. transform = this.getWorldMatrix();
  15414. }
  15415. if (!origin) {
  15416. origin = this.position;
  15417. }
  15418. var forward = new BABYLON.Vector3(0, 0, 1);
  15419. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15420. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15421. return new BABYLON.Ray(origin, direction, length);
  15422. };
  15423. Camera.prototype.dispose = function () {
  15424. // Observables
  15425. this.onViewMatrixChangedObservable.clear();
  15426. this.onProjectionMatrixChangedObservable.clear();
  15427. this.onAfterCheckInputsObservable.clear();
  15428. this.onRestoreStateObservable.clear();
  15429. // Inputs
  15430. if (this.inputs) {
  15431. this.inputs.clear();
  15432. }
  15433. // Animations
  15434. this.getScene().stopAnimation(this);
  15435. // Remove from scene
  15436. this.getScene().removeCamera(this);
  15437. while (this._rigCameras.length > 0) {
  15438. this._rigCameras.pop().dispose();
  15439. }
  15440. // Postprocesses
  15441. var i = this._postProcesses.length;
  15442. while (--i >= 0) {
  15443. this._postProcesses[i].dispose(this);
  15444. }
  15445. // Render targets
  15446. var i = this.customRenderTargets.length;
  15447. while (--i >= 0) {
  15448. this.customRenderTargets[i].dispose();
  15449. }
  15450. this.customRenderTargets = [];
  15451. // Active Meshes
  15452. this._activeMeshes.dispose();
  15453. _super.prototype.dispose.call(this);
  15454. };
  15455. Object.defineProperty(Camera.prototype, "leftCamera", {
  15456. // ---- Camera rigs section ----
  15457. get: function () {
  15458. if (this._rigCameras.length < 1) {
  15459. return undefined;
  15460. }
  15461. return this._rigCameras[0];
  15462. },
  15463. enumerable: true,
  15464. configurable: true
  15465. });
  15466. Object.defineProperty(Camera.prototype, "rightCamera", {
  15467. get: function () {
  15468. if (this._rigCameras.length < 2) {
  15469. return undefined;
  15470. }
  15471. return this._rigCameras[1];
  15472. },
  15473. enumerable: true,
  15474. configurable: true
  15475. });
  15476. Camera.prototype.getLeftTarget = function () {
  15477. if (this._rigCameras.length < 1) {
  15478. return undefined;
  15479. }
  15480. return this._rigCameras[0].getTarget();
  15481. };
  15482. Camera.prototype.getRightTarget = function () {
  15483. if (this._rigCameras.length < 2) {
  15484. return undefined;
  15485. }
  15486. return this._rigCameras[1].getTarget();
  15487. };
  15488. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15489. while (this._rigCameras.length > 0) {
  15490. this._rigCameras.pop().dispose();
  15491. }
  15492. this.cameraRigMode = mode;
  15493. this._cameraRigParams = {};
  15494. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15495. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15496. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15497. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15498. // create the rig cameras, unless none
  15499. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15500. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15501. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15502. }
  15503. switch (this.cameraRigMode) {
  15504. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15505. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15506. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15507. break;
  15508. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15509. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15510. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15511. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15512. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15513. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15514. break;
  15515. case Camera.RIG_MODE_VR:
  15516. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15517. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15518. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15519. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15520. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15521. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15522. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15523. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15524. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15525. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15526. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15527. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15528. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15529. if (metrics.compensateDistortion) {
  15530. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15531. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15532. }
  15533. break;
  15534. case Camera.RIG_MODE_WEBVR:
  15535. if (rigParams.vrDisplay) {
  15536. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15537. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15538. //Left eye
  15539. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15540. this._rigCameras[0].setCameraRigParameter("left", true);
  15541. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15542. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15543. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15544. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15545. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15546. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15547. this._rigCameras[0].parent = this;
  15548. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15549. //Right eye
  15550. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15551. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15552. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15553. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15554. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15555. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15556. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15557. this._rigCameras[1].parent = this;
  15558. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15559. }
  15560. break;
  15561. }
  15562. this._cascadePostProcessesToRigCams();
  15563. this.
  15564. update();
  15565. };
  15566. Camera.prototype._getVRProjectionMatrix = function () {
  15567. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15568. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15569. return this._projectionMatrix;
  15570. };
  15571. Camera.prototype._updateCameraRotationMatrix = function () {
  15572. //Here for WebVR
  15573. };
  15574. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15575. //Here for WebVR
  15576. };
  15577. /**
  15578. * This function MUST be overwritten by the different WebVR cameras available.
  15579. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15580. */
  15581. Camera.prototype._getWebVRProjectionMatrix = function () {
  15582. return BABYLON.Matrix.Identity();
  15583. };
  15584. /**
  15585. * This function MUST be overwritten by the different WebVR cameras available.
  15586. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15587. */
  15588. Camera.prototype._getWebVRViewMatrix = function () {
  15589. return BABYLON.Matrix.Identity();
  15590. };
  15591. Camera.prototype.setCameraRigParameter = function (name, value) {
  15592. if (!this._cameraRigParams) {
  15593. this._cameraRigParams = {};
  15594. }
  15595. this._cameraRigParams[name] = value;
  15596. //provisionnally:
  15597. if (name === "interaxialDistance") {
  15598. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15599. }
  15600. };
  15601. /**
  15602. * needs to be overridden by children so sub has required properties to be copied
  15603. */
  15604. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15605. return null;
  15606. };
  15607. /**
  15608. * May need to be overridden by children
  15609. */
  15610. Camera.prototype._updateRigCameras = function () {
  15611. for (var i = 0; i < this._rigCameras.length; i++) {
  15612. this._rigCameras[i].minZ = this.minZ;
  15613. this._rigCameras[i].maxZ = this.maxZ;
  15614. this._rigCameras[i].fov = this.fov;
  15615. }
  15616. // only update viewport when ANAGLYPH
  15617. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15618. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15619. }
  15620. };
  15621. Camera.prototype._setupInputs = function () {
  15622. };
  15623. Camera.prototype.serialize = function () {
  15624. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15625. // Type
  15626. serializationObject.type = this.getClassName();
  15627. // Parent
  15628. if (this.parent) {
  15629. serializationObject.parentId = this.parent.id;
  15630. }
  15631. if (this.inputs) {
  15632. this.inputs.serialize(serializationObject);
  15633. }
  15634. // Animations
  15635. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15636. serializationObject.ranges = this.serializeAnimationRanges();
  15637. return serializationObject;
  15638. };
  15639. Camera.prototype.clone = function (name) {
  15640. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15641. };
  15642. Camera.prototype.getDirection = function (localAxis) {
  15643. var result = BABYLON.Vector3.Zero();
  15644. this.getDirectionToRef(localAxis, result);
  15645. return result;
  15646. };
  15647. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15648. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15649. };
  15650. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15651. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15652. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15653. switch (type) {
  15654. case "ArcRotateCamera":
  15655. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15656. case "DeviceOrientationCamera":
  15657. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15658. case "FollowCamera":
  15659. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15660. case "ArcFollowCamera":
  15661. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15662. case "GamepadCamera":
  15663. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15664. case "TouchCamera":
  15665. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15666. case "VirtualJoysticksCamera":
  15667. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15668. case "WebVRFreeCamera":
  15669. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15670. case "WebVRGamepadCamera":
  15671. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15672. case "VRDeviceOrientationFreeCamera":
  15673. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15674. case "VRDeviceOrientationGamepadCamera":
  15675. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15676. case "AnaglyphArcRotateCamera":
  15677. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15678. case "AnaglyphFreeCamera":
  15679. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15680. case "AnaglyphGamepadCamera":
  15681. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15682. case "AnaglyphUniversalCamera":
  15683. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15684. case "StereoscopicArcRotateCamera":
  15685. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15686. case "StereoscopicFreeCamera":
  15687. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15688. case "StereoscopicGamepadCamera":
  15689. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15690. case "StereoscopicUniversalCamera":
  15691. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15692. case "FreeCamera":// Forcing Universal here
  15693. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15694. default:// Universal Camera is the default value
  15695. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15696. }
  15697. };
  15698. Camera.Parse = function (parsedCamera, scene) {
  15699. var type = parsedCamera.type;
  15700. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15701. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15702. // Parent
  15703. if (parsedCamera.parentId) {
  15704. camera._waitingParentId = parsedCamera.parentId;
  15705. }
  15706. //If camera has an input manager, let it parse inputs settings
  15707. if (camera.inputs) {
  15708. camera.inputs.parse(parsedCamera);
  15709. camera._setupInputs();
  15710. }
  15711. if (camera.setPosition) {
  15712. camera.position.copyFromFloats(0, 0, 0);
  15713. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15714. }
  15715. // Target
  15716. if (parsedCamera.target) {
  15717. if (camera.setTarget) {
  15718. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15719. }
  15720. }
  15721. // Apply 3d rig, when found
  15722. if (parsedCamera.cameraRigMode) {
  15723. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15724. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15725. }
  15726. // Animations
  15727. if (parsedCamera.animations) {
  15728. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15729. var parsedAnimation = parsedCamera.animations[animationIndex];
  15730. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15731. }
  15732. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15733. }
  15734. if (parsedCamera.autoAnimate) {
  15735. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15736. }
  15737. return camera;
  15738. };
  15739. // Statics
  15740. Camera._PERSPECTIVE_CAMERA = 0;
  15741. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15742. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15743. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15744. Camera._RIG_MODE_NONE = 0;
  15745. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15746. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15747. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15748. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15749. Camera._RIG_MODE_VR = 20;
  15750. Camera._RIG_MODE_WEBVR = 21;
  15751. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15752. __decorate([
  15753. BABYLON.serializeAsVector3()
  15754. ], Camera.prototype, "position", void 0);
  15755. __decorate([
  15756. BABYLON.serializeAsVector3()
  15757. ], Camera.prototype, "upVector", void 0);
  15758. __decorate([
  15759. BABYLON.serialize()
  15760. ], Camera.prototype, "orthoLeft", void 0);
  15761. __decorate([
  15762. BABYLON.serialize()
  15763. ], Camera.prototype, "orthoRight", void 0);
  15764. __decorate([
  15765. BABYLON.serialize()
  15766. ], Camera.prototype, "orthoBottom", void 0);
  15767. __decorate([
  15768. BABYLON.serialize()
  15769. ], Camera.prototype, "orthoTop", void 0);
  15770. __decorate([
  15771. BABYLON.serialize()
  15772. ], Camera.prototype, "fov", void 0);
  15773. __decorate([
  15774. BABYLON.serialize()
  15775. ], Camera.prototype, "minZ", void 0);
  15776. __decorate([
  15777. BABYLON.serialize()
  15778. ], Camera.prototype, "maxZ", void 0);
  15779. __decorate([
  15780. BABYLON.serialize()
  15781. ], Camera.prototype, "inertia", void 0);
  15782. __decorate([
  15783. BABYLON.serialize()
  15784. ], Camera.prototype, "mode", void 0);
  15785. __decorate([
  15786. BABYLON.serialize()
  15787. ], Camera.prototype, "layerMask", void 0);
  15788. __decorate([
  15789. BABYLON.serialize()
  15790. ], Camera.prototype, "fovMode", void 0);
  15791. __decorate([
  15792. BABYLON.serialize()
  15793. ], Camera.prototype, "cameraRigMode", void 0);
  15794. __decorate([
  15795. BABYLON.serialize()
  15796. ], Camera.prototype, "interaxialDistance", void 0);
  15797. __decorate([
  15798. BABYLON.serialize()
  15799. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15800. return Camera;
  15801. }(BABYLON.Node));
  15802. BABYLON.Camera = Camera;
  15803. })(BABYLON || (BABYLON = {}));
  15804. //# sourceMappingURL=babylon.camera.js.map
  15805. var BABYLON;
  15806. (function (BABYLON) {
  15807. var RenderingManager = (function () {
  15808. function RenderingManager(scene) {
  15809. this._renderingGroups = new Array();
  15810. this._autoClearDepthStencil = {};
  15811. this._customOpaqueSortCompareFn = {};
  15812. this._customAlphaTestSortCompareFn = {};
  15813. this._customTransparentSortCompareFn = {};
  15814. this._renderinGroupInfo = null;
  15815. this._scene = scene;
  15816. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15817. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15818. }
  15819. }
  15820. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15821. if (depth === void 0) { depth = true; }
  15822. if (stencil === void 0) { stencil = true; }
  15823. if (this._depthStencilBufferAlreadyCleaned) {
  15824. return;
  15825. }
  15826. this._scene.getEngine().clear(null, false, depth, stencil);
  15827. this._depthStencilBufferAlreadyCleaned = true;
  15828. };
  15829. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15830. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15831. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15832. var info = null;
  15833. if (observable) {
  15834. if (!this._renderinGroupInfo) {
  15835. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15836. }
  15837. info = this._renderinGroupInfo;
  15838. info.scene = this._scene;
  15839. info.camera = this._scene.activeCamera;
  15840. }
  15841. // Dispatch sprites
  15842. if (renderSprites) {
  15843. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15844. var manager = this._scene.spriteManagers[index];
  15845. this.dispatchSprites(manager);
  15846. }
  15847. }
  15848. // Render
  15849. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15850. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15851. var renderingGroup = this._renderingGroups[index];
  15852. if (!renderingGroup && !observable)
  15853. continue;
  15854. this._currentIndex = index;
  15855. var renderingGroupMask = 0;
  15856. // Fire PRECLEAR stage
  15857. if (observable) {
  15858. renderingGroupMask = Math.pow(2, index);
  15859. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15860. info.renderingGroupId = index;
  15861. observable.notifyObservers(info, renderingGroupMask);
  15862. }
  15863. // Clear depth/stencil if needed
  15864. if (RenderingManager.AUTOCLEAR) {
  15865. var autoClear = this._autoClearDepthStencil[index];
  15866. if (autoClear && autoClear.autoClear) {
  15867. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15868. }
  15869. }
  15870. if (observable) {
  15871. // Fire PREOPAQUE stage
  15872. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15873. observable.notifyObservers(info, renderingGroupMask);
  15874. // Fire PRETRANSPARENT stage
  15875. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15876. observable.notifyObservers(info, renderingGroupMask);
  15877. }
  15878. if (renderingGroup)
  15879. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15880. // Fire POSTTRANSPARENT stage
  15881. if (observable) {
  15882. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15883. observable.notifyObservers(info, renderingGroupMask);
  15884. }
  15885. }
  15886. };
  15887. RenderingManager.prototype.reset = function () {
  15888. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15889. var renderingGroup = this._renderingGroups[index];
  15890. if (renderingGroup) {
  15891. renderingGroup.prepare();
  15892. }
  15893. }
  15894. };
  15895. RenderingManager.prototype.dispose = function () {
  15896. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15897. var renderingGroup = this._renderingGroups[index];
  15898. if (renderingGroup) {
  15899. renderingGroup.dispose();
  15900. }
  15901. }
  15902. this._renderingGroups.length = 0;
  15903. };
  15904. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15905. if (!this._renderingGroups[renderingGroupId]) {
  15906. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15907. }
  15908. };
  15909. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15910. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15911. this._prepareRenderingGroup(renderingGroupId);
  15912. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15913. };
  15914. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15915. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15916. this._prepareRenderingGroup(renderingGroupId);
  15917. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15918. };
  15919. RenderingManager.prototype.dispatch = function (subMesh) {
  15920. var mesh = subMesh.getMesh();
  15921. var renderingGroupId = mesh.renderingGroupId || 0;
  15922. this._prepareRenderingGroup(renderingGroupId);
  15923. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15924. };
  15925. /**
  15926. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15927. * This allowed control for front to back rendering or reversly depending of the special needs.
  15928. *
  15929. * @param renderingGroupId The rendering group id corresponding to its index
  15930. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15931. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15932. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15933. */
  15934. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15935. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15936. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15937. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15938. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15939. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15940. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15941. if (this._renderingGroups[renderingGroupId]) {
  15942. var group = this._renderingGroups[renderingGroupId];
  15943. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15944. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15945. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15946. }
  15947. };
  15948. /**
  15949. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15950. *
  15951. * @param renderingGroupId The rendering group id corresponding to its index
  15952. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15953. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15954. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15955. */
  15956. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15957. if (depth === void 0) { depth = true; }
  15958. if (stencil === void 0) { stencil = true; }
  15959. this._autoClearDepthStencil[renderingGroupId] = {
  15960. autoClear: autoClearDepthStencil,
  15961. depth: depth,
  15962. stencil: stencil
  15963. };
  15964. };
  15965. /**
  15966. * The max id used for rendering groups (not included)
  15967. */
  15968. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15969. /**
  15970. * The min id used for rendering groups (included)
  15971. */
  15972. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15973. /**
  15974. * Used to globally prevent autoclearing scenes.
  15975. */
  15976. RenderingManager.AUTOCLEAR = true;
  15977. return RenderingManager;
  15978. }());
  15979. BABYLON.RenderingManager = RenderingManager;
  15980. })(BABYLON || (BABYLON = {}));
  15981. //# sourceMappingURL=babylon.renderingManager.js.map
  15982. var BABYLON;
  15983. (function (BABYLON) {
  15984. var RenderingGroup = (function () {
  15985. /**
  15986. * Creates a new rendering group.
  15987. * @param index The rendering group index
  15988. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15989. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15990. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15991. */
  15992. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15993. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15994. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15995. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15996. this.index = index;
  15997. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15998. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15999. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16000. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16001. this._particleSystems = new BABYLON.SmartArray(256);
  16002. this._spriteManagers = new BABYLON.SmartArray(256);
  16003. this._edgesRenderers = new BABYLON.SmartArray(16);
  16004. this._scene = scene;
  16005. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16006. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16007. this.transparentSortCompareFn = transparentSortCompareFn;
  16008. }
  16009. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16010. /**
  16011. * Set the opaque sort comparison function.
  16012. * If null the sub meshes will be render in the order they were created
  16013. */
  16014. set: function (value) {
  16015. this._opaqueSortCompareFn = value;
  16016. if (value) {
  16017. this._renderOpaque = this.renderOpaqueSorted;
  16018. }
  16019. else {
  16020. this._renderOpaque = RenderingGroup.renderUnsorted;
  16021. }
  16022. },
  16023. enumerable: true,
  16024. configurable: true
  16025. });
  16026. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16027. /**
  16028. * Set the alpha test sort comparison function.
  16029. * If null the sub meshes will be render in the order they were created
  16030. */
  16031. set: function (value) {
  16032. this._alphaTestSortCompareFn = value;
  16033. if (value) {
  16034. this._renderAlphaTest = this.renderAlphaTestSorted;
  16035. }
  16036. else {
  16037. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16038. }
  16039. },
  16040. enumerable: true,
  16041. configurable: true
  16042. });
  16043. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16044. /**
  16045. * Set the transparent sort comparison function.
  16046. * If null the sub meshes will be render in the order they were created
  16047. */
  16048. set: function (value) {
  16049. if (value) {
  16050. this._transparentSortCompareFn = value;
  16051. }
  16052. else {
  16053. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16054. }
  16055. this._renderTransparent = this.renderTransparentSorted;
  16056. },
  16057. enumerable: true,
  16058. configurable: true
  16059. });
  16060. /**
  16061. * Render all the sub meshes contained in the group.
  16062. * @param customRenderFunction Used to override the default render behaviour of the group.
  16063. * @returns true if rendered some submeshes.
  16064. */
  16065. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16066. if (customRenderFunction) {
  16067. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16068. return;
  16069. }
  16070. var engine = this._scene.getEngine();
  16071. // Depth only
  16072. if (this._depthOnlySubMeshes.length !== 0) {
  16073. engine.setAlphaTesting(true);
  16074. engine.setColorWrite(false);
  16075. this._renderAlphaTest(this._depthOnlySubMeshes);
  16076. engine.setAlphaTesting(false);
  16077. engine.setColorWrite(true);
  16078. }
  16079. // Opaque
  16080. if (this._opaqueSubMeshes.length !== 0) {
  16081. this._renderOpaque(this._opaqueSubMeshes);
  16082. }
  16083. // Alpha test
  16084. if (this._alphaTestSubMeshes.length !== 0) {
  16085. engine.setAlphaTesting(true);
  16086. this._renderAlphaTest(this._alphaTestSubMeshes);
  16087. engine.setAlphaTesting(false);
  16088. }
  16089. var stencilState = engine.getStencilBuffer();
  16090. engine.setStencilBuffer(false);
  16091. // Sprites
  16092. if (renderSprites) {
  16093. this._renderSprites();
  16094. }
  16095. // Particles
  16096. if (renderParticles) {
  16097. this._renderParticles(activeMeshes);
  16098. }
  16099. if (this.onBeforeTransparentRendering) {
  16100. this.onBeforeTransparentRendering();
  16101. }
  16102. // Transparent
  16103. if (this._transparentSubMeshes.length !== 0) {
  16104. this._renderTransparent(this._transparentSubMeshes);
  16105. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16106. }
  16107. // Set back stencil to false in case it changes before the edge renderer.
  16108. engine.setStencilBuffer(false);
  16109. // Edges
  16110. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16111. this._edgesRenderers.data[edgesRendererIndex].render();
  16112. }
  16113. // Restore Stencil state.
  16114. engine.setStencilBuffer(stencilState);
  16115. };
  16116. /**
  16117. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16118. * @param subMeshes The submeshes to render
  16119. */
  16120. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16121. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16122. };
  16123. /**
  16124. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16125. * @param subMeshes The submeshes to render
  16126. */
  16127. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16128. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16129. };
  16130. /**
  16131. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16132. * @param subMeshes The submeshes to render
  16133. */
  16134. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16135. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16136. };
  16137. /**
  16138. * Renders the submeshes in a specified order.
  16139. * @param subMeshes The submeshes to sort before render
  16140. * @param sortCompareFn The comparison function use to sort
  16141. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16142. * @param transparent Specifies to activate blending if true
  16143. */
  16144. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16145. var subIndex = 0;
  16146. var subMesh;
  16147. for (; subIndex < subMeshes.length; subIndex++) {
  16148. subMesh = subMeshes.data[subIndex];
  16149. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16150. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16151. }
  16152. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16153. sortedArray.sort(sortCompareFn);
  16154. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16155. subMesh = sortedArray[subIndex];
  16156. if (transparent) {
  16157. var material = subMesh.getMaterial();
  16158. if (material.needDepthPrePass) {
  16159. var engine = material.getScene().getEngine();
  16160. engine.setColorWrite(false);
  16161. engine.setAlphaTesting(true);
  16162. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16163. subMesh.render(false);
  16164. engine.setAlphaTesting(false);
  16165. engine.setColorWrite(true);
  16166. }
  16167. }
  16168. subMesh.render(transparent);
  16169. }
  16170. };
  16171. /**
  16172. * Renders the submeshes in the order they were dispatched (no sort applied).
  16173. * @param subMeshes The submeshes to render
  16174. */
  16175. RenderingGroup.renderUnsorted = function (subMeshes) {
  16176. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16177. var submesh = subMeshes.data[subIndex];
  16178. submesh.render(false);
  16179. }
  16180. };
  16181. /**
  16182. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16183. * are rendered back to front if in the same alpha index.
  16184. *
  16185. * @param a The first submesh
  16186. * @param b The second submesh
  16187. * @returns The result of the comparison
  16188. */
  16189. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16190. // Alpha index first
  16191. if (a._alphaIndex > b._alphaIndex) {
  16192. return 1;
  16193. }
  16194. if (a._alphaIndex < b._alphaIndex) {
  16195. return -1;
  16196. }
  16197. // Then distance to camera
  16198. return RenderingGroup.backToFrontSortCompare(a, b);
  16199. };
  16200. /**
  16201. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16202. * are rendered back to front.
  16203. *
  16204. * @param a The first submesh
  16205. * @param b The second submesh
  16206. * @returns The result of the comparison
  16207. */
  16208. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16209. // Then distance to camera
  16210. if (a._distanceToCamera < b._distanceToCamera) {
  16211. return 1;
  16212. }
  16213. if (a._distanceToCamera > b._distanceToCamera) {
  16214. return -1;
  16215. }
  16216. return 0;
  16217. };
  16218. /**
  16219. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16220. * are rendered front to back (prevent overdraw).
  16221. *
  16222. * @param a The first submesh
  16223. * @param b The second submesh
  16224. * @returns The result of the comparison
  16225. */
  16226. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16227. // Then distance to camera
  16228. if (a._distanceToCamera < b._distanceToCamera) {
  16229. return -1;
  16230. }
  16231. if (a._distanceToCamera > b._distanceToCamera) {
  16232. return 1;
  16233. }
  16234. return 0;
  16235. };
  16236. /**
  16237. * Resets the different lists of submeshes to prepare a new frame.
  16238. */
  16239. RenderingGroup.prototype.prepare = function () {
  16240. this._opaqueSubMeshes.reset();
  16241. this._transparentSubMeshes.reset();
  16242. this._alphaTestSubMeshes.reset();
  16243. this._depthOnlySubMeshes.reset();
  16244. this._particleSystems.reset();
  16245. this._spriteManagers.reset();
  16246. this._edgesRenderers.reset();
  16247. };
  16248. RenderingGroup.prototype.dispose = function () {
  16249. this._opaqueSubMeshes.dispose();
  16250. this._transparentSubMeshes.dispose();
  16251. this._alphaTestSubMeshes.dispose();
  16252. this._depthOnlySubMeshes.dispose();
  16253. this._particleSystems.dispose();
  16254. this._spriteManagers.dispose();
  16255. this._edgesRenderers.dispose();
  16256. };
  16257. /**
  16258. * Inserts the submesh in its correct queue depending on its material.
  16259. * @param subMesh The submesh to dispatch
  16260. */
  16261. RenderingGroup.prototype.dispatch = function (subMesh) {
  16262. var material = subMesh.getMaterial();
  16263. var mesh = subMesh.getMesh();
  16264. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16265. this._transparentSubMeshes.push(subMesh);
  16266. }
  16267. else if (material.needAlphaTesting()) {
  16268. if (material.needDepthPrePass) {
  16269. this._depthOnlySubMeshes.push(subMesh);
  16270. }
  16271. this._alphaTestSubMeshes.push(subMesh);
  16272. }
  16273. else {
  16274. if (material.needDepthPrePass) {
  16275. this._depthOnlySubMeshes.push(subMesh);
  16276. }
  16277. this._opaqueSubMeshes.push(subMesh); // Opaque
  16278. }
  16279. if (mesh._edgesRenderer) {
  16280. this._edgesRenderers.push(mesh._edgesRenderer);
  16281. }
  16282. };
  16283. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16284. this._spriteManagers.push(spriteManager);
  16285. };
  16286. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16287. this._particleSystems.push(particleSystem);
  16288. };
  16289. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16290. if (this._particleSystems.length === 0) {
  16291. return;
  16292. }
  16293. // Particles
  16294. var activeCamera = this._scene.activeCamera;
  16295. this._scene._particlesDuration.beginMonitoring();
  16296. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16297. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16298. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16299. continue;
  16300. }
  16301. var emitter = particleSystem.emitter;
  16302. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16303. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16304. }
  16305. }
  16306. this._scene._particlesDuration.endMonitoring(false);
  16307. };
  16308. RenderingGroup.prototype._renderSprites = function () {
  16309. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16310. return;
  16311. }
  16312. // Sprites
  16313. var activeCamera = this._scene.activeCamera;
  16314. this._scene._spritesDuration.beginMonitoring();
  16315. for (var id = 0; id < this._spriteManagers.length; id++) {
  16316. var spriteManager = this._spriteManagers.data[id];
  16317. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16318. spriteManager.render();
  16319. }
  16320. }
  16321. this._scene._spritesDuration.endMonitoring(false);
  16322. };
  16323. return RenderingGroup;
  16324. }());
  16325. BABYLON.RenderingGroup = RenderingGroup;
  16326. })(BABYLON || (BABYLON = {}));
  16327. //# sourceMappingURL=babylon.renderingGroup.js.map
  16328. var BABYLON;
  16329. (function (BABYLON) {
  16330. var ClickInfo = (function () {
  16331. function ClickInfo() {
  16332. this._singleClick = false;
  16333. this._doubleClick = false;
  16334. this._hasSwiped = false;
  16335. this._ignore = false;
  16336. }
  16337. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16338. get: function () {
  16339. return this._singleClick;
  16340. },
  16341. set: function (b) {
  16342. this._singleClick = b;
  16343. },
  16344. enumerable: true,
  16345. configurable: true
  16346. });
  16347. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16348. get: function () {
  16349. return this._doubleClick;
  16350. },
  16351. set: function (b) {
  16352. this._doubleClick = b;
  16353. },
  16354. enumerable: true,
  16355. configurable: true
  16356. });
  16357. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16358. get: function () {
  16359. return this._hasSwiped;
  16360. },
  16361. set: function (b) {
  16362. this._hasSwiped = b;
  16363. },
  16364. enumerable: true,
  16365. configurable: true
  16366. });
  16367. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16368. get: function () {
  16369. return this._ignore;
  16370. },
  16371. set: function (b) {
  16372. this._ignore = b;
  16373. },
  16374. enumerable: true,
  16375. configurable: true
  16376. });
  16377. return ClickInfo;
  16378. }());
  16379. /**
  16380. * This class is used by the onRenderingGroupObservable
  16381. */
  16382. var RenderingGroupInfo = (function () {
  16383. function RenderingGroupInfo() {
  16384. }
  16385. /**
  16386. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16387. * This stage will be fired no matter what
  16388. */
  16389. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16390. /**
  16391. * Called before opaque object are rendered.
  16392. * This stage will be fired only if there's 3D Opaque content to render
  16393. */
  16394. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16395. /**
  16396. * Called after the opaque objects are rendered and before the transparent ones
  16397. * This stage will be fired only if there's 3D transparent content to render
  16398. */
  16399. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16400. /**
  16401. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16402. * This stage will be fired no matter what
  16403. */
  16404. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16405. return RenderingGroupInfo;
  16406. }());
  16407. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16408. /**
  16409. * Represents a scene to be rendered by the engine.
  16410. * @see http://doc.babylonjs.com/page.php?p=21911
  16411. */
  16412. var Scene = (function () {
  16413. /**
  16414. * @constructor
  16415. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16416. */
  16417. function Scene(engine) {
  16418. // Members
  16419. this.autoClear = true;
  16420. this.autoClearDepthAndStencil = true;
  16421. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16422. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16423. this.forceWireframe = false;
  16424. this._forcePointsCloud = false;
  16425. this.forceShowBoundingBoxes = false;
  16426. this.animationsEnabled = true;
  16427. this.constantlyUpdateMeshUnderPointer = false;
  16428. this.hoverCursor = "pointer";
  16429. this.defaultCursor = "";
  16430. // Metadata
  16431. this.metadata = null;
  16432. /**
  16433. * An event triggered when the scene is disposed.
  16434. * @type {BABYLON.Observable}
  16435. */
  16436. this.onDisposeObservable = new BABYLON.Observable();
  16437. /**
  16438. * An event triggered before rendering the scene
  16439. * @type {BABYLON.Observable}
  16440. */
  16441. this.onBeforeRenderObservable = new BABYLON.Observable();
  16442. /**
  16443. * An event triggered after rendering the scene
  16444. * @type {BABYLON.Observable}
  16445. */
  16446. this.onAfterRenderObservable = new BABYLON.Observable();
  16447. /**
  16448. * An event triggered when the scene is ready
  16449. * @type {BABYLON.Observable}
  16450. */
  16451. this.onReadyObservable = new BABYLON.Observable();
  16452. /**
  16453. * An event triggered before rendering a camera
  16454. * @type {BABYLON.Observable}
  16455. */
  16456. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16457. /**
  16458. * An event triggered after rendering a camera
  16459. * @type {BABYLON.Observable}
  16460. */
  16461. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16462. /**
  16463. * An event triggered when a camera is created
  16464. * @type {BABYLON.Observable}
  16465. */
  16466. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16467. /**
  16468. * An event triggered when a camera is removed
  16469. * @type {BABYLON.Observable}
  16470. */
  16471. this.onCameraRemovedObservable = new BABYLON.Observable();
  16472. /**
  16473. * An event triggered when a light is created
  16474. * @type {BABYLON.Observable}
  16475. */
  16476. this.onNewLightAddedObservable = new BABYLON.Observable();
  16477. /**
  16478. * An event triggered when a light is removed
  16479. * @type {BABYLON.Observable}
  16480. */
  16481. this.onLightRemovedObservable = new BABYLON.Observable();
  16482. /**
  16483. * An event triggered when a geometry is created
  16484. * @type {BABYLON.Observable}
  16485. */
  16486. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16487. /**
  16488. * An event triggered when a geometry is removed
  16489. * @type {BABYLON.Observable}
  16490. */
  16491. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16492. /**
  16493. * An event triggered when a mesh is created
  16494. * @type {BABYLON.Observable}
  16495. */
  16496. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16497. /**
  16498. * An event triggered when a mesh is removed
  16499. * @type {BABYLON.Observable}
  16500. */
  16501. this.onMeshRemovedObservable = new BABYLON.Observable();
  16502. /**
  16503. * An event triggered before calculating deterministic simulation step
  16504. * @type {BABYLON.Observable}
  16505. */
  16506. this.onBeforeStepObservable = new BABYLON.Observable();
  16507. /**
  16508. * An event triggered after calculating deterministic simulation step
  16509. * @type {BABYLON.Observable}
  16510. */
  16511. this.onAfterStepObservable = new BABYLON.Observable();
  16512. /**
  16513. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16514. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16515. * 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)
  16516. */
  16517. this.onRenderingGroupObservable = new BABYLON.Observable();
  16518. // Animations
  16519. this.animations = [];
  16520. /**
  16521. * 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).
  16522. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16523. */
  16524. this.onPrePointerObservable = new BABYLON.Observable();
  16525. /**
  16526. * Observable event triggered each time an input event is received from the rendering canvas
  16527. */
  16528. this.onPointerObservable = new BABYLON.Observable();
  16529. this._meshPickProceed = false;
  16530. this._previousHasSwiped = false;
  16531. this._currentPickResult = null;
  16532. this._previousPickResult = null;
  16533. this._isButtonPressed = false;
  16534. this._doubleClickOccured = false;
  16535. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16536. this.cameraToUseForPointers = null;
  16537. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16538. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16539. this._startingPointerTime = 0;
  16540. this._previousStartingPointerTime = 0;
  16541. // Deterministic lockstep
  16542. this._timeAccumulator = 0;
  16543. this._currentStepId = 0;
  16544. this._currentInternalStep = 0;
  16545. // Keyboard
  16546. /**
  16547. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16548. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16549. */
  16550. this.onPreKeyboardObservable = new BABYLON.Observable();
  16551. /**
  16552. * Observable event triggered each time an keyboard event is received from the hosting window
  16553. */
  16554. this.onKeyboardObservable = new BABYLON.Observable();
  16555. // Coordinate system
  16556. /**
  16557. * use right-handed coordinate system on this scene.
  16558. * @type {boolean}
  16559. */
  16560. this._useRightHandedSystem = false;
  16561. // Fog
  16562. this._fogEnabled = true;
  16563. this._fogMode = Scene.FOGMODE_NONE;
  16564. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16565. this.fogDensity = 0.1;
  16566. this.fogStart = 0;
  16567. this.fogEnd = 1000.0;
  16568. // Lights
  16569. /**
  16570. * is shadow enabled on this scene.
  16571. * @type {boolean}
  16572. */
  16573. this._shadowsEnabled = true;
  16574. /**
  16575. * is light enabled on this scene.
  16576. * @type {boolean}
  16577. */
  16578. this._lightsEnabled = true;
  16579. /**
  16580. * All of the lights added to this scene.
  16581. * @see BABYLON.Light
  16582. * @type {BABYLON.Light[]}
  16583. */
  16584. this.lights = new Array();
  16585. // Cameras
  16586. /** All of the cameras added to this scene. */
  16587. this.cameras = new Array();
  16588. /** All of the active cameras added to this scene. */
  16589. this.activeCameras = new Array();
  16590. // Meshes
  16591. /**
  16592. * All of the (abstract) meshes added to this scene.
  16593. * @see BABYLON.AbstractMesh
  16594. * @type {BABYLON.AbstractMesh[]}
  16595. */
  16596. this.meshes = new Array();
  16597. // Geometries
  16598. this._geometries = new Array();
  16599. this.materials = new Array();
  16600. this.multiMaterials = new Array();
  16601. // Textures
  16602. this._texturesEnabled = true;
  16603. this.textures = new Array();
  16604. // Particles
  16605. this.particlesEnabled = true;
  16606. this.particleSystems = new Array();
  16607. // Sprites
  16608. this.spritesEnabled = true;
  16609. this.spriteManagers = new Array();
  16610. // Layers
  16611. this.layers = new Array();
  16612. this.highlightLayers = new Array();
  16613. // Skeletons
  16614. this._skeletonsEnabled = true;
  16615. this.skeletons = new Array();
  16616. // Morph targets
  16617. this.morphTargetManagers = new Array();
  16618. // Lens flares
  16619. this.lensFlaresEnabled = true;
  16620. this.lensFlareSystems = new Array();
  16621. // Collisions
  16622. this.collisionsEnabled = true;
  16623. /** Defines the gravity applied to this scene */
  16624. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16625. // Postprocesses
  16626. this.postProcesses = new Array();
  16627. this.postProcessesEnabled = true;
  16628. // Customs render targets
  16629. this.renderTargetsEnabled = true;
  16630. this.dumpNextRenderTargets = false;
  16631. this.customRenderTargets = new Array();
  16632. // Imported meshes
  16633. this.importedMeshesFiles = new Array();
  16634. // Probes
  16635. this.probesEnabled = true;
  16636. this.reflectionProbes = new Array();
  16637. this._actionManagers = new Array();
  16638. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16639. // Procedural textures
  16640. this.proceduralTexturesEnabled = true;
  16641. this._proceduralTextures = new Array();
  16642. this.soundTracks = new Array();
  16643. this._audioEnabled = true;
  16644. this._headphone = false;
  16645. // Performance counters
  16646. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16647. this._totalLightsCounter = new BABYLON.PerfCounter();
  16648. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16649. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16650. this._totalVertices = new BABYLON.PerfCounter();
  16651. this._activeIndices = new BABYLON.PerfCounter();
  16652. this._activeParticles = new BABYLON.PerfCounter();
  16653. this._lastFrameDuration = new BABYLON.PerfCounter();
  16654. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16655. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16656. this._particlesDuration = new BABYLON.PerfCounter();
  16657. this._renderDuration = new BABYLON.PerfCounter();
  16658. this._spritesDuration = new BABYLON.PerfCounter();
  16659. this._activeBones = new BABYLON.PerfCounter();
  16660. this._animationTime = 0;
  16661. this.animationTimeScale = 1;
  16662. this._renderId = 0;
  16663. this._executeWhenReadyTimeoutId = -1;
  16664. this._intermediateRendering = false;
  16665. this._viewUpdateFlag = -1;
  16666. this._projectionUpdateFlag = -1;
  16667. this._toBeDisposed = new BABYLON.SmartArray(256);
  16668. this._pendingData = []; //ANY
  16669. this._activeMeshes = new BABYLON.SmartArray(256);
  16670. this._processedMaterials = new BABYLON.SmartArray(256);
  16671. this._renderTargets = new BABYLON.SmartArray(256);
  16672. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16673. this._activeSkeletons = new BABYLON.SmartArray(32);
  16674. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16675. this._activeAnimatables = new Array();
  16676. this._transformMatrix = BABYLON.Matrix.Zero();
  16677. this.requireLightSorting = false;
  16678. this._uniqueIdCounter = 0;
  16679. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16680. this._engine.scenes.push(this);
  16681. this._uid = null;
  16682. this._renderingManager = new BABYLON.RenderingManager(this);
  16683. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16684. if (BABYLON.OutlineRenderer) {
  16685. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16686. }
  16687. this.attachControl();
  16688. if (BABYLON.SoundTrack) {
  16689. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16690. }
  16691. //simplification queue
  16692. if (BABYLON.SimplificationQueue) {
  16693. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16694. }
  16695. //collision coordinator initialization. For now legacy per default.
  16696. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16697. // Uniform Buffer
  16698. this._createUbo();
  16699. // Default Image processing definition.
  16700. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16701. }
  16702. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16703. /** The fog is deactivated */
  16704. get: function () {
  16705. return Scene._FOGMODE_NONE;
  16706. },
  16707. enumerable: true,
  16708. configurable: true
  16709. });
  16710. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16711. /** The fog density is following an exponential function */
  16712. get: function () {
  16713. return Scene._FOGMODE_EXP;
  16714. },
  16715. enumerable: true,
  16716. configurable: true
  16717. });
  16718. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16719. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16720. get: function () {
  16721. return Scene._FOGMODE_EXP2;
  16722. },
  16723. enumerable: true,
  16724. configurable: true
  16725. });
  16726. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16727. /** The fog density is following a linear function. */
  16728. get: function () {
  16729. return Scene._FOGMODE_LINEAR;
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16735. /**
  16736. * Texture used in all pbr material as the reflection texture.
  16737. * As in the majority of the scene they are the same (exception for multi room and so on),
  16738. * this is easier to reference from here than from all the materials.
  16739. */
  16740. get: function () {
  16741. return this._environmentTexture;
  16742. },
  16743. /**
  16744. * Texture used in all pbr material as the reflection texture.
  16745. * As in the majority of the scene they are the same (exception for multi room and so on),
  16746. * this is easier to set here than in all the materials.
  16747. */
  16748. set: function (value) {
  16749. this._environmentTexture = value;
  16750. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16751. },
  16752. enumerable: true,
  16753. configurable: true
  16754. });
  16755. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16756. /**
  16757. * Default image processing configuration used either in the rendering
  16758. * Forward main pass or through the imageProcessingPostProcess if present.
  16759. * As in the majority of the scene they are the same (exception for multi camera),
  16760. * this is easier to reference from here than from all the materials and post process.
  16761. *
  16762. * No setter as we it is a shared configuration, you can set the values instead.
  16763. */
  16764. get: function () {
  16765. return this._imageProcessingConfiguration;
  16766. },
  16767. enumerable: true,
  16768. configurable: true
  16769. });
  16770. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16771. get: function () {
  16772. return this._forcePointsCloud;
  16773. },
  16774. set: function (value) {
  16775. if (this._forcePointsCloud === value) {
  16776. return;
  16777. }
  16778. this._forcePointsCloud = value;
  16779. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16780. },
  16781. enumerable: true,
  16782. configurable: true
  16783. });
  16784. Object.defineProperty(Scene.prototype, "onDispose", {
  16785. /** A function to be executed when this scene is disposed. */
  16786. set: function (callback) {
  16787. if (this._onDisposeObserver) {
  16788. this.onDisposeObservable.remove(this._onDisposeObserver);
  16789. }
  16790. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16791. },
  16792. enumerable: true,
  16793. configurable: true
  16794. });
  16795. Object.defineProperty(Scene.prototype, "beforeRender", {
  16796. /** A function to be executed before rendering this scene */
  16797. set: function (callback) {
  16798. if (this._onBeforeRenderObserver) {
  16799. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16800. }
  16801. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16802. },
  16803. enumerable: true,
  16804. configurable: true
  16805. });
  16806. Object.defineProperty(Scene.prototype, "afterRender", {
  16807. /** A function to be executed after rendering this scene */
  16808. set: function (callback) {
  16809. if (this._onAfterRenderObserver) {
  16810. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16811. }
  16812. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16813. },
  16814. enumerable: true,
  16815. configurable: true
  16816. });
  16817. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16818. set: function (callback) {
  16819. if (this._onBeforeCameraRenderObserver) {
  16820. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16821. }
  16822. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16823. },
  16824. enumerable: true,
  16825. configurable: true
  16826. });
  16827. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16828. set: function (callback) {
  16829. if (this._onAfterCameraRenderObserver) {
  16830. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16831. }
  16832. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16833. },
  16834. enumerable: true,
  16835. configurable: true
  16836. });
  16837. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16838. get: function () {
  16839. if (!this._gamepadManager) {
  16840. this._gamepadManager = new BABYLON.GamepadManager();
  16841. }
  16842. return this._gamepadManager;
  16843. },
  16844. enumerable: true,
  16845. configurable: true
  16846. });
  16847. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16848. get: function () {
  16849. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16855. get: function () {
  16856. return this._useRightHandedSystem;
  16857. },
  16858. set: function (value) {
  16859. if (this._useRightHandedSystem === value) {
  16860. return;
  16861. }
  16862. this._useRightHandedSystem = value;
  16863. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. Scene.prototype.setStepId = function (newStepId) {
  16869. this._currentStepId = newStepId;
  16870. };
  16871. ;
  16872. Scene.prototype.getStepId = function () {
  16873. return this._currentStepId;
  16874. };
  16875. ;
  16876. Scene.prototype.getInternalStep = function () {
  16877. return this._currentInternalStep;
  16878. };
  16879. ;
  16880. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16881. get: function () {
  16882. return this._fogEnabled;
  16883. },
  16884. /**
  16885. * is fog enabled on this scene.
  16886. */
  16887. set: function (value) {
  16888. if (this._fogEnabled === value) {
  16889. return;
  16890. }
  16891. this._fogEnabled = value;
  16892. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16893. },
  16894. enumerable: true,
  16895. configurable: true
  16896. });
  16897. Object.defineProperty(Scene.prototype, "fogMode", {
  16898. get: function () {
  16899. return this._fogMode;
  16900. },
  16901. set: function (value) {
  16902. if (this._fogMode === value) {
  16903. return;
  16904. }
  16905. this._fogMode = value;
  16906. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16907. },
  16908. enumerable: true,
  16909. configurable: true
  16910. });
  16911. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16912. get: function () {
  16913. return this._shadowsEnabled;
  16914. },
  16915. set: function (value) {
  16916. if (this._shadowsEnabled === value) {
  16917. return;
  16918. }
  16919. this._shadowsEnabled = value;
  16920. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16921. },
  16922. enumerable: true,
  16923. configurable: true
  16924. });
  16925. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16926. get: function () {
  16927. return this._lightsEnabled;
  16928. },
  16929. set: function (value) {
  16930. if (this._lightsEnabled === value) {
  16931. return;
  16932. }
  16933. this._lightsEnabled = value;
  16934. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16935. },
  16936. enumerable: true,
  16937. configurable: true
  16938. });
  16939. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16940. /** The default material used on meshes when no material is affected */
  16941. get: function () {
  16942. if (!this._defaultMaterial) {
  16943. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16944. }
  16945. return this._defaultMaterial;
  16946. },
  16947. /** The default material used on meshes when no material is affected */
  16948. set: function (value) {
  16949. this._defaultMaterial = value;
  16950. },
  16951. enumerable: true,
  16952. configurable: true
  16953. });
  16954. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16955. get: function () {
  16956. return this._texturesEnabled;
  16957. },
  16958. set: function (value) {
  16959. if (this._texturesEnabled === value) {
  16960. return;
  16961. }
  16962. this._texturesEnabled = value;
  16963. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16964. },
  16965. enumerable: true,
  16966. configurable: true
  16967. });
  16968. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16969. get: function () {
  16970. return this._skeletonsEnabled;
  16971. },
  16972. set: function (value) {
  16973. if (this._skeletonsEnabled === value) {
  16974. return;
  16975. }
  16976. this._skeletonsEnabled = value;
  16977. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16978. },
  16979. enumerable: true,
  16980. configurable: true
  16981. });
  16982. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16983. get: function () {
  16984. if (!this._postProcessRenderPipelineManager) {
  16985. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16986. }
  16987. return this._postProcessRenderPipelineManager;
  16988. },
  16989. enumerable: true,
  16990. configurable: true
  16991. });
  16992. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16993. get: function () {
  16994. return this._frustumPlanes;
  16995. },
  16996. enumerable: true,
  16997. configurable: true
  16998. });
  16999. Object.defineProperty(Scene.prototype, "debugLayer", {
  17000. // Properties
  17001. get: function () {
  17002. if (!this._debugLayer) {
  17003. this._debugLayer = new BABYLON.DebugLayer(this);
  17004. }
  17005. return this._debugLayer;
  17006. },
  17007. enumerable: true,
  17008. configurable: true
  17009. });
  17010. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17011. get: function () {
  17012. return this._workerCollisions;
  17013. },
  17014. set: function (enabled) {
  17015. if (!BABYLON.CollisionCoordinatorLegacy) {
  17016. return;
  17017. }
  17018. enabled = (enabled && !!Worker);
  17019. this._workerCollisions = enabled;
  17020. if (this.collisionCoordinator) {
  17021. this.collisionCoordinator.destroy();
  17022. }
  17023. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17024. this.collisionCoordinator.init(this);
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17030. get: function () {
  17031. return this._selectionOctree;
  17032. },
  17033. enumerable: true,
  17034. configurable: true
  17035. });
  17036. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17037. /**
  17038. * The mesh that is currently under the pointer.
  17039. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17040. */
  17041. get: function () {
  17042. return this._pointerOverMesh;
  17043. },
  17044. enumerable: true,
  17045. configurable: true
  17046. });
  17047. Object.defineProperty(Scene.prototype, "pointerX", {
  17048. /**
  17049. * Current on-screen X position of the pointer
  17050. * @return {number} X position of the pointer
  17051. */
  17052. get: function () {
  17053. return this._pointerX;
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Object.defineProperty(Scene.prototype, "pointerY", {
  17059. /**
  17060. * Current on-screen Y position of the pointer
  17061. * @return {number} Y position of the pointer
  17062. */
  17063. get: function () {
  17064. return this._pointerY;
  17065. },
  17066. enumerable: true,
  17067. configurable: true
  17068. });
  17069. Scene.prototype.getCachedMaterial = function () {
  17070. return this._cachedMaterial;
  17071. };
  17072. Scene.prototype.getCachedEffect = function () {
  17073. return this._cachedEffect;
  17074. };
  17075. Scene.prototype.getCachedVisibility = function () {
  17076. return this._cachedVisibility;
  17077. };
  17078. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17079. if (visibility === void 0) { visibility = 1; }
  17080. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17081. };
  17082. Scene.prototype.getBoundingBoxRenderer = function () {
  17083. if (!this._boundingBoxRenderer) {
  17084. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17085. }
  17086. return this._boundingBoxRenderer;
  17087. };
  17088. Scene.prototype.getOutlineRenderer = function () {
  17089. return this._outlineRenderer;
  17090. };
  17091. Scene.prototype.getEngine = function () {
  17092. return this._engine;
  17093. };
  17094. Scene.prototype.getTotalVertices = function () {
  17095. return this._totalVertices.current;
  17096. };
  17097. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17098. get: function () {
  17099. return this._totalVertices;
  17100. },
  17101. enumerable: true,
  17102. configurable: true
  17103. });
  17104. Scene.prototype.getActiveIndices = function () {
  17105. return this._activeIndices.current;
  17106. };
  17107. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17108. get: function () {
  17109. return this._activeIndices;
  17110. },
  17111. enumerable: true,
  17112. configurable: true
  17113. });
  17114. Scene.prototype.getActiveParticles = function () {
  17115. return this._activeParticles.current;
  17116. };
  17117. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17118. get: function () {
  17119. return this._activeParticles;
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. Scene.prototype.getActiveBones = function () {
  17125. return this._activeBones.current;
  17126. };
  17127. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17128. get: function () {
  17129. return this._activeBones;
  17130. },
  17131. enumerable: true,
  17132. configurable: true
  17133. });
  17134. // Stats
  17135. Scene.prototype.getLastFrameDuration = function () {
  17136. return this._lastFrameDuration.current;
  17137. };
  17138. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17139. get: function () {
  17140. return this._lastFrameDuration;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17146. return this._evaluateActiveMeshesDuration.current;
  17147. };
  17148. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17149. get: function () {
  17150. return this._evaluateActiveMeshesDuration;
  17151. },
  17152. enumerable: true,
  17153. configurable: true
  17154. });
  17155. Scene.prototype.getActiveMeshes = function () {
  17156. return this._activeMeshes;
  17157. };
  17158. Scene.prototype.getRenderTargetsDuration = function () {
  17159. return this._renderTargetsDuration.current;
  17160. };
  17161. Scene.prototype.getRenderDuration = function () {
  17162. return this._renderDuration.current;
  17163. };
  17164. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17165. get: function () {
  17166. return this._renderDuration;
  17167. },
  17168. enumerable: true,
  17169. configurable: true
  17170. });
  17171. Scene.prototype.getParticlesDuration = function () {
  17172. return this._particlesDuration.current;
  17173. };
  17174. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17175. get: function () {
  17176. return this._particlesDuration;
  17177. },
  17178. enumerable: true,
  17179. configurable: true
  17180. });
  17181. Scene.prototype.getSpritesDuration = function () {
  17182. return this._spritesDuration.current;
  17183. };
  17184. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17185. get: function () {
  17186. return this._spritesDuration;
  17187. },
  17188. enumerable: true,
  17189. configurable: true
  17190. });
  17191. Scene.prototype.getAnimationRatio = function () {
  17192. return this._animationRatio;
  17193. };
  17194. Scene.prototype.getRenderId = function () {
  17195. return this._renderId;
  17196. };
  17197. Scene.prototype.incrementRenderId = function () {
  17198. this._renderId++;
  17199. };
  17200. Scene.prototype._updatePointerPosition = function (evt) {
  17201. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17202. this._pointerX = evt.clientX - canvasRect.left;
  17203. this._pointerY = evt.clientY - canvasRect.top;
  17204. this._unTranslatedPointerX = this._pointerX;
  17205. this._unTranslatedPointerY = this._pointerY;
  17206. };
  17207. Scene.prototype._createUbo = function () {
  17208. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17209. this._sceneUbo.addUniform("viewProjection", 16);
  17210. this._sceneUbo.addUniform("view", 16);
  17211. };
  17212. // Pointers handling
  17213. /**
  17214. * Use this method to simulate a pointer move on a mesh
  17215. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17216. */
  17217. Scene.prototype.simulatePointerMove = function (pickResult) {
  17218. var evt = new PointerEvent("pointermove");
  17219. return this._processPointerMove(pickResult, evt);
  17220. };
  17221. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17222. var canvas = this._engine.getRenderingCanvas();
  17223. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17224. this.setPointerOverSprite(null);
  17225. this.setPointerOverMesh(pickResult.pickedMesh);
  17226. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17227. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17228. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17229. }
  17230. else {
  17231. canvas.style.cursor = this.hoverCursor;
  17232. }
  17233. }
  17234. else {
  17235. canvas.style.cursor = this.defaultCursor;
  17236. }
  17237. }
  17238. else {
  17239. this.setPointerOverMesh(null);
  17240. // Sprites
  17241. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17242. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17243. this.setPointerOverSprite(pickResult.pickedSprite);
  17244. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17245. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17246. }
  17247. else {
  17248. canvas.style.cursor = this.hoverCursor;
  17249. }
  17250. }
  17251. else {
  17252. this.setPointerOverSprite(null);
  17253. // Restore pointer
  17254. canvas.style.cursor = this.defaultCursor;
  17255. }
  17256. }
  17257. if (this.onPointerMove) {
  17258. this.onPointerMove(evt, pickResult);
  17259. }
  17260. if (this.onPointerObservable.hasObservers()) {
  17261. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17262. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17263. this.onPointerObservable.notifyObservers(pi, type);
  17264. }
  17265. return this;
  17266. };
  17267. /**
  17268. * Use this method to simulate a pointer down on a mesh
  17269. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17270. */
  17271. Scene.prototype.simulatePointerDown = function (pickResult) {
  17272. var evt = new PointerEvent("pointerdown");
  17273. return this._processPointerDown(pickResult, evt);
  17274. };
  17275. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17276. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17277. this._pickedDownMesh = pickResult.pickedMesh;
  17278. var actionManager = pickResult.pickedMesh.actionManager;
  17279. if (actionManager) {
  17280. if (actionManager.hasPickTriggers) {
  17281. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17282. switch (evt.button) {
  17283. case 0:
  17284. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17285. break;
  17286. case 1:
  17287. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17288. break;
  17289. case 2:
  17290. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17291. break;
  17292. }
  17293. }
  17294. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17295. window.setTimeout((function () {
  17296. var _this = this;
  17297. 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);
  17298. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17299. if (this._isButtonPressed &&
  17300. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17301. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17302. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17303. this._startingPointerTime = 0;
  17304. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17305. }
  17306. }
  17307. }).bind(this), Scene.LongPressDelay);
  17308. }
  17309. }
  17310. }
  17311. if (this.onPointerDown) {
  17312. this.onPointerDown(evt, pickResult);
  17313. }
  17314. if (this.onPointerObservable.hasObservers()) {
  17315. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17316. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17317. this.onPointerObservable.notifyObservers(pi, type);
  17318. }
  17319. return this;
  17320. };
  17321. /**
  17322. * Use this method to simulate a pointer up on a mesh
  17323. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17324. */
  17325. Scene.prototype.simulatePointerUp = function (pickResult) {
  17326. var evt = new PointerEvent("pointerup");
  17327. var clickInfo = new ClickInfo();
  17328. clickInfo.singleClick = true;
  17329. return this._processPointerUp(pickResult, evt, clickInfo);
  17330. };
  17331. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17332. if (pickResult && pickResult && pickResult.pickedMesh) {
  17333. this._pickedUpMesh = pickResult.pickedMesh;
  17334. if (this._pickedDownMesh === this._pickedUpMesh) {
  17335. if (this.onPointerPick) {
  17336. this.onPointerPick(evt, pickResult);
  17337. }
  17338. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17339. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17340. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17341. this.onPointerObservable.notifyObservers(pi, type);
  17342. }
  17343. }
  17344. if (pickResult.pickedMesh.actionManager) {
  17345. if (clickInfo.ignore) {
  17346. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17347. }
  17348. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17349. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17350. }
  17351. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17352. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17353. }
  17354. }
  17355. }
  17356. if (this._pickedDownMesh &&
  17357. this._pickedDownMesh.actionManager &&
  17358. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17359. this._pickedDownMesh !== this._pickedUpMesh) {
  17360. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17361. }
  17362. if (this.onPointerUp) {
  17363. this.onPointerUp(evt, pickResult);
  17364. }
  17365. if (this.onPointerObservable.hasObservers()) {
  17366. if (!clickInfo.ignore) {
  17367. if (!clickInfo.hasSwiped) {
  17368. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17369. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17370. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17371. this.onPointerObservable.notifyObservers(pi, type);
  17372. }
  17373. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17374. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17375. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17376. this.onPointerObservable.notifyObservers(pi, type);
  17377. }
  17378. }
  17379. }
  17380. else {
  17381. var type = BABYLON.PointerEventTypes.POINTERUP;
  17382. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17383. this.onPointerObservable.notifyObservers(pi, type);
  17384. }
  17385. }
  17386. return this;
  17387. };
  17388. /**
  17389. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17390. * @param attachUp defines if you want to attach events to pointerup
  17391. * @param attachDown defines if you want to attach events to pointerdown
  17392. * @param attachMove defines if you want to attach events to pointermove
  17393. */
  17394. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17395. var _this = this;
  17396. if (attachUp === void 0) { attachUp = true; }
  17397. if (attachDown === void 0) { attachDown = true; }
  17398. if (attachMove === void 0) { attachMove = true; }
  17399. this._initActionManager = function (act, clickInfo) {
  17400. if (!_this._meshPickProceed) {
  17401. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17402. _this._currentPickResult = pickResult;
  17403. if (pickResult) {
  17404. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17405. }
  17406. _this._meshPickProceed = true;
  17407. }
  17408. return act;
  17409. };
  17410. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17411. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17412. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17413. btn !== _this._previousButtonPressed) {
  17414. _this._doubleClickOccured = false;
  17415. clickInfo.singleClick = true;
  17416. clickInfo.ignore = false;
  17417. cb(clickInfo, _this._currentPickResult);
  17418. }
  17419. };
  17420. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17421. var clickInfo = new ClickInfo();
  17422. _this._currentPickResult = null;
  17423. var act;
  17424. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17425. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17426. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17427. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17428. act = _this._initActionManager(act, clickInfo);
  17429. if (act)
  17430. checkPicking = act.hasPickTriggers;
  17431. }
  17432. if (checkPicking) {
  17433. var btn = evt.button;
  17434. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17435. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17436. if (!clickInfo.hasSwiped) {
  17437. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17438. if (!checkSingleClickImmediately) {
  17439. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17440. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17441. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17442. act = _this._initActionManager(act, clickInfo);
  17443. if (act)
  17444. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17445. }
  17446. }
  17447. if (checkSingleClickImmediately) {
  17448. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17449. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17450. btn !== _this._previousButtonPressed) {
  17451. clickInfo.singleClick = true;
  17452. cb(clickInfo, _this._currentPickResult);
  17453. }
  17454. }
  17455. else {
  17456. // wait that no double click has been raised during the double click delay
  17457. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17458. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17459. }
  17460. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17461. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17462. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17463. act = _this._initActionManager(act, clickInfo);
  17464. if (act)
  17465. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17466. }
  17467. if (checkDoubleClick) {
  17468. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17469. if (btn === _this._previousButtonPressed &&
  17470. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17471. !_this._doubleClickOccured) {
  17472. // pointer has not moved for 2 clicks, it's a double click
  17473. if (!clickInfo.hasSwiped &&
  17474. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17475. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17476. _this._previousStartingPointerTime = 0;
  17477. _this._doubleClickOccured = true;
  17478. clickInfo.doubleClick = true;
  17479. clickInfo.ignore = false;
  17480. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17481. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17482. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17483. cb(clickInfo, _this._currentPickResult);
  17484. }
  17485. else {
  17486. _this._doubleClickOccured = false;
  17487. _this._previousStartingPointerTime = _this._startingPointerTime;
  17488. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17489. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17490. _this._previousButtonPressed = btn;
  17491. _this._previousHasSwiped = clickInfo.hasSwiped;
  17492. if (Scene.ExclusiveDoubleClickMode) {
  17493. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17494. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17495. }
  17496. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17497. cb(clickInfo, _this._previousPickResult);
  17498. }
  17499. else {
  17500. cb(clickInfo, _this._currentPickResult);
  17501. }
  17502. }
  17503. }
  17504. else {
  17505. _this._doubleClickOccured = false;
  17506. _this._previousStartingPointerTime = _this._startingPointerTime;
  17507. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17508. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17509. _this._previousButtonPressed = btn;
  17510. _this._previousHasSwiped = clickInfo.hasSwiped;
  17511. }
  17512. }
  17513. }
  17514. }
  17515. clickInfo.ignore = true;
  17516. cb(clickInfo, _this._currentPickResult);
  17517. };
  17518. this._spritePredicate = function (sprite) {
  17519. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17520. };
  17521. this._onPointerMove = function (evt) {
  17522. _this._updatePointerPosition(evt);
  17523. // PreObservable support
  17524. if (_this.onPrePointerObservable.hasObservers()) {
  17525. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17526. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17527. _this.onPrePointerObservable.notifyObservers(pi, type);
  17528. if (pi.skipOnPointerObservable) {
  17529. return;
  17530. }
  17531. }
  17532. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17533. return;
  17534. }
  17535. if (!_this.pointerMovePredicate) {
  17536. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17537. }
  17538. // Meshes
  17539. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17540. _this._processPointerMove(pickResult, evt);
  17541. };
  17542. this._onPointerDown = function (evt) {
  17543. _this._isButtonPressed = true;
  17544. _this._pickedDownMesh = null;
  17545. _this._meshPickProceed = false;
  17546. _this._updatePointerPosition(evt);
  17547. // PreObservable support
  17548. if (_this.onPrePointerObservable.hasObservers()) {
  17549. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17550. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17551. _this.onPrePointerObservable.notifyObservers(pi, type);
  17552. if (pi.skipOnPointerObservable) {
  17553. return;
  17554. }
  17555. }
  17556. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17557. return;
  17558. }
  17559. _this._startingPointerPosition.x = _this._pointerX;
  17560. _this._startingPointerPosition.y = _this._pointerY;
  17561. _this._startingPointerTime = new Date().getTime();
  17562. if (!_this.pointerDownPredicate) {
  17563. _this.pointerDownPredicate = function (mesh) {
  17564. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17565. };
  17566. }
  17567. // Meshes
  17568. _this._pickedDownMesh = null;
  17569. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17570. _this._processPointerDown(pickResult, evt);
  17571. // Sprites
  17572. _this._pickedDownSprite = null;
  17573. if (_this.spriteManagers.length > 0) {
  17574. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17575. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17576. if (pickResult.pickedSprite.actionManager) {
  17577. _this._pickedDownSprite = pickResult.pickedSprite;
  17578. switch (evt.button) {
  17579. case 0:
  17580. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17581. break;
  17582. case 1:
  17583. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17584. break;
  17585. case 2:
  17586. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17587. break;
  17588. }
  17589. if (pickResult.pickedSprite.actionManager) {
  17590. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17591. }
  17592. }
  17593. }
  17594. }
  17595. };
  17596. this._onPointerUp = function (evt) {
  17597. _this._isButtonPressed = false;
  17598. _this._pickedUpMesh = null;
  17599. _this._meshPickProceed = false;
  17600. _this._updatePointerPosition(evt);
  17601. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17602. // PreObservable support
  17603. if (this.onPrePointerObservable.hasObservers()) {
  17604. if (!clickInfo.ignore) {
  17605. if (!clickInfo.hasSwiped) {
  17606. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17607. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17608. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17609. this.onPrePointerObservable.notifyObservers(pi, type);
  17610. if (pi.skipOnPointerObservable) {
  17611. return;
  17612. }
  17613. }
  17614. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17615. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17616. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17617. this.onPrePointerObservable.notifyObservers(pi, type);
  17618. if (pi.skipOnPointerObservable) {
  17619. return;
  17620. }
  17621. }
  17622. }
  17623. }
  17624. else {
  17625. var type = BABYLON.PointerEventTypes.POINTERUP;
  17626. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17627. this.onPrePointerObservable.notifyObservers(pi, type);
  17628. if (pi.skipOnPointerObservable) {
  17629. return;
  17630. }
  17631. }
  17632. }
  17633. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17634. return;
  17635. }
  17636. if (!this.pointerUpPredicate) {
  17637. this.pointerUpPredicate = function (mesh) {
  17638. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17639. };
  17640. }
  17641. // Meshes
  17642. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17643. this._initActionManager(null, clickInfo);
  17644. }
  17645. if (!pickResult) {
  17646. pickResult = this._currentPickResult;
  17647. }
  17648. // Sprites
  17649. if (this.spriteManagers.length > 0) {
  17650. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17651. if (pickResult.hit && pickResult.pickedSprite) {
  17652. if (pickResult.pickedSprite.actionManager) {
  17653. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17654. if (pickResult.pickedSprite.actionManager) {
  17655. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17656. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17657. }
  17658. }
  17659. }
  17660. }
  17661. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17662. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17663. }
  17664. }
  17665. this._previousPickResult = this._currentPickResult;
  17666. }).bind(_this));
  17667. };
  17668. this._onKeyDown = function (evt) {
  17669. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17670. if (_this.onPreKeyboardObservable.hasObservers()) {
  17671. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17672. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17673. if (pi.skipOnPointerObservable) {
  17674. return;
  17675. }
  17676. }
  17677. if (_this.onKeyboardObservable.hasObservers()) {
  17678. var pi = new BABYLON.KeyboardInfo(type, evt);
  17679. _this.onKeyboardObservable.notifyObservers(pi, type);
  17680. }
  17681. if (_this.actionManager) {
  17682. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17683. }
  17684. };
  17685. this._onKeyUp = function (evt) {
  17686. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17687. if (_this.onPreKeyboardObservable.hasObservers()) {
  17688. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17689. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17690. if (pi.skipOnPointerObservable) {
  17691. return;
  17692. }
  17693. }
  17694. if (_this.onKeyboardObservable.hasObservers()) {
  17695. var pi = new BABYLON.KeyboardInfo(type, evt);
  17696. _this.onKeyboardObservable.notifyObservers(pi, type);
  17697. }
  17698. if (_this.actionManager) {
  17699. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17700. }
  17701. };
  17702. var engine = this.getEngine();
  17703. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17704. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17705. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17706. });
  17707. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17708. canvas.removeEventListener("keydown", _this._onKeyDown);
  17709. canvas.removeEventListener("keyup", _this._onKeyUp);
  17710. });
  17711. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17712. var canvas = this._engine.getRenderingCanvas();
  17713. if (attachMove) {
  17714. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17715. // Wheel
  17716. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17717. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17718. }
  17719. if (attachDown) {
  17720. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17721. }
  17722. if (attachUp) {
  17723. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17724. }
  17725. canvas.tabIndex = 1;
  17726. };
  17727. Scene.prototype.detachControl = function () {
  17728. var engine = this.getEngine();
  17729. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17730. var canvas = engine.getRenderingCanvas();
  17731. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17732. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17733. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17734. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17735. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17736. // Wheel
  17737. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17738. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17739. // Keyboard
  17740. canvas.removeEventListener("keydown", this._onKeyDown);
  17741. canvas.removeEventListener("keyup", this._onKeyUp);
  17742. // Observables
  17743. this.onKeyboardObservable.clear();
  17744. this.onPreKeyboardObservable.clear();
  17745. this.onPointerObservable.clear();
  17746. this.onPrePointerObservable.clear();
  17747. };
  17748. // Ready
  17749. Scene.prototype.isReady = function () {
  17750. if (this._pendingData.length > 0) {
  17751. return false;
  17752. }
  17753. var index;
  17754. // Geometries
  17755. for (index = 0; index < this._geometries.length; index++) {
  17756. var geometry = this._geometries[index];
  17757. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17758. return false;
  17759. }
  17760. }
  17761. // Meshes
  17762. for (index = 0; index < this.meshes.length; index++) {
  17763. var mesh = this.meshes[index];
  17764. if (!mesh.isEnabled()) {
  17765. continue;
  17766. }
  17767. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17768. continue;
  17769. }
  17770. if (!mesh.isReady()) {
  17771. return false;
  17772. }
  17773. var mat = mesh.material;
  17774. if (mat) {
  17775. if (!mat.isReady(mesh)) {
  17776. return false;
  17777. }
  17778. }
  17779. }
  17780. return true;
  17781. };
  17782. Scene.prototype.resetCachedMaterial = function () {
  17783. this._cachedMaterial = null;
  17784. this._cachedEffect = null;
  17785. this._cachedVisibility = null;
  17786. };
  17787. Scene.prototype.registerBeforeRender = function (func) {
  17788. this.onBeforeRenderObservable.add(func);
  17789. };
  17790. Scene.prototype.unregisterBeforeRender = function (func) {
  17791. this.onBeforeRenderObservable.removeCallback(func);
  17792. };
  17793. Scene.prototype.registerAfterRender = function (func) {
  17794. this.onAfterRenderObservable.add(func);
  17795. };
  17796. Scene.prototype.unregisterAfterRender = function (func) {
  17797. this.onAfterRenderObservable.removeCallback(func);
  17798. };
  17799. Scene.prototype._addPendingData = function (data) {
  17800. this._pendingData.push(data);
  17801. };
  17802. Scene.prototype._removePendingData = function (data) {
  17803. var index = this._pendingData.indexOf(data);
  17804. if (index !== -1) {
  17805. this._pendingData.splice(index, 1);
  17806. }
  17807. };
  17808. Scene.prototype.getWaitingItemsCount = function () {
  17809. return this._pendingData.length;
  17810. };
  17811. /**
  17812. * Registers a function to be executed when the scene is ready.
  17813. * @param {Function} func - the function to be executed.
  17814. */
  17815. Scene.prototype.executeWhenReady = function (func) {
  17816. var _this = this;
  17817. this.onReadyObservable.add(func);
  17818. if (this._executeWhenReadyTimeoutId !== -1) {
  17819. return;
  17820. }
  17821. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17822. _this._checkIsReady();
  17823. }, 150);
  17824. };
  17825. Scene.prototype._checkIsReady = function () {
  17826. var _this = this;
  17827. if (this.isReady()) {
  17828. this.onReadyObservable.notifyObservers(this);
  17829. this.onReadyObservable.clear();
  17830. this._executeWhenReadyTimeoutId = -1;
  17831. return;
  17832. }
  17833. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17834. _this._checkIsReady();
  17835. }, 150);
  17836. };
  17837. // Animations
  17838. /**
  17839. * Will start the animation sequence of a given target
  17840. * @param target - the target
  17841. * @param {number} from - from which frame should animation start
  17842. * @param {number} to - till which frame should animation run.
  17843. * @param {boolean} [loop] - should the animation loop
  17844. * @param {number} [speedRatio] - the speed in which to run the animation
  17845. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17846. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17847. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17848. * See BABYLON.Animatable
  17849. */
  17850. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17851. if (speedRatio === void 0) { speedRatio = 1.0; }
  17852. if (from > to && speedRatio > 0) {
  17853. speedRatio *= -1;
  17854. }
  17855. this.stopAnimation(target);
  17856. if (!animatable) {
  17857. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17858. }
  17859. // Local animations
  17860. if (target.animations) {
  17861. animatable.appendAnimations(target, target.animations);
  17862. }
  17863. // Children animations
  17864. if (target.getAnimatables) {
  17865. var animatables = target.getAnimatables();
  17866. for (var index = 0; index < animatables.length; index++) {
  17867. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17868. }
  17869. }
  17870. animatable.reset();
  17871. return animatable;
  17872. };
  17873. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17874. if (speedRatio === undefined) {
  17875. speedRatio = 1.0;
  17876. }
  17877. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17878. return animatable;
  17879. };
  17880. Scene.prototype.getAnimatableByTarget = function (target) {
  17881. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17882. if (this._activeAnimatables[index].target === target) {
  17883. return this._activeAnimatables[index];
  17884. }
  17885. }
  17886. return null;
  17887. };
  17888. Object.defineProperty(Scene.prototype, "Animatables", {
  17889. get: function () {
  17890. return this._activeAnimatables;
  17891. },
  17892. enumerable: true,
  17893. configurable: true
  17894. });
  17895. /**
  17896. * Will stop the animation of the given target
  17897. * @param target - the target
  17898. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17899. * @see beginAnimation
  17900. */
  17901. Scene.prototype.stopAnimation = function (target, animationName) {
  17902. var animatable = this.getAnimatableByTarget(target);
  17903. if (animatable) {
  17904. animatable.stop(animationName);
  17905. }
  17906. };
  17907. Scene.prototype._animate = function () {
  17908. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17909. return;
  17910. }
  17911. // Getting time
  17912. var now = BABYLON.Tools.Now;
  17913. if (!this._animationTimeLast) {
  17914. if (this._pendingData.length > 0) {
  17915. return;
  17916. }
  17917. this._animationTimeLast = now;
  17918. }
  17919. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17920. this._animationTime += deltaTime;
  17921. this._animationTimeLast = now;
  17922. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17923. this._activeAnimatables[index]._animate(this._animationTime);
  17924. }
  17925. };
  17926. // Matrix
  17927. Scene.prototype.getViewMatrix = function () {
  17928. return this._viewMatrix;
  17929. };
  17930. Scene.prototype.getProjectionMatrix = function () {
  17931. return this._projectionMatrix;
  17932. };
  17933. Scene.prototype.getTransformMatrix = function () {
  17934. return this._transformMatrix;
  17935. };
  17936. Scene.prototype.setTransformMatrix = function (view, projection) {
  17937. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17938. return;
  17939. }
  17940. this._viewUpdateFlag = view.updateFlag;
  17941. this._projectionUpdateFlag = projection.updateFlag;
  17942. this._viewMatrix = view;
  17943. this._projectionMatrix = projection;
  17944. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17945. // Update frustum
  17946. if (!this._frustumPlanes) {
  17947. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17948. }
  17949. else {
  17950. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17951. }
  17952. if (this._sceneUbo.useUbo) {
  17953. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17954. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17955. this._sceneUbo.update();
  17956. }
  17957. };
  17958. Scene.prototype.getSceneUniformBuffer = function () {
  17959. return this._sceneUbo;
  17960. };
  17961. // Methods
  17962. Scene.prototype.getUniqueId = function () {
  17963. var result = this._uniqueIdCounter;
  17964. this._uniqueIdCounter++;
  17965. return result;
  17966. };
  17967. Scene.prototype.addMesh = function (newMesh) {
  17968. newMesh.uniqueId = this.getUniqueId();
  17969. var position = this.meshes.push(newMesh);
  17970. //notify the collision coordinator
  17971. if (this.collisionCoordinator) {
  17972. this.collisionCoordinator.onMeshAdded(newMesh);
  17973. }
  17974. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17975. };
  17976. Scene.prototype.removeMesh = function (toRemove) {
  17977. var index = this.meshes.indexOf(toRemove);
  17978. if (index !== -1) {
  17979. // Remove from the scene if mesh found
  17980. this.meshes.splice(index, 1);
  17981. }
  17982. //notify the collision coordinator
  17983. if (this.collisionCoordinator) {
  17984. this.collisionCoordinator.onMeshRemoved(toRemove);
  17985. }
  17986. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17987. return index;
  17988. };
  17989. Scene.prototype.removeSkeleton = function (toRemove) {
  17990. var index = this.skeletons.indexOf(toRemove);
  17991. if (index !== -1) {
  17992. // Remove from the scene if found
  17993. this.skeletons.splice(index, 1);
  17994. }
  17995. return index;
  17996. };
  17997. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17998. var index = this.morphTargetManagers.indexOf(toRemove);
  17999. if (index !== -1) {
  18000. // Remove from the scene if found
  18001. this.morphTargetManagers.splice(index, 1);
  18002. }
  18003. return index;
  18004. };
  18005. Scene.prototype.removeLight = function (toRemove) {
  18006. var index = this.lights.indexOf(toRemove);
  18007. if (index !== -1) {
  18008. // Remove from the scene if mesh found
  18009. this.lights.splice(index, 1);
  18010. this.sortLightsByPriority();
  18011. }
  18012. this.onLightRemovedObservable.notifyObservers(toRemove);
  18013. return index;
  18014. };
  18015. Scene.prototype.removeCamera = function (toRemove) {
  18016. var index = this.cameras.indexOf(toRemove);
  18017. if (index !== -1) {
  18018. // Remove from the scene if mesh found
  18019. this.cameras.splice(index, 1);
  18020. }
  18021. // Remove from activeCameras
  18022. var index2 = this.activeCameras.indexOf(toRemove);
  18023. if (index2 !== -1) {
  18024. // Remove from the scene if mesh found
  18025. this.activeCameras.splice(index2, 1);
  18026. }
  18027. // Reset the activeCamera
  18028. if (this.activeCamera === toRemove) {
  18029. if (this.cameras.length > 0) {
  18030. this.activeCamera = this.cameras[0];
  18031. }
  18032. else {
  18033. this.activeCamera = null;
  18034. }
  18035. }
  18036. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18037. return index;
  18038. };
  18039. Scene.prototype.addLight = function (newLight) {
  18040. newLight.uniqueId = this.getUniqueId();
  18041. this.lights.push(newLight);
  18042. this.sortLightsByPriority();
  18043. this.onNewLightAddedObservable.notifyObservers(newLight);
  18044. };
  18045. Scene.prototype.sortLightsByPriority = function () {
  18046. if (this.requireLightSorting) {
  18047. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18048. }
  18049. };
  18050. Scene.prototype.addCamera = function (newCamera) {
  18051. newCamera.uniqueId = this.getUniqueId();
  18052. var position = this.cameras.push(newCamera);
  18053. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18054. };
  18055. /**
  18056. * Switch active camera
  18057. * @param {Camera} newCamera - new active camera
  18058. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18059. */
  18060. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18061. if (attachControl === void 0) { attachControl = true; }
  18062. var canvas = this._engine.getRenderingCanvas();
  18063. this.activeCamera.detachControl(canvas);
  18064. this.activeCamera = newCamera;
  18065. if (attachControl) {
  18066. newCamera.attachControl(canvas);
  18067. }
  18068. };
  18069. /**
  18070. * sets the active camera of the scene using its ID
  18071. * @param {string} id - the camera's ID
  18072. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18073. * @see activeCamera
  18074. */
  18075. Scene.prototype.setActiveCameraByID = function (id) {
  18076. var camera = this.getCameraByID(id);
  18077. if (camera) {
  18078. this.activeCamera = camera;
  18079. return camera;
  18080. }
  18081. return null;
  18082. };
  18083. /**
  18084. * sets the active camera of the scene using its name
  18085. * @param {string} name - the camera's name
  18086. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18087. * @see activeCamera
  18088. */
  18089. Scene.prototype.setActiveCameraByName = function (name) {
  18090. var camera = this.getCameraByName(name);
  18091. if (camera) {
  18092. this.activeCamera = camera;
  18093. return camera;
  18094. }
  18095. return null;
  18096. };
  18097. /**
  18098. * get a material using its id
  18099. * @param {string} the material's ID
  18100. * @return {BABYLON.Material|null} the material or null if none found.
  18101. */
  18102. Scene.prototype.getMaterialByID = function (id) {
  18103. for (var index = 0; index < this.materials.length; index++) {
  18104. if (this.materials[index].id === id) {
  18105. return this.materials[index];
  18106. }
  18107. }
  18108. return null;
  18109. };
  18110. /**
  18111. * get a material using its name
  18112. * @param {string} the material's name
  18113. * @return {BABYLON.Material|null} the material or null if none found.
  18114. */
  18115. Scene.prototype.getMaterialByName = function (name) {
  18116. for (var index = 0; index < this.materials.length; index++) {
  18117. if (this.materials[index].name === name) {
  18118. return this.materials[index];
  18119. }
  18120. }
  18121. return null;
  18122. };
  18123. Scene.prototype.getLensFlareSystemByName = function (name) {
  18124. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18125. if (this.lensFlareSystems[index].name === name) {
  18126. return this.lensFlareSystems[index];
  18127. }
  18128. }
  18129. return null;
  18130. };
  18131. Scene.prototype.getLensFlareSystemByID = function (id) {
  18132. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18133. if (this.lensFlareSystems[index].id === id) {
  18134. return this.lensFlareSystems[index];
  18135. }
  18136. }
  18137. return null;
  18138. };
  18139. Scene.prototype.getCameraByID = function (id) {
  18140. for (var index = 0; index < this.cameras.length; index++) {
  18141. if (this.cameras[index].id === id) {
  18142. return this.cameras[index];
  18143. }
  18144. }
  18145. return null;
  18146. };
  18147. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18148. for (var index = 0; index < this.cameras.length; index++) {
  18149. if (this.cameras[index].uniqueId === uniqueId) {
  18150. return this.cameras[index];
  18151. }
  18152. }
  18153. return null;
  18154. };
  18155. /**
  18156. * get a camera using its name
  18157. * @param {string} the camera's name
  18158. * @return {BABYLON.Camera|null} the camera or null if none found.
  18159. */
  18160. Scene.prototype.getCameraByName = function (name) {
  18161. for (var index = 0; index < this.cameras.length; index++) {
  18162. if (this.cameras[index].name === name) {
  18163. return this.cameras[index];
  18164. }
  18165. }
  18166. return null;
  18167. };
  18168. /**
  18169. * get a bone using its id
  18170. * @param {string} the bone's id
  18171. * @return {BABYLON.Bone|null} the bone or null if not found
  18172. */
  18173. Scene.prototype.getBoneByID = function (id) {
  18174. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18175. var skeleton = this.skeletons[skeletonIndex];
  18176. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18177. if (skeleton.bones[boneIndex].id === id) {
  18178. return skeleton.bones[boneIndex];
  18179. }
  18180. }
  18181. }
  18182. return null;
  18183. };
  18184. /**
  18185. * get a bone using its id
  18186. * @param {string} the bone's name
  18187. * @return {BABYLON.Bone|null} the bone or null if not found
  18188. */
  18189. Scene.prototype.getBoneByName = function (name) {
  18190. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18191. var skeleton = this.skeletons[skeletonIndex];
  18192. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18193. if (skeleton.bones[boneIndex].name === name) {
  18194. return skeleton.bones[boneIndex];
  18195. }
  18196. }
  18197. }
  18198. return null;
  18199. };
  18200. /**
  18201. * get a light node using its name
  18202. * @param {string} the light's name
  18203. * @return {BABYLON.Light|null} the light or null if none found.
  18204. */
  18205. Scene.prototype.getLightByName = function (name) {
  18206. for (var index = 0; index < this.lights.length; index++) {
  18207. if (this.lights[index].name === name) {
  18208. return this.lights[index];
  18209. }
  18210. }
  18211. return null;
  18212. };
  18213. /**
  18214. * get a light node using its ID
  18215. * @param {string} the light's id
  18216. * @return {BABYLON.Light|null} the light or null if none found.
  18217. */
  18218. Scene.prototype.getLightByID = function (id) {
  18219. for (var index = 0; index < this.lights.length; index++) {
  18220. if (this.lights[index].id === id) {
  18221. return this.lights[index];
  18222. }
  18223. }
  18224. return null;
  18225. };
  18226. /**
  18227. * get a light node using its scene-generated unique ID
  18228. * @param {number} the light's unique id
  18229. * @return {BABYLON.Light|null} the light or null if none found.
  18230. */
  18231. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18232. for (var index = 0; index < this.lights.length; index++) {
  18233. if (this.lights[index].uniqueId === uniqueId) {
  18234. return this.lights[index];
  18235. }
  18236. }
  18237. return null;
  18238. };
  18239. /**
  18240. * get a particle system by id
  18241. * @param id {number} the particle system id
  18242. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18243. */
  18244. Scene.prototype.getParticleSystemByID = function (id) {
  18245. for (var index = 0; index < this.particleSystems.length; index++) {
  18246. if (this.particleSystems[index].id === id) {
  18247. return this.particleSystems[index];
  18248. }
  18249. }
  18250. return null;
  18251. };
  18252. /**
  18253. * get a geometry using its ID
  18254. * @param {string} the geometry's id
  18255. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18256. */
  18257. Scene.prototype.getGeometryByID = function (id) {
  18258. for (var index = 0; index < this._geometries.length; index++) {
  18259. if (this._geometries[index].id === id) {
  18260. return this._geometries[index];
  18261. }
  18262. }
  18263. return null;
  18264. };
  18265. /**
  18266. * add a new geometry to this scene.
  18267. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18268. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18269. * @return {boolean} was the geometry added or not
  18270. */
  18271. Scene.prototype.pushGeometry = function (geometry, force) {
  18272. if (!force && this.getGeometryByID(geometry.id)) {
  18273. return false;
  18274. }
  18275. this._geometries.push(geometry);
  18276. //notify the collision coordinator
  18277. if (this.collisionCoordinator) {
  18278. this.collisionCoordinator.onGeometryAdded(geometry);
  18279. }
  18280. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18281. return true;
  18282. };
  18283. /**
  18284. * Removes an existing geometry
  18285. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18286. * @return {boolean} was the geometry removed or not
  18287. */
  18288. Scene.prototype.removeGeometry = function (geometry) {
  18289. var index = this._geometries.indexOf(geometry);
  18290. if (index > -1) {
  18291. this._geometries.splice(index, 1);
  18292. //notify the collision coordinator
  18293. if (this.collisionCoordinator) {
  18294. this.collisionCoordinator.onGeometryDeleted(geometry);
  18295. }
  18296. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18297. return true;
  18298. }
  18299. return false;
  18300. };
  18301. Scene.prototype.getGeometries = function () {
  18302. return this._geometries;
  18303. };
  18304. /**
  18305. * Get the first added mesh found of a given ID
  18306. * @param {string} id - the id to search for
  18307. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18308. */
  18309. Scene.prototype.getMeshByID = function (id) {
  18310. for (var index = 0; index < this.meshes.length; index++) {
  18311. if (this.meshes[index].id === id) {
  18312. return this.meshes[index];
  18313. }
  18314. }
  18315. return null;
  18316. };
  18317. Scene.prototype.getMeshesByID = function (id) {
  18318. return this.meshes.filter(function (m) {
  18319. return m.id === id;
  18320. });
  18321. };
  18322. /**
  18323. * Get a mesh with its auto-generated unique id
  18324. * @param {number} uniqueId - the unique id to search for
  18325. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18326. */
  18327. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18328. for (var index = 0; index < this.meshes.length; index++) {
  18329. if (this.meshes[index].uniqueId === uniqueId) {
  18330. return this.meshes[index];
  18331. }
  18332. }
  18333. return null;
  18334. };
  18335. /**
  18336. * Get a the last added mesh found of a given ID
  18337. * @param {string} id - the id to search for
  18338. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18339. */
  18340. Scene.prototype.getLastMeshByID = function (id) {
  18341. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18342. if (this.meshes[index].id === id) {
  18343. return this.meshes[index];
  18344. }
  18345. }
  18346. return null;
  18347. };
  18348. /**
  18349. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18350. * @param {string} id - the id to search for
  18351. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18352. */
  18353. Scene.prototype.getLastEntryByID = function (id) {
  18354. var index;
  18355. for (index = this.meshes.length - 1; index >= 0; index--) {
  18356. if (this.meshes[index].id === id) {
  18357. return this.meshes[index];
  18358. }
  18359. }
  18360. for (index = this.cameras.length - 1; index >= 0; index--) {
  18361. if (this.cameras[index].id === id) {
  18362. return this.cameras[index];
  18363. }
  18364. }
  18365. for (index = this.lights.length - 1; index >= 0; index--) {
  18366. if (this.lights[index].id === id) {
  18367. return this.lights[index];
  18368. }
  18369. }
  18370. return null;
  18371. };
  18372. Scene.prototype.getNodeByID = function (id) {
  18373. var mesh = this.getMeshByID(id);
  18374. if (mesh) {
  18375. return mesh;
  18376. }
  18377. var light = this.getLightByID(id);
  18378. if (light) {
  18379. return light;
  18380. }
  18381. var camera = this.getCameraByID(id);
  18382. if (camera) {
  18383. return camera;
  18384. }
  18385. var bone = this.getBoneByID(id);
  18386. return bone;
  18387. };
  18388. Scene.prototype.getNodeByName = function (name) {
  18389. var mesh = this.getMeshByName(name);
  18390. if (mesh) {
  18391. return mesh;
  18392. }
  18393. var light = this.getLightByName(name);
  18394. if (light) {
  18395. return light;
  18396. }
  18397. var camera = this.getCameraByName(name);
  18398. if (camera) {
  18399. return camera;
  18400. }
  18401. var bone = this.getBoneByName(name);
  18402. return bone;
  18403. };
  18404. Scene.prototype.getMeshByName = function (name) {
  18405. for (var index = 0; index < this.meshes.length; index++) {
  18406. if (this.meshes[index].name === name) {
  18407. return this.meshes[index];
  18408. }
  18409. }
  18410. return null;
  18411. };
  18412. Scene.prototype.getSoundByName = function (name) {
  18413. var index;
  18414. if (BABYLON.AudioEngine) {
  18415. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18416. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18417. return this.mainSoundTrack.soundCollection[index];
  18418. }
  18419. }
  18420. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18421. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18422. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18423. return this.soundTracks[sdIndex].soundCollection[index];
  18424. }
  18425. }
  18426. }
  18427. }
  18428. return null;
  18429. };
  18430. Scene.prototype.getLastSkeletonByID = function (id) {
  18431. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18432. if (this.skeletons[index].id === id) {
  18433. return this.skeletons[index];
  18434. }
  18435. }
  18436. return null;
  18437. };
  18438. Scene.prototype.getSkeletonById = function (id) {
  18439. for (var index = 0; index < this.skeletons.length; index++) {
  18440. if (this.skeletons[index].id === id) {
  18441. return this.skeletons[index];
  18442. }
  18443. }
  18444. return null;
  18445. };
  18446. Scene.prototype.getSkeletonByName = function (name) {
  18447. for (var index = 0; index < this.skeletons.length; index++) {
  18448. if (this.skeletons[index].name === name) {
  18449. return this.skeletons[index];
  18450. }
  18451. }
  18452. return null;
  18453. };
  18454. Scene.prototype.getMorphTargetManagerById = function (id) {
  18455. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18456. if (this.morphTargetManagers[index].uniqueId === id) {
  18457. return this.morphTargetManagers[index];
  18458. }
  18459. }
  18460. return null;
  18461. };
  18462. Scene.prototype.isActiveMesh = function (mesh) {
  18463. return (this._activeMeshes.indexOf(mesh) !== -1);
  18464. };
  18465. /**
  18466. * Return a the first highlight layer of the scene with a given name.
  18467. * @param name The name of the highlight layer to look for.
  18468. * @return The highlight layer if found otherwise null.
  18469. */
  18470. Scene.prototype.getHighlightLayerByName = function (name) {
  18471. for (var index = 0; index < this.highlightLayers.length; index++) {
  18472. if (this.highlightLayers[index].name === name) {
  18473. return this.highlightLayers[index];
  18474. }
  18475. }
  18476. return null;
  18477. };
  18478. Object.defineProperty(Scene.prototype, "uid", {
  18479. /**
  18480. * Return a unique id as a string which can serve as an identifier for the scene
  18481. */
  18482. get: function () {
  18483. if (!this._uid) {
  18484. this._uid = BABYLON.Tools.RandomId();
  18485. }
  18486. return this._uid;
  18487. },
  18488. enumerable: true,
  18489. configurable: true
  18490. });
  18491. /**
  18492. * Add an externaly attached data from its key.
  18493. * This method call will fail and return false, if such key already exists.
  18494. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18495. * @param key the unique key that identifies the data
  18496. * @param data the data object to associate to the key for this Engine instance
  18497. * @return true if no such key were already present and the data was added successfully, false otherwise
  18498. */
  18499. Scene.prototype.addExternalData = function (key, data) {
  18500. if (!this._externalData) {
  18501. this._externalData = new BABYLON.StringDictionary();
  18502. }
  18503. return this._externalData.add(key, data);
  18504. };
  18505. /**
  18506. * Get an externaly attached data from its key
  18507. * @param key the unique key that identifies the data
  18508. * @return the associated data, if present (can be null), or undefined if not present
  18509. */
  18510. Scene.prototype.getExternalData = function (key) {
  18511. if (!this._externalData) {
  18512. return null;
  18513. }
  18514. return this._externalData.get(key);
  18515. };
  18516. /**
  18517. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18518. * @param key the unique key that identifies the data
  18519. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18520. * @return the associated data, can be null if the factory returned null.
  18521. */
  18522. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18523. if (!this._externalData) {
  18524. this._externalData = new BABYLON.StringDictionary();
  18525. }
  18526. return this._externalData.getOrAddWithFactory(key, factory);
  18527. };
  18528. /**
  18529. * Remove an externaly attached data from the Engine instance
  18530. * @param key the unique key that identifies the data
  18531. * @return true if the data was successfully removed, false if it doesn't exist
  18532. */
  18533. Scene.prototype.removeExternalData = function (key) {
  18534. return this._externalData.remove(key);
  18535. };
  18536. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18537. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18538. var material = subMesh.getMaterial();
  18539. if (mesh.showSubMeshesBoundingBox) {
  18540. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18541. }
  18542. if (material) {
  18543. // Render targets
  18544. if (material.getRenderTargetTextures) {
  18545. if (this._processedMaterials.indexOf(material) === -1) {
  18546. this._processedMaterials.push(material);
  18547. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18548. }
  18549. }
  18550. // Dispatch
  18551. this._activeIndices.addCount(subMesh.indexCount, false);
  18552. this._renderingManager.dispatch(subMesh);
  18553. }
  18554. }
  18555. };
  18556. Scene.prototype._isInIntermediateRendering = function () {
  18557. return this._intermediateRendering;
  18558. };
  18559. Scene.prototype._evaluateActiveMeshes = function () {
  18560. this.activeCamera._activeMeshes.reset();
  18561. this._activeMeshes.reset();
  18562. this._renderingManager.reset();
  18563. this._processedMaterials.reset();
  18564. this._activeParticleSystems.reset();
  18565. this._activeSkeletons.reset();
  18566. this._softwareSkinnedMeshes.reset();
  18567. if (this._boundingBoxRenderer) {
  18568. this._boundingBoxRenderer.reset();
  18569. }
  18570. // Meshes
  18571. var meshes;
  18572. var len;
  18573. if (this._selectionOctree) {
  18574. var selection = this._selectionOctree.select(this._frustumPlanes);
  18575. meshes = selection.data;
  18576. len = selection.length;
  18577. }
  18578. else {
  18579. len = this.meshes.length;
  18580. meshes = this.meshes;
  18581. }
  18582. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18583. var mesh = meshes[meshIndex];
  18584. if (mesh.isBlocked) {
  18585. continue;
  18586. }
  18587. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18588. if (!mesh.isReady() || !mesh.isEnabled()) {
  18589. continue;
  18590. }
  18591. mesh.computeWorldMatrix();
  18592. // Intersections
  18593. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18594. this._meshesForIntersections.pushNoDuplicate(mesh);
  18595. }
  18596. // Switch to current LOD
  18597. var meshLOD = mesh.getLOD(this.activeCamera);
  18598. if (!meshLOD) {
  18599. continue;
  18600. }
  18601. mesh._preActivate();
  18602. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18603. this._activeMeshes.push(mesh);
  18604. this.activeCamera._activeMeshes.push(mesh);
  18605. mesh._activate(this._renderId);
  18606. if (meshLOD !== mesh) {
  18607. meshLOD._activate(this._renderId);
  18608. }
  18609. this._activeMesh(mesh, meshLOD);
  18610. }
  18611. }
  18612. // Particle systems
  18613. this._particlesDuration.beginMonitoring();
  18614. var beforeParticlesDate = BABYLON.Tools.Now;
  18615. if (this.particlesEnabled) {
  18616. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18617. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18618. var particleSystem = this.particleSystems[particleIndex];
  18619. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18620. continue;
  18621. }
  18622. var emitter = particleSystem.emitter;
  18623. if (!emitter.position || emitter.isEnabled()) {
  18624. this._activeParticleSystems.push(particleSystem);
  18625. particleSystem.animate();
  18626. this._renderingManager.dispatchParticles(particleSystem);
  18627. }
  18628. }
  18629. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18630. }
  18631. this._particlesDuration.endMonitoring(false);
  18632. };
  18633. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18634. if (mesh.skeleton && this.skeletonsEnabled) {
  18635. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18636. mesh.skeleton.prepare();
  18637. }
  18638. if (!mesh.computeBonesUsingShaders) {
  18639. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18640. }
  18641. }
  18642. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18643. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18644. }
  18645. if (mesh && mesh.subMeshes) {
  18646. // Submeshes Octrees
  18647. var len;
  18648. var subMeshes;
  18649. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18650. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18651. len = intersections.length;
  18652. subMeshes = intersections.data;
  18653. }
  18654. else {
  18655. subMeshes = mesh.subMeshes;
  18656. len = subMeshes.length;
  18657. }
  18658. for (var subIndex = 0; subIndex < len; subIndex++) {
  18659. var subMesh = subMeshes[subIndex];
  18660. this._evaluateSubMesh(subMesh, mesh);
  18661. }
  18662. }
  18663. };
  18664. Scene.prototype.updateTransformMatrix = function (force) {
  18665. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18666. };
  18667. Scene.prototype._renderForCamera = function (camera) {
  18668. var engine = this._engine;
  18669. var startTime = BABYLON.Tools.Now;
  18670. this.activeCamera = camera;
  18671. if (!this.activeCamera)
  18672. throw new Error("Active camera not set");
  18673. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18674. // Viewport
  18675. engine.setViewport(this.activeCamera.viewport);
  18676. // Camera
  18677. this.resetCachedMaterial();
  18678. this._renderId++;
  18679. this.updateTransformMatrix();
  18680. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18681. // Meshes
  18682. this._evaluateActiveMeshesDuration.beginMonitoring();
  18683. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18684. this._evaluateActiveMeshes();
  18685. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18686. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18687. // Software skinning
  18688. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18689. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18690. mesh.applySkeleton(mesh.skeleton);
  18691. }
  18692. // Render targets
  18693. this._renderTargetsDuration.beginMonitoring();
  18694. var needsRestoreFrameBuffer = false;
  18695. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18696. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18697. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18698. }
  18699. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18700. this._intermediateRendering = true;
  18701. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18702. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18703. var renderTarget = this._renderTargets.data[renderIndex];
  18704. if (renderTarget._shouldRender()) {
  18705. this._renderId++;
  18706. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18707. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18708. }
  18709. }
  18710. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18711. this._intermediateRendering = false;
  18712. this._renderId++;
  18713. needsRestoreFrameBuffer = true; // Restore back buffer
  18714. }
  18715. // Render HighlightLayer Texture
  18716. var stencilState = this._engine.getStencilBuffer();
  18717. var renderhighlights = false;
  18718. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18719. this._intermediateRendering = true;
  18720. for (var i = 0; i < this.highlightLayers.length; i++) {
  18721. var highlightLayer = this.highlightLayers[i];
  18722. if (highlightLayer.shouldRender() &&
  18723. (!highlightLayer.camera ||
  18724. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18725. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18726. renderhighlights = true;
  18727. var renderTarget = highlightLayer._mainTexture;
  18728. if (renderTarget._shouldRender()) {
  18729. this._renderId++;
  18730. renderTarget.render(false, false);
  18731. needsRestoreFrameBuffer = true;
  18732. }
  18733. }
  18734. }
  18735. this._intermediateRendering = false;
  18736. this._renderId++;
  18737. }
  18738. if (needsRestoreFrameBuffer) {
  18739. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18740. }
  18741. this._renderTargetsDuration.endMonitoring(false);
  18742. // Prepare Frame
  18743. this.postProcessManager._prepareFrame();
  18744. this._renderDuration.beginMonitoring();
  18745. // Backgrounds
  18746. var layerIndex;
  18747. var layer;
  18748. if (this.layers.length) {
  18749. engine.setDepthBuffer(false);
  18750. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18751. layer = this.layers[layerIndex];
  18752. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18753. layer.render();
  18754. }
  18755. }
  18756. engine.setDepthBuffer(true);
  18757. }
  18758. // Render
  18759. BABYLON.Tools.StartPerformanceCounter("Main render");
  18760. // Activate HighlightLayer stencil
  18761. if (renderhighlights) {
  18762. this._engine.setStencilBuffer(true);
  18763. }
  18764. this._renderingManager.render(null, null, true, true);
  18765. // Restore HighlightLayer stencil
  18766. if (renderhighlights) {
  18767. this._engine.setStencilBuffer(stencilState);
  18768. }
  18769. BABYLON.Tools.EndPerformanceCounter("Main render");
  18770. // Bounding boxes
  18771. if (this._boundingBoxRenderer) {
  18772. this._boundingBoxRenderer.render();
  18773. }
  18774. // Lens flares
  18775. if (this.lensFlaresEnabled) {
  18776. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18777. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18778. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18779. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18780. lensFlareSystem.render();
  18781. }
  18782. }
  18783. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18784. }
  18785. // Foregrounds
  18786. if (this.layers.length) {
  18787. engine.setDepthBuffer(false);
  18788. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18789. layer = this.layers[layerIndex];
  18790. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18791. layer.render();
  18792. }
  18793. }
  18794. engine.setDepthBuffer(true);
  18795. }
  18796. // Highlight Layer
  18797. if (renderhighlights) {
  18798. engine.setDepthBuffer(false);
  18799. for (var i = 0; i < this.highlightLayers.length; i++) {
  18800. if (this.highlightLayers[i].shouldRender()) {
  18801. this.highlightLayers[i].render();
  18802. }
  18803. }
  18804. engine.setDepthBuffer(true);
  18805. }
  18806. this._renderDuration.endMonitoring(false);
  18807. // Finalize frame
  18808. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18809. // Update camera
  18810. this.activeCamera._updateFromScene();
  18811. // Reset some special arrays
  18812. this._renderTargets.reset();
  18813. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18814. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18815. };
  18816. Scene.prototype._processSubCameras = function (camera) {
  18817. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18818. this._renderForCamera(camera);
  18819. return;
  18820. }
  18821. // rig cameras
  18822. for (var index = 0; index < camera._rigCameras.length; index++) {
  18823. this._renderForCamera(camera._rigCameras[index]);
  18824. }
  18825. this.activeCamera = camera;
  18826. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18827. // Update camera
  18828. this.activeCamera._updateFromScene();
  18829. };
  18830. Scene.prototype._checkIntersections = function () {
  18831. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18832. var sourceMesh = this._meshesForIntersections.data[index];
  18833. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18834. var action = sourceMesh.actionManager.actions[actionIndex];
  18835. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18836. var parameters = action.getTriggerParameter();
  18837. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18838. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18839. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18840. if (areIntersecting && currentIntersectionInProgress === -1) {
  18841. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18842. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18843. sourceMesh._intersectionsInProgress.push(otherMesh);
  18844. }
  18845. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18846. sourceMesh._intersectionsInProgress.push(otherMesh);
  18847. }
  18848. }
  18849. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18850. //They intersected, and now they don't.
  18851. //is this trigger an exit trigger? execute an event.
  18852. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18853. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18854. }
  18855. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18856. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18857. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18858. }
  18859. }
  18860. }
  18861. }
  18862. }
  18863. };
  18864. Scene.prototype.render = function () {
  18865. if (this.isDisposed) {
  18866. return;
  18867. }
  18868. this._lastFrameDuration.beginMonitoring();
  18869. this._particlesDuration.fetchNewFrame();
  18870. this._spritesDuration.fetchNewFrame();
  18871. this._activeParticles.fetchNewFrame();
  18872. this._renderDuration.fetchNewFrame();
  18873. this._renderTargetsDuration.fetchNewFrame();
  18874. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18875. this._totalVertices.fetchNewFrame();
  18876. this._activeIndices.fetchNewFrame();
  18877. this._activeBones.fetchNewFrame();
  18878. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18879. this._meshesForIntersections.reset();
  18880. this.resetCachedMaterial();
  18881. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18882. // Actions
  18883. if (this.actionManager) {
  18884. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18885. }
  18886. //Simplification Queue
  18887. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18888. this.simplificationQueue.executeNext();
  18889. }
  18890. if (this._engine.isDeterministicLockStep()) {
  18891. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18892. var defaultTimeStep = (60.0 / 1000.0);
  18893. if (this._physicsEngine) {
  18894. defaultTimeStep = this._physicsEngine.getTimeStep();
  18895. }
  18896. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18897. this._timeAccumulator += deltaTime;
  18898. // compute the amount of fixed steps we should have taken since the last step
  18899. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18900. internalSteps = Math.min(internalSteps, maxSubSteps);
  18901. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18902. this.onBeforeStepObservable.notifyObservers(this);
  18903. // Animations
  18904. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18905. this._animate();
  18906. // Physics
  18907. if (this._physicsEngine) {
  18908. BABYLON.Tools.StartPerformanceCounter("Physics");
  18909. this._physicsEngine._step(defaultTimeStep);
  18910. BABYLON.Tools.EndPerformanceCounter("Physics");
  18911. }
  18912. this._timeAccumulator -= defaultTimeStep;
  18913. this.onAfterStepObservable.notifyObservers(this);
  18914. this._currentStepId++;
  18915. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18916. // Q: can this be optimized by putting some code in the afterStep callback?
  18917. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18918. // would return incorrect positions for internal stepIds (non-rendered steps)
  18919. this._evaluateActiveMeshes();
  18920. }
  18921. }
  18922. }
  18923. else {
  18924. // Animations
  18925. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18926. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18927. this._animate();
  18928. // Physics
  18929. if (this._physicsEngine) {
  18930. BABYLON.Tools.StartPerformanceCounter("Physics");
  18931. this._physicsEngine._step(deltaTime / 1000.0);
  18932. BABYLON.Tools.EndPerformanceCounter("Physics");
  18933. }
  18934. }
  18935. // Before render
  18936. this.onBeforeRenderObservable.notifyObservers(this);
  18937. // Customs render targets
  18938. this._renderTargetsDuration.beginMonitoring();
  18939. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18940. var engine = this.getEngine();
  18941. var currentActiveCamera = this.activeCamera;
  18942. if (this.renderTargetsEnabled) {
  18943. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18944. this._intermediateRendering = true;
  18945. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18946. var renderTarget = this.customRenderTargets[customIndex];
  18947. if (renderTarget._shouldRender()) {
  18948. this._renderId++;
  18949. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18950. if (!this.activeCamera)
  18951. throw new Error("Active camera not set");
  18952. // Viewport
  18953. engine.setViewport(this.activeCamera.viewport);
  18954. // Camera
  18955. this.updateTransformMatrix();
  18956. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18957. }
  18958. }
  18959. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18960. this._intermediateRendering = false;
  18961. this._renderId++;
  18962. }
  18963. // Restore back buffer
  18964. if (this.customRenderTargets.length > 0) {
  18965. engine.restoreDefaultFramebuffer();
  18966. }
  18967. this._renderTargetsDuration.endMonitoring();
  18968. this.activeCamera = currentActiveCamera;
  18969. // Procedural textures
  18970. if (this.proceduralTexturesEnabled) {
  18971. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18972. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18973. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18974. if (proceduralTexture._shouldRender()) {
  18975. proceduralTexture.render();
  18976. }
  18977. }
  18978. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18979. }
  18980. // Clear
  18981. if (this.autoClearDepthAndStencil || this.autoClear) {
  18982. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18983. }
  18984. // Shadows
  18985. if (this.shadowsEnabled) {
  18986. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18987. var light = this.lights[lightIndex];
  18988. var shadowGenerator = light.getShadowGenerator();
  18989. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18990. var shadowMap = shadowGenerator.getShadowMap();
  18991. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18992. this._renderTargets.push(shadowMap);
  18993. }
  18994. }
  18995. }
  18996. }
  18997. // Depth renderer
  18998. if (this._depthRenderer) {
  18999. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19000. }
  19001. // Geometry renderer
  19002. if (this._geometryBufferRenderer) {
  19003. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19004. }
  19005. // RenderPipeline
  19006. if (this._postProcessRenderPipelineManager) {
  19007. this._postProcessRenderPipelineManager.update();
  19008. }
  19009. // Multi-cameras?
  19010. if (this.activeCameras.length > 0) {
  19011. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19012. if (cameraIndex > 0) {
  19013. this._engine.clear(null, false, true, true);
  19014. }
  19015. this._processSubCameras(this.activeCameras[cameraIndex]);
  19016. }
  19017. }
  19018. else {
  19019. if (!this.activeCamera) {
  19020. throw new Error("No camera defined");
  19021. }
  19022. this._processSubCameras(this.activeCamera);
  19023. }
  19024. // Intersection checks
  19025. this._checkIntersections();
  19026. // Update the audio listener attached to the camera
  19027. if (BABYLON.AudioEngine) {
  19028. this._updateAudioParameters();
  19029. }
  19030. // After render
  19031. if (this.afterRender) {
  19032. this.afterRender();
  19033. }
  19034. this.onAfterRenderObservable.notifyObservers(this);
  19035. // Cleaning
  19036. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19037. this._toBeDisposed.data[index].dispose();
  19038. this._toBeDisposed[index] = null;
  19039. }
  19040. this._toBeDisposed.reset();
  19041. if (this.dumpNextRenderTargets) {
  19042. this.dumpNextRenderTargets = false;
  19043. }
  19044. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19045. this._lastFrameDuration.endMonitoring();
  19046. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19047. this._totalLightsCounter.addCount(this.lights.length, true);
  19048. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19049. this._totalTexturesCounter.addCount(this.textures.length, true);
  19050. this._activeBones.addCount(0, true);
  19051. this._activeIndices.addCount(0, true);
  19052. this._activeParticles.addCount(0, true);
  19053. };
  19054. Scene.prototype._updateAudioParameters = function () {
  19055. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19056. return;
  19057. }
  19058. var listeningCamera;
  19059. var audioEngine = BABYLON.Engine.audioEngine;
  19060. if (this.activeCameras.length > 0) {
  19061. listeningCamera = this.activeCameras[0];
  19062. }
  19063. else {
  19064. listeningCamera = this.activeCamera;
  19065. }
  19066. if (listeningCamera && audioEngine.canUseWebAudio) {
  19067. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19068. // for VR cameras
  19069. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19070. listeningCamera = listeningCamera.rigCameras[0];
  19071. }
  19072. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19073. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19074. cameraDirection.normalize();
  19075. // To avoid some errors on GearVR
  19076. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19077. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19078. }
  19079. var i;
  19080. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19081. var sound = this.mainSoundTrack.soundCollection[i];
  19082. if (sound.useCustomAttenuation) {
  19083. sound.updateDistanceFromListener();
  19084. }
  19085. }
  19086. for (i = 0; i < this.soundTracks.length; i++) {
  19087. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19088. sound = this.soundTracks[i].soundCollection[j];
  19089. if (sound.useCustomAttenuation) {
  19090. sound.updateDistanceFromListener();
  19091. }
  19092. }
  19093. }
  19094. }
  19095. };
  19096. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19097. // Audio
  19098. get: function () {
  19099. return this._audioEnabled;
  19100. },
  19101. set: function (value) {
  19102. this._audioEnabled = value;
  19103. if (BABYLON.AudioEngine) {
  19104. if (this._audioEnabled) {
  19105. this._enableAudio();
  19106. }
  19107. else {
  19108. this._disableAudio();
  19109. }
  19110. }
  19111. },
  19112. enumerable: true,
  19113. configurable: true
  19114. });
  19115. Scene.prototype._disableAudio = function () {
  19116. var i;
  19117. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19118. this.mainSoundTrack.soundCollection[i].pause();
  19119. }
  19120. for (i = 0; i < this.soundTracks.length; i++) {
  19121. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19122. this.soundTracks[i].soundCollection[j].pause();
  19123. }
  19124. }
  19125. };
  19126. Scene.prototype._enableAudio = function () {
  19127. var i;
  19128. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19129. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19130. this.mainSoundTrack.soundCollection[i].play();
  19131. }
  19132. }
  19133. for (i = 0; i < this.soundTracks.length; i++) {
  19134. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19135. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19136. this.soundTracks[i].soundCollection[j].play();
  19137. }
  19138. }
  19139. }
  19140. };
  19141. Object.defineProperty(Scene.prototype, "headphone", {
  19142. get: function () {
  19143. return this._headphone;
  19144. },
  19145. set: function (value) {
  19146. this._headphone = value;
  19147. if (BABYLON.AudioEngine) {
  19148. if (this._headphone) {
  19149. this._switchAudioModeForHeadphones();
  19150. }
  19151. else {
  19152. this._switchAudioModeForNormalSpeakers();
  19153. }
  19154. }
  19155. },
  19156. enumerable: true,
  19157. configurable: true
  19158. });
  19159. Scene.prototype._switchAudioModeForHeadphones = function () {
  19160. this.mainSoundTrack.switchPanningModelToHRTF();
  19161. for (var i = 0; i < this.soundTracks.length; i++) {
  19162. this.soundTracks[i].switchPanningModelToHRTF();
  19163. }
  19164. };
  19165. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19166. this.mainSoundTrack.switchPanningModelToEqualPower();
  19167. for (var i = 0; i < this.soundTracks.length; i++) {
  19168. this.soundTracks[i].switchPanningModelToEqualPower();
  19169. }
  19170. };
  19171. Scene.prototype.enableDepthRenderer = function () {
  19172. if (this._depthRenderer) {
  19173. return this._depthRenderer;
  19174. }
  19175. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19176. return this._depthRenderer;
  19177. };
  19178. Scene.prototype.disableDepthRenderer = function () {
  19179. if (!this._depthRenderer) {
  19180. return;
  19181. }
  19182. this._depthRenderer.dispose();
  19183. this._depthRenderer = null;
  19184. };
  19185. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19186. if (ratio === void 0) { ratio = 1; }
  19187. if (this._geometryBufferRenderer) {
  19188. return this._geometryBufferRenderer;
  19189. }
  19190. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19191. if (!this._geometryBufferRenderer.isSupported) {
  19192. this._geometryBufferRenderer = null;
  19193. }
  19194. return this._geometryBufferRenderer;
  19195. };
  19196. Scene.prototype.disableGeometryBufferRenderer = function () {
  19197. if (!this._geometryBufferRenderer) {
  19198. return;
  19199. }
  19200. this._geometryBufferRenderer.dispose();
  19201. this._geometryBufferRenderer = null;
  19202. };
  19203. Scene.prototype.freezeMaterials = function () {
  19204. for (var i = 0; i < this.materials.length; i++) {
  19205. this.materials[i].freeze();
  19206. }
  19207. };
  19208. Scene.prototype.unfreezeMaterials = function () {
  19209. for (var i = 0; i < this.materials.length; i++) {
  19210. this.materials[i].unfreeze();
  19211. }
  19212. };
  19213. Scene.prototype.dispose = function () {
  19214. this.beforeRender = null;
  19215. this.afterRender = null;
  19216. this.skeletons = [];
  19217. this.morphTargetManagers = [];
  19218. this.importedMeshesFiles = new Array();
  19219. this.resetCachedMaterial();
  19220. if (this._depthRenderer) {
  19221. this._depthRenderer.dispose();
  19222. }
  19223. if (this._gamepadManager) {
  19224. this._gamepadManager.dispose();
  19225. this._gamepadManager = null;
  19226. }
  19227. // Smart arrays
  19228. if (this.activeCamera) {
  19229. this.activeCamera._activeMeshes.dispose();
  19230. this.activeCamera = null;
  19231. }
  19232. this._activeMeshes.dispose();
  19233. this._renderingManager.dispose();
  19234. this._processedMaterials.dispose();
  19235. this._activeParticleSystems.dispose();
  19236. this._activeSkeletons.dispose();
  19237. this._softwareSkinnedMeshes.dispose();
  19238. this._renderTargets.dispose();
  19239. if (this._boundingBoxRenderer) {
  19240. this._boundingBoxRenderer.dispose();
  19241. }
  19242. this._meshesForIntersections.dispose();
  19243. this._toBeDisposed.dispose();
  19244. // Debug layer
  19245. if (this._debugLayer) {
  19246. this._debugLayer.hide();
  19247. }
  19248. // Events
  19249. this.onDisposeObservable.notifyObservers(this);
  19250. this.onDisposeObservable.clear();
  19251. this.onBeforeRenderObservable.clear();
  19252. this.onAfterRenderObservable.clear();
  19253. this.detachControl();
  19254. // Release sounds & sounds tracks
  19255. if (BABYLON.AudioEngine) {
  19256. this.disposeSounds();
  19257. }
  19258. // VR Helper
  19259. if (this.VRHelper) {
  19260. this.VRHelper.dispose();
  19261. }
  19262. // Detach cameras
  19263. var canvas = this._engine.getRenderingCanvas();
  19264. var index;
  19265. for (index = 0; index < this.cameras.length; index++) {
  19266. this.cameras[index].detachControl(canvas);
  19267. }
  19268. // Release lights
  19269. while (this.lights.length) {
  19270. this.lights[0].dispose();
  19271. }
  19272. // Release meshes
  19273. while (this.meshes.length) {
  19274. this.meshes[0].dispose(true);
  19275. }
  19276. // Release cameras
  19277. while (this.cameras.length) {
  19278. this.cameras[0].dispose();
  19279. }
  19280. // Release materials
  19281. if (this.defaultMaterial) {
  19282. this.defaultMaterial.dispose();
  19283. }
  19284. while (this.multiMaterials.length) {
  19285. this.multiMaterials[0].dispose();
  19286. }
  19287. while (this.materials.length) {
  19288. this.materials[0].dispose();
  19289. }
  19290. // Release particles
  19291. while (this.particleSystems.length) {
  19292. this.particleSystems[0].dispose();
  19293. }
  19294. // Release sprites
  19295. while (this.spriteManagers.length) {
  19296. this.spriteManagers[0].dispose();
  19297. }
  19298. // Release postProcesses
  19299. while (this.postProcesses.length) {
  19300. this.postProcesses[0].dispose();
  19301. }
  19302. // Release layers
  19303. while (this.layers.length) {
  19304. this.layers[0].dispose();
  19305. }
  19306. while (this.highlightLayers.length) {
  19307. this.highlightLayers[0].dispose();
  19308. }
  19309. // Release textures
  19310. while (this.textures.length) {
  19311. this.textures[0].dispose();
  19312. }
  19313. // Release UBO
  19314. this._sceneUbo.dispose();
  19315. // Post-processes
  19316. this.postProcessManager.dispose();
  19317. if (this._postProcessRenderPipelineManager) {
  19318. this._postProcessRenderPipelineManager.dispose();
  19319. }
  19320. // Physics
  19321. if (this._physicsEngine) {
  19322. this.disablePhysicsEngine();
  19323. }
  19324. // Remove from engine
  19325. index = this._engine.scenes.indexOf(this);
  19326. if (index > -1) {
  19327. this._engine.scenes.splice(index, 1);
  19328. }
  19329. this._engine.wipeCaches();
  19330. this._engine = null;
  19331. this.defaultMaterial = null;
  19332. this.multiMaterials = null;
  19333. this.materials = null;
  19334. };
  19335. Object.defineProperty(Scene.prototype, "isDisposed", {
  19336. get: function () {
  19337. return !this._engine;
  19338. },
  19339. enumerable: true,
  19340. configurable: true
  19341. });
  19342. // Release sounds & sounds tracks
  19343. Scene.prototype.disposeSounds = function () {
  19344. this.mainSoundTrack.dispose();
  19345. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19346. this.soundTracks[scIndex].dispose();
  19347. }
  19348. };
  19349. // Octrees
  19350. Scene.prototype.getWorldExtends = function () {
  19351. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19352. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19353. for (var index = 0; index < this.meshes.length; index++) {
  19354. var mesh = this.meshes[index];
  19355. mesh.computeWorldMatrix(true);
  19356. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19357. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19358. BABYLON.Tools.CheckExtends(minBox, min, max);
  19359. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19360. }
  19361. return {
  19362. min: min,
  19363. max: max
  19364. };
  19365. };
  19366. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19367. if (maxCapacity === void 0) { maxCapacity = 64; }
  19368. if (maxDepth === void 0) { maxDepth = 2; }
  19369. if (!this._selectionOctree) {
  19370. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19371. }
  19372. var worldExtends = this.getWorldExtends();
  19373. // Update octree
  19374. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19375. return this._selectionOctree;
  19376. };
  19377. // Picking
  19378. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19379. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19380. var engine = this._engine;
  19381. if (!camera) {
  19382. if (!this.activeCamera)
  19383. throw new Error("Active camera not set");
  19384. camera = this.activeCamera;
  19385. }
  19386. var cameraViewport = camera.viewport;
  19387. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19388. // Moving coordinates to local viewport world
  19389. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19390. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19391. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19392. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19393. };
  19394. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19395. if (!BABYLON.PickingInfo) {
  19396. return null;
  19397. }
  19398. var engine = this._engine;
  19399. if (!camera) {
  19400. if (!this.activeCamera)
  19401. throw new Error("Active camera not set");
  19402. camera = this.activeCamera;
  19403. }
  19404. var cameraViewport = camera.viewport;
  19405. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19406. var identity = BABYLON.Matrix.Identity();
  19407. // Moving coordinates to local viewport world
  19408. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19409. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19410. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19411. };
  19412. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19413. if (!BABYLON.PickingInfo) {
  19414. return null;
  19415. }
  19416. var pickingInfo = null;
  19417. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19418. var mesh = this.meshes[meshIndex];
  19419. if (predicate) {
  19420. if (!predicate(mesh)) {
  19421. continue;
  19422. }
  19423. }
  19424. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19425. continue;
  19426. }
  19427. var world = mesh.getWorldMatrix();
  19428. var ray = rayFunction(world);
  19429. var result = mesh.intersects(ray, fastCheck);
  19430. if (!result || !result.hit)
  19431. continue;
  19432. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19433. continue;
  19434. pickingInfo = result;
  19435. if (fastCheck) {
  19436. break;
  19437. }
  19438. }
  19439. return pickingInfo || new BABYLON.PickingInfo();
  19440. };
  19441. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19442. if (!BABYLON.PickingInfo) {
  19443. return null;
  19444. }
  19445. var pickingInfos = new Array();
  19446. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19447. var mesh = this.meshes[meshIndex];
  19448. if (predicate) {
  19449. if (!predicate(mesh)) {
  19450. continue;
  19451. }
  19452. }
  19453. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19454. continue;
  19455. }
  19456. var world = mesh.getWorldMatrix();
  19457. var ray = rayFunction(world);
  19458. var result = mesh.intersects(ray, false);
  19459. if (!result || !result.hit)
  19460. continue;
  19461. pickingInfos.push(result);
  19462. }
  19463. return pickingInfos;
  19464. };
  19465. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19466. if (!BABYLON.PickingInfo) {
  19467. return null;
  19468. }
  19469. var pickingInfo = null;
  19470. camera = camera || this.activeCamera;
  19471. if (this.spriteManagers.length > 0) {
  19472. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19473. var spriteManager = this.spriteManagers[spriteIndex];
  19474. if (!spriteManager.isPickable) {
  19475. continue;
  19476. }
  19477. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19478. if (!result || !result.hit)
  19479. continue;
  19480. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19481. continue;
  19482. pickingInfo = result;
  19483. if (fastCheck) {
  19484. break;
  19485. }
  19486. }
  19487. }
  19488. return pickingInfo || new BABYLON.PickingInfo();
  19489. };
  19490. /** Launch a ray to try to pick a mesh in the scene
  19491. * @param x position on screen
  19492. * @param y position on screen
  19493. * @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
  19494. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19495. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19496. */
  19497. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19498. var _this = this;
  19499. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19500. };
  19501. /** Launch a ray to try to pick a sprite in the scene
  19502. * @param x position on screen
  19503. * @param y position on screen
  19504. * @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
  19505. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19506. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19507. */
  19508. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19509. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19510. };
  19511. /** Use the given ray to pick a mesh in the scene
  19512. * @param ray The ray to use to pick meshes
  19513. * @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
  19514. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19515. */
  19516. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19517. var _this = this;
  19518. return this._internalPick(function (world) {
  19519. if (!_this._pickWithRayInverseMatrix) {
  19520. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19521. }
  19522. world.invertToRef(_this._pickWithRayInverseMatrix);
  19523. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19524. }, predicate, fastCheck);
  19525. };
  19526. /**
  19527. * Launch a ray to try to pick a mesh in the scene
  19528. * @param x X position on screen
  19529. * @param y Y position on screen
  19530. * @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
  19531. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19532. */
  19533. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19534. var _this = this;
  19535. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19536. };
  19537. /**
  19538. * Launch a ray to try to pick a mesh in the scene
  19539. * @param ray Ray to use
  19540. * @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
  19541. */
  19542. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19543. var _this = this;
  19544. return this._internalMultiPick(function (world) {
  19545. if (!_this._pickWithRayInverseMatrix) {
  19546. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19547. }
  19548. world.invertToRef(_this._pickWithRayInverseMatrix);
  19549. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19550. }, predicate);
  19551. };
  19552. Scene.prototype.setPointerOverMesh = function (mesh) {
  19553. if (this._pointerOverMesh === mesh) {
  19554. return;
  19555. }
  19556. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19557. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19558. }
  19559. this._pointerOverMesh = mesh;
  19560. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19561. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19562. }
  19563. };
  19564. Scene.prototype.getPointerOverMesh = function () {
  19565. return this._pointerOverMesh;
  19566. };
  19567. Scene.prototype.setPointerOverSprite = function (sprite) {
  19568. if (this._pointerOverSprite === sprite) {
  19569. return;
  19570. }
  19571. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19572. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19573. }
  19574. this._pointerOverSprite = sprite;
  19575. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19576. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19577. }
  19578. };
  19579. Scene.prototype.getPointerOverSprite = function () {
  19580. return this._pointerOverSprite;
  19581. };
  19582. // Physics
  19583. Scene.prototype.getPhysicsEngine = function () {
  19584. return this._physicsEngine;
  19585. };
  19586. /**
  19587. * Enables physics to the current scene
  19588. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19589. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19590. * @return {boolean} was the physics engine initialized
  19591. */
  19592. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19593. if (this._physicsEngine) {
  19594. return true;
  19595. }
  19596. try {
  19597. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19598. return true;
  19599. }
  19600. catch (e) {
  19601. BABYLON.Tools.Error(e.message);
  19602. return false;
  19603. }
  19604. };
  19605. Scene.prototype.disablePhysicsEngine = function () {
  19606. if (!this._physicsEngine) {
  19607. return;
  19608. }
  19609. this._physicsEngine.dispose();
  19610. this._physicsEngine = undefined;
  19611. };
  19612. Scene.prototype.isPhysicsEnabled = function () {
  19613. return this._physicsEngine !== undefined;
  19614. };
  19615. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19616. var mesh = compound.parts[0].mesh;
  19617. mesh.physicsImpostor.dispose();
  19618. mesh.physicsImpostor = null;
  19619. };
  19620. // Misc.
  19621. Scene.prototype._rebuildGeometries = function () {
  19622. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19623. var geometry = _a[_i];
  19624. geometry._rebuild();
  19625. }
  19626. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19627. var mesh = _c[_b];
  19628. mesh._rebuild();
  19629. }
  19630. if (this.postProcessManager) {
  19631. this.postProcessManager._rebuild();
  19632. }
  19633. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19634. var layer = _e[_d];
  19635. layer._rebuild();
  19636. }
  19637. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19638. var highlightLayer = _g[_f];
  19639. highlightLayer._rebuild();
  19640. }
  19641. if (this._boundingBoxRenderer) {
  19642. this._boundingBoxRenderer._rebuild();
  19643. }
  19644. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19645. var system = _j[_h];
  19646. system.rebuild();
  19647. }
  19648. if (this._postProcessRenderPipelineManager) {
  19649. this._postProcessRenderPipelineManager._rebuild();
  19650. }
  19651. };
  19652. Scene.prototype._rebuildTextures = function () {
  19653. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19654. var texture = _a[_i];
  19655. texture._rebuild();
  19656. }
  19657. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19658. };
  19659. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19660. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19661. if (replace === void 0) { replace = false; }
  19662. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19663. // Dispose existing camera or light in replace mode.
  19664. if (replace) {
  19665. if (this.activeCamera) {
  19666. this.activeCamera.dispose();
  19667. this.activeCamera = null;
  19668. }
  19669. if (this.lights) {
  19670. for (var i = 0; i < this.lights.length; i++) {
  19671. this.lights[i].dispose();
  19672. }
  19673. }
  19674. }
  19675. // Light
  19676. if (this.lights.length === 0) {
  19677. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19678. }
  19679. // Camera
  19680. if (!this.activeCamera) {
  19681. var worldExtends = this.getWorldExtends();
  19682. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19683. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19684. var camera;
  19685. var radius = worldSize.length() * 1.5;
  19686. if (createArcRotateCamera) {
  19687. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19688. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19689. arcRotateCamera.wheelPrecision = 100 / radius;
  19690. camera = arcRotateCamera;
  19691. }
  19692. else {
  19693. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19694. freeCamera.setTarget(worldCenter);
  19695. camera = freeCamera;
  19696. }
  19697. camera.minZ = radius * 0.01;
  19698. camera.maxZ = radius * 100;
  19699. camera.speed = radius * 0.2;
  19700. this.activeCamera = camera;
  19701. if (attachCameraControls) {
  19702. camera.attachControl(this.getEngine().getRenderingCanvas());
  19703. }
  19704. }
  19705. };
  19706. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19707. if (pbr === void 0) { pbr = false; }
  19708. if (scale === void 0) { scale = 1000; }
  19709. if (blur === void 0) { blur = 0; }
  19710. if (environmentTexture) {
  19711. this.environmentTexture = environmentTexture;
  19712. }
  19713. if (!this.environmentTexture) {
  19714. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19715. return;
  19716. }
  19717. // Skybox
  19718. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19719. if (pbr) {
  19720. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19721. hdrSkyboxMaterial.backFaceCulling = false;
  19722. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19723. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19724. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19725. hdrSkyboxMaterial.disableLighting = true;
  19726. hdrSkyboxMaterial.twoSidedLighting = true;
  19727. hdrSkybox.infiniteDistance = true;
  19728. hdrSkybox.material = hdrSkyboxMaterial;
  19729. }
  19730. else {
  19731. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19732. skyboxMaterial.backFaceCulling = false;
  19733. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19734. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19735. skyboxMaterial.disableLighting = true;
  19736. hdrSkybox.infiniteDistance = true;
  19737. hdrSkybox.material = skyboxMaterial;
  19738. }
  19739. return hdrSkybox;
  19740. };
  19741. Scene.prototype.createDefaultVRExperience = function () {
  19742. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19743. };
  19744. // Tags
  19745. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19746. if (tagsQuery === undefined) {
  19747. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19748. return list;
  19749. }
  19750. var listByTags = [];
  19751. forEach = forEach || (function (item) { return; });
  19752. for (var i in list) {
  19753. var item = list[i];
  19754. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19755. listByTags.push(item);
  19756. forEach(item);
  19757. }
  19758. }
  19759. return listByTags;
  19760. };
  19761. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19762. return this._getByTags(this.meshes, tagsQuery, forEach);
  19763. };
  19764. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19765. return this._getByTags(this.cameras, tagsQuery, forEach);
  19766. };
  19767. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19768. return this._getByTags(this.lights, tagsQuery, forEach);
  19769. };
  19770. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19771. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19772. };
  19773. /**
  19774. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19775. * This allowed control for front to back rendering or reversly depending of the special needs.
  19776. *
  19777. * @param renderingGroupId The rendering group id corresponding to its index
  19778. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19779. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19780. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19781. */
  19782. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19783. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19784. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19785. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19786. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19787. };
  19788. /**
  19789. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19790. *
  19791. * @param renderingGroupId The rendering group id corresponding to its index
  19792. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19793. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19794. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19795. */
  19796. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19797. if (depth === void 0) { depth = true; }
  19798. if (stencil === void 0) { stencil = true; }
  19799. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19800. };
  19801. /**
  19802. * Will flag all materials as dirty to trigger new shader compilation
  19803. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19804. */
  19805. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19806. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19807. var material = _a[_i];
  19808. if (predicate && !predicate(material)) {
  19809. continue;
  19810. }
  19811. material.markAsDirty(flag);
  19812. }
  19813. };
  19814. // Statics
  19815. Scene._FOGMODE_NONE = 0;
  19816. Scene._FOGMODE_EXP = 1;
  19817. Scene._FOGMODE_EXP2 = 2;
  19818. Scene._FOGMODE_LINEAR = 3;
  19819. Scene.MinDeltaTime = 1.0;
  19820. Scene.MaxDeltaTime = 1000.0;
  19821. /** The distance in pixel that you have to move to prevent some events */
  19822. Scene.DragMovementThreshold = 10; // in pixels
  19823. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19824. Scene.LongPressDelay = 500; // in milliseconds
  19825. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19826. Scene.DoubleClickDelay = 300; // in milliseconds
  19827. /** If you need to check double click without raising a single click at first click, enable this flag */
  19828. Scene.ExclusiveDoubleClickMode = false;
  19829. return Scene;
  19830. }());
  19831. BABYLON.Scene = Scene;
  19832. })(BABYLON || (BABYLON = {}));
  19833. //# sourceMappingURL=babylon.scene.js.map
  19834. var BABYLON;
  19835. (function (BABYLON) {
  19836. var Buffer = (function () {
  19837. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19838. if (engine instanceof BABYLON.Mesh) {
  19839. this._engine = engine.getScene().getEngine();
  19840. }
  19841. else {
  19842. this._engine = engine;
  19843. }
  19844. this._updatable = updatable;
  19845. this._data = data;
  19846. this._strideSize = stride;
  19847. if (!postponeInternalCreation) {
  19848. this.create();
  19849. }
  19850. this._instanced = instanced;
  19851. this._instanceDivisor = instanced ? 1 : 0;
  19852. }
  19853. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19854. // a lot of these parameters are ignored as they are overriden by the buffer
  19855. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19856. };
  19857. // Properties
  19858. Buffer.prototype.isUpdatable = function () {
  19859. return this._updatable;
  19860. };
  19861. Buffer.prototype.getData = function () {
  19862. return this._data;
  19863. };
  19864. Buffer.prototype.getBuffer = function () {
  19865. return this._buffer;
  19866. };
  19867. Buffer.prototype.getStrideSize = function () {
  19868. return this._strideSize;
  19869. };
  19870. Buffer.prototype.getIsInstanced = function () {
  19871. return this._instanced;
  19872. };
  19873. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19874. get: function () {
  19875. return this._instanceDivisor;
  19876. },
  19877. set: function (value) {
  19878. this._instanceDivisor = value;
  19879. if (value == 0) {
  19880. this._instanced = false;
  19881. }
  19882. else {
  19883. this._instanced = true;
  19884. }
  19885. },
  19886. enumerable: true,
  19887. configurable: true
  19888. });
  19889. // Methods
  19890. Buffer.prototype.create = function (data) {
  19891. if (!data && this._buffer) {
  19892. return; // nothing to do
  19893. }
  19894. data = data || this._data;
  19895. if (!this._buffer) {
  19896. if (this._updatable) {
  19897. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19898. this._data = data;
  19899. }
  19900. else {
  19901. this._buffer = this._engine.createVertexBuffer(data);
  19902. }
  19903. }
  19904. else if (this._updatable) {
  19905. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19906. this._data = data;
  19907. }
  19908. };
  19909. Buffer.prototype._rebuild = function () {
  19910. this._buffer = null;
  19911. this.create(this._data);
  19912. };
  19913. Buffer.prototype.update = function (data) {
  19914. this.create(data);
  19915. };
  19916. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19917. if (!this._buffer) {
  19918. return;
  19919. }
  19920. if (this._updatable) {
  19921. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19922. this._data = null;
  19923. }
  19924. };
  19925. Buffer.prototype.dispose = function () {
  19926. if (!this._buffer) {
  19927. return;
  19928. }
  19929. if (this._engine._releaseBuffer(this._buffer)) {
  19930. this._buffer = null;
  19931. }
  19932. };
  19933. return Buffer;
  19934. }());
  19935. BABYLON.Buffer = Buffer;
  19936. })(BABYLON || (BABYLON = {}));
  19937. //# sourceMappingURL=babylon.buffer.js.map
  19938. var BABYLON;
  19939. (function (BABYLON) {
  19940. var VertexBuffer = (function () {
  19941. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19942. if (!stride) {
  19943. // Deduce stride from kind
  19944. switch (kind) {
  19945. case VertexBuffer.PositionKind:
  19946. stride = 3;
  19947. break;
  19948. case VertexBuffer.NormalKind:
  19949. stride = 3;
  19950. break;
  19951. case VertexBuffer.UVKind:
  19952. case VertexBuffer.UV2Kind:
  19953. case VertexBuffer.UV3Kind:
  19954. case VertexBuffer.UV4Kind:
  19955. case VertexBuffer.UV5Kind:
  19956. case VertexBuffer.UV6Kind:
  19957. stride = 2;
  19958. break;
  19959. case VertexBuffer.TangentKind:
  19960. case VertexBuffer.ColorKind:
  19961. stride = 4;
  19962. break;
  19963. case VertexBuffer.MatricesIndicesKind:
  19964. case VertexBuffer.MatricesIndicesExtraKind:
  19965. stride = 4;
  19966. break;
  19967. case VertexBuffer.MatricesWeightsKind:
  19968. case VertexBuffer.MatricesWeightsExtraKind:
  19969. stride = 4;
  19970. break;
  19971. }
  19972. }
  19973. if (data instanceof BABYLON.Buffer) {
  19974. if (!stride) {
  19975. stride = data.getStrideSize();
  19976. }
  19977. this._buffer = data;
  19978. this._ownsBuffer = false;
  19979. }
  19980. else {
  19981. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19982. this._ownsBuffer = true;
  19983. }
  19984. this._stride = stride;
  19985. this._offset = offset ? offset : 0;
  19986. this._size = size ? size : stride;
  19987. this._kind = kind;
  19988. }
  19989. VertexBuffer.prototype._rebuild = function () {
  19990. if (!this._buffer) {
  19991. return;
  19992. }
  19993. this._buffer._rebuild();
  19994. };
  19995. /**
  19996. * Returns the kind of the VertexBuffer (string).
  19997. */
  19998. VertexBuffer.prototype.getKind = function () {
  19999. return this._kind;
  20000. };
  20001. // Properties
  20002. /**
  20003. * Boolean : is the VertexBuffer updatable ?
  20004. */
  20005. VertexBuffer.prototype.isUpdatable = function () {
  20006. return this._buffer.isUpdatable();
  20007. };
  20008. /**
  20009. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20010. */
  20011. VertexBuffer.prototype.getData = function () {
  20012. return this._buffer.getData();
  20013. };
  20014. /**
  20015. * Returns the WebGLBuffer associated to the VertexBuffer.
  20016. */
  20017. VertexBuffer.prototype.getBuffer = function () {
  20018. return this._buffer.getBuffer();
  20019. };
  20020. /**
  20021. * Returns the stride of the VertexBuffer (integer).
  20022. */
  20023. VertexBuffer.prototype.getStrideSize = function () {
  20024. return this._stride;
  20025. };
  20026. /**
  20027. * Returns the offset (integer).
  20028. */
  20029. VertexBuffer.prototype.getOffset = function () {
  20030. return this._offset;
  20031. };
  20032. /**
  20033. * Returns the VertexBuffer total size (integer).
  20034. */
  20035. VertexBuffer.prototype.getSize = function () {
  20036. return this._size;
  20037. };
  20038. /**
  20039. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20040. */
  20041. VertexBuffer.prototype.getIsInstanced = function () {
  20042. return this._buffer.getIsInstanced();
  20043. };
  20044. /**
  20045. * Returns the instancing divisor, zero for non-instanced (integer).
  20046. */
  20047. VertexBuffer.prototype.getInstanceDivisor = function () {
  20048. return this._buffer.instanceDivisor;
  20049. };
  20050. // Methods
  20051. /**
  20052. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20053. * Returns the created WebGLBuffer.
  20054. */
  20055. VertexBuffer.prototype.create = function (data) {
  20056. return this._buffer.create(data);
  20057. };
  20058. /**
  20059. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20060. * Returns the updated WebGLBuffer.
  20061. */
  20062. VertexBuffer.prototype.update = function (data) {
  20063. return this._buffer.update(data);
  20064. };
  20065. /**
  20066. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20067. * Returns the directly updated WebGLBuffer.
  20068. */
  20069. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20070. return this._buffer.updateDirectly(data, offset);
  20071. };
  20072. /**
  20073. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20074. */
  20075. VertexBuffer.prototype.dispose = function () {
  20076. if (this._ownsBuffer) {
  20077. this._buffer.dispose();
  20078. }
  20079. };
  20080. Object.defineProperty(VertexBuffer, "PositionKind", {
  20081. get: function () {
  20082. return VertexBuffer._PositionKind;
  20083. },
  20084. enumerable: true,
  20085. configurable: true
  20086. });
  20087. Object.defineProperty(VertexBuffer, "NormalKind", {
  20088. get: function () {
  20089. return VertexBuffer._NormalKind;
  20090. },
  20091. enumerable: true,
  20092. configurable: true
  20093. });
  20094. Object.defineProperty(VertexBuffer, "TangentKind", {
  20095. get: function () {
  20096. return VertexBuffer._TangentKind;
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Object.defineProperty(VertexBuffer, "UVKind", {
  20102. get: function () {
  20103. return VertexBuffer._UVKind;
  20104. },
  20105. enumerable: true,
  20106. configurable: true
  20107. });
  20108. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20109. get: function () {
  20110. return VertexBuffer._UV2Kind;
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20116. get: function () {
  20117. return VertexBuffer._UV3Kind;
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20123. get: function () {
  20124. return VertexBuffer._UV4Kind;
  20125. },
  20126. enumerable: true,
  20127. configurable: true
  20128. });
  20129. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20130. get: function () {
  20131. return VertexBuffer._UV5Kind;
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20137. get: function () {
  20138. return VertexBuffer._UV6Kind;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(VertexBuffer, "ColorKind", {
  20144. get: function () {
  20145. return VertexBuffer._ColorKind;
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20151. get: function () {
  20152. return VertexBuffer._MatricesIndicesKind;
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20158. get: function () {
  20159. return VertexBuffer._MatricesWeightsKind;
  20160. },
  20161. enumerable: true,
  20162. configurable: true
  20163. });
  20164. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20165. get: function () {
  20166. return VertexBuffer._MatricesIndicesExtraKind;
  20167. },
  20168. enumerable: true,
  20169. configurable: true
  20170. });
  20171. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20172. get: function () {
  20173. return VertexBuffer._MatricesWeightsExtraKind;
  20174. },
  20175. enumerable: true,
  20176. configurable: true
  20177. });
  20178. // Enums
  20179. VertexBuffer._PositionKind = "position";
  20180. VertexBuffer._NormalKind = "normal";
  20181. VertexBuffer._TangentKind = "tangent";
  20182. VertexBuffer._UVKind = "uv";
  20183. VertexBuffer._UV2Kind = "uv2";
  20184. VertexBuffer._UV3Kind = "uv3";
  20185. VertexBuffer._UV4Kind = "uv4";
  20186. VertexBuffer._UV5Kind = "uv5";
  20187. VertexBuffer._UV6Kind = "uv6";
  20188. VertexBuffer._ColorKind = "color";
  20189. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20190. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20191. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20192. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20193. return VertexBuffer;
  20194. }());
  20195. BABYLON.VertexBuffer = VertexBuffer;
  20196. })(BABYLON || (BABYLON = {}));
  20197. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20198. var BABYLON;
  20199. (function (BABYLON) {
  20200. var InternalTexture = (function () {
  20201. function InternalTexture(engine, dataSource) {
  20202. this.onLoadedObservable = new BABYLON.Observable();
  20203. // Private
  20204. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20205. this._references = 1;
  20206. this._engine = engine;
  20207. this._dataSource = dataSource;
  20208. this._webGLTexture = engine._createTexture();
  20209. }
  20210. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20211. get: function () {
  20212. return this._dataSource;
  20213. },
  20214. enumerable: true,
  20215. configurable: true
  20216. });
  20217. InternalTexture.prototype.incrementReferences = function () {
  20218. this._references++;
  20219. };
  20220. InternalTexture.prototype.updateSize = function (width, height) {
  20221. this.width = width;
  20222. this.height = height;
  20223. this._size = width * height;
  20224. this.baseWidth = width;
  20225. this.baseHeight = height;
  20226. };
  20227. InternalTexture.prototype._rebuild = function () {
  20228. var _this = this;
  20229. var proxy;
  20230. this.isReady = false;
  20231. this._cachedCoordinatesMode = null;
  20232. this._cachedWrapU = null;
  20233. this._cachedWrapV = null;
  20234. this._cachedAnisotropicFilteringLevel = null;
  20235. switch (this._dataSource) {
  20236. case InternalTexture.DATASOURCE_TEMP:
  20237. return;
  20238. case InternalTexture.DATASOURCE_URL:
  20239. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20240. _this.isReady = true;
  20241. }, null, this._buffer, null, this.format);
  20242. proxy._swapAndDie(this);
  20243. return;
  20244. case InternalTexture.DATASOURCE_RAW:
  20245. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20246. proxy._swapAndDie(this);
  20247. this.isReady = true;
  20248. return;
  20249. case InternalTexture.DATASOURCE_DYNAMIC:
  20250. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20251. proxy._swapAndDie(this);
  20252. // The engine will make sure to update content so no need to flag it as isReady = true
  20253. return;
  20254. case InternalTexture.DATASOURCE_RENDERTARGET:
  20255. var options = new BABYLON.RenderTargetCreationOptions();
  20256. options.generateDepthBuffer = this._generateDepthBuffer;
  20257. options.generateMipMaps = this.generateMipMaps;
  20258. options.generateStencilBuffer = this._generateStencilBuffer;
  20259. options.samplingMode = this.samplingMode;
  20260. options.type = this.type;
  20261. if (this.isCube) {
  20262. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20263. }
  20264. else {
  20265. var size = {
  20266. width: this.width,
  20267. height: this.height
  20268. };
  20269. proxy = this._engine.createRenderTargetTexture(size, options);
  20270. }
  20271. proxy._swapAndDie(this);
  20272. this.isReady = true;
  20273. return;
  20274. case InternalTexture.DATASOURCE_CUBE:
  20275. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20276. _this.isReady = true;
  20277. }, null, this.format, this._extension);
  20278. proxy._swapAndDie(this);
  20279. return;
  20280. case InternalTexture.DATASOURCE_CUBERAW:
  20281. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20282. proxy._swapAndDie(this);
  20283. this.isReady = true;
  20284. return;
  20285. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20286. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20287. proxy._swapAndDie(_this);
  20288. _this.isReady = true;
  20289. }, null, this.format, this._extension);
  20290. return;
  20291. }
  20292. };
  20293. InternalTexture.prototype._swapAndDie = function (target) {
  20294. target._webGLTexture = this._webGLTexture;
  20295. if (this._framebuffer) {
  20296. target._framebuffer = this._framebuffer;
  20297. }
  20298. if (this._depthStencilBuffer) {
  20299. target._depthStencilBuffer = this._depthStencilBuffer;
  20300. }
  20301. if (this._lodTextureHigh) {
  20302. if (target._lodTextureHigh) {
  20303. target._lodTextureHigh.dispose();
  20304. }
  20305. target._lodTextureHigh = this._lodTextureHigh;
  20306. }
  20307. if (this._lodTextureMid) {
  20308. if (target._lodTextureMid) {
  20309. target._lodTextureMid.dispose();
  20310. }
  20311. target._lodTextureMid = this._lodTextureMid;
  20312. }
  20313. if (this._lodTextureLow) {
  20314. if (target._lodTextureLow) {
  20315. target._lodTextureLow.dispose();
  20316. }
  20317. target._lodTextureLow = this._lodTextureLow;
  20318. }
  20319. var cache = this._engine.getLoadedTexturesCache();
  20320. var index = cache.indexOf(this);
  20321. if (index !== -1) {
  20322. cache.splice(index, 1);
  20323. }
  20324. };
  20325. InternalTexture.prototype.dispose = function () {
  20326. if (!this._webGLTexture) {
  20327. return;
  20328. }
  20329. this._references--;
  20330. if (this._references === 0) {
  20331. this._engine._releaseTexture(this);
  20332. this._webGLTexture = null;
  20333. }
  20334. };
  20335. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20336. InternalTexture.DATASOURCE_URL = 1;
  20337. InternalTexture.DATASOURCE_TEMP = 2;
  20338. InternalTexture.DATASOURCE_RAW = 3;
  20339. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20340. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20341. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20342. InternalTexture.DATASOURCE_CUBE = 7;
  20343. InternalTexture.DATASOURCE_CUBERAW = 8;
  20344. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20345. return InternalTexture;
  20346. }());
  20347. BABYLON.InternalTexture = InternalTexture;
  20348. })(BABYLON || (BABYLON = {}));
  20349. //# sourceMappingURL=babylon.internalTexture.js.map
  20350. var BABYLON;
  20351. (function (BABYLON) {
  20352. var BaseTexture = (function () {
  20353. function BaseTexture(scene) {
  20354. this._hasAlpha = false;
  20355. this.getAlphaFromRGB = false;
  20356. this.level = 1;
  20357. this.coordinatesIndex = 0;
  20358. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20359. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20360. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20361. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20362. this.isCube = false;
  20363. this.gammaSpace = true;
  20364. this.invertZ = false;
  20365. this.lodLevelInAlpha = false;
  20366. this.lodGenerationOffset = 0.0;
  20367. this.lodGenerationScale = 0.8;
  20368. this.isRenderTarget = false;
  20369. this.animations = new Array();
  20370. /**
  20371. * An event triggered when the texture is disposed.
  20372. * @type {BABYLON.Observable}
  20373. */
  20374. this.onDisposeObservable = new BABYLON.Observable();
  20375. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20376. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20377. this._scene.textures.push(this);
  20378. this._uid = null;
  20379. }
  20380. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20381. get: function () {
  20382. return this._hasAlpha;
  20383. },
  20384. set: function (value) {
  20385. if (this._hasAlpha === value) {
  20386. return;
  20387. }
  20388. this._hasAlpha = value;
  20389. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20390. },
  20391. enumerable: true,
  20392. configurable: true
  20393. });
  20394. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20395. get: function () {
  20396. return this._coordinatesMode;
  20397. },
  20398. set: function (value) {
  20399. if (this._coordinatesMode === value) {
  20400. return;
  20401. }
  20402. this._coordinatesMode = value;
  20403. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20404. },
  20405. enumerable: true,
  20406. configurable: true
  20407. });
  20408. Object.defineProperty(BaseTexture.prototype, "uid", {
  20409. get: function () {
  20410. if (!this._uid) {
  20411. this._uid = BABYLON.Tools.RandomId();
  20412. }
  20413. return this._uid;
  20414. },
  20415. enumerable: true,
  20416. configurable: true
  20417. });
  20418. BaseTexture.prototype.toString = function () {
  20419. return this.name;
  20420. };
  20421. BaseTexture.prototype.getClassName = function () {
  20422. return "BaseTexture";
  20423. };
  20424. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20425. set: function (callback) {
  20426. if (this._onDisposeObserver) {
  20427. this.onDisposeObservable.remove(this._onDisposeObserver);
  20428. }
  20429. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20430. },
  20431. enumerable: true,
  20432. configurable: true
  20433. });
  20434. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20435. get: function () {
  20436. return true;
  20437. },
  20438. enumerable: true,
  20439. configurable: true
  20440. });
  20441. BaseTexture.prototype.getScene = function () {
  20442. return this._scene;
  20443. };
  20444. BaseTexture.prototype.getTextureMatrix = function () {
  20445. return null;
  20446. };
  20447. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20448. return null;
  20449. };
  20450. BaseTexture.prototype.getInternalTexture = function () {
  20451. return this._texture;
  20452. };
  20453. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20454. return !this.isBlocking || this.isReady();
  20455. };
  20456. BaseTexture.prototype.isReady = function () {
  20457. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20458. this.delayLoad();
  20459. return false;
  20460. }
  20461. if (this._texture) {
  20462. return this._texture.isReady;
  20463. }
  20464. return false;
  20465. };
  20466. BaseTexture.prototype.getSize = function () {
  20467. if (this._texture.width) {
  20468. return new BABYLON.Size(this._texture.width, this._texture.height);
  20469. }
  20470. if (this._texture._size) {
  20471. return new BABYLON.Size(this._texture._size, this._texture._size);
  20472. }
  20473. return BABYLON.Size.Zero();
  20474. };
  20475. BaseTexture.prototype.getBaseSize = function () {
  20476. if (!this.isReady() || !this._texture)
  20477. return BABYLON.Size.Zero();
  20478. if (this._texture._size) {
  20479. return new BABYLON.Size(this._texture._size, this._texture._size);
  20480. }
  20481. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20482. };
  20483. BaseTexture.prototype.scale = function (ratio) {
  20484. };
  20485. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20486. get: function () {
  20487. return false;
  20488. },
  20489. enumerable: true,
  20490. configurable: true
  20491. });
  20492. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20493. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20494. for (var index = 0; index < texturesCache.length; index++) {
  20495. var texturesCacheEntry = texturesCache[index];
  20496. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20497. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20498. texturesCacheEntry.incrementReferences();
  20499. return texturesCacheEntry;
  20500. }
  20501. }
  20502. }
  20503. return null;
  20504. };
  20505. BaseTexture.prototype._rebuild = function () {
  20506. };
  20507. BaseTexture.prototype.delayLoad = function () {
  20508. };
  20509. BaseTexture.prototype.clone = function () {
  20510. return null;
  20511. };
  20512. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20513. get: function () {
  20514. if (!this._texture) {
  20515. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20516. }
  20517. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20518. },
  20519. enumerable: true,
  20520. configurable: true
  20521. });
  20522. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20523. get: function () {
  20524. if (!this._texture) {
  20525. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20526. }
  20527. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20528. },
  20529. enumerable: true,
  20530. configurable: true
  20531. });
  20532. BaseTexture.prototype.readPixels = function (faceIndex) {
  20533. if (faceIndex === void 0) { faceIndex = 0; }
  20534. if (!this._texture) {
  20535. return null;
  20536. }
  20537. var size = this.getSize();
  20538. var engine = this.getScene().getEngine();
  20539. if (this._texture.isCube) {
  20540. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20541. }
  20542. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20543. };
  20544. BaseTexture.prototype.releaseInternalTexture = function () {
  20545. if (this._texture) {
  20546. this._texture.dispose();
  20547. this._texture = null;
  20548. }
  20549. };
  20550. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20551. get: function () {
  20552. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20553. return null;
  20554. }
  20555. if (!this._texture._sphericalPolynomial) {
  20556. this._texture._sphericalPolynomial =
  20557. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20558. }
  20559. return this._texture._sphericalPolynomial;
  20560. },
  20561. set: function (value) {
  20562. if (this._texture) {
  20563. this._texture._sphericalPolynomial = value;
  20564. }
  20565. },
  20566. enumerable: true,
  20567. configurable: true
  20568. });
  20569. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20570. get: function () {
  20571. if (this._texture) {
  20572. return this._texture._lodTextureHigh;
  20573. }
  20574. return null;
  20575. },
  20576. enumerable: true,
  20577. configurable: true
  20578. });
  20579. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20580. get: function () {
  20581. if (this._texture) {
  20582. return this._texture._lodTextureMid;
  20583. }
  20584. return null;
  20585. },
  20586. enumerable: true,
  20587. configurable: true
  20588. });
  20589. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20590. get: function () {
  20591. if (this._texture) {
  20592. return this._texture._lodTextureLow;
  20593. }
  20594. return null;
  20595. },
  20596. enumerable: true,
  20597. configurable: true
  20598. });
  20599. BaseTexture.prototype.dispose = function () {
  20600. // Animations
  20601. this.getScene().stopAnimation(this);
  20602. // Remove from scene
  20603. this._scene._removePendingData(this);
  20604. var index = this._scene.textures.indexOf(this);
  20605. if (index >= 0) {
  20606. this._scene.textures.splice(index, 1);
  20607. }
  20608. if (this._texture === undefined) {
  20609. return;
  20610. }
  20611. // Release
  20612. this.releaseInternalTexture();
  20613. // Callback
  20614. this.onDisposeObservable.notifyObservers(this);
  20615. this.onDisposeObservable.clear();
  20616. };
  20617. BaseTexture.prototype.serialize = function () {
  20618. if (!this.name) {
  20619. return null;
  20620. }
  20621. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20622. // Animations
  20623. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20624. return serializationObject;
  20625. };
  20626. BaseTexture.WhenAllReady = function (textures, callback) {
  20627. var numRemaining = textures.length;
  20628. if (numRemaining === 0) {
  20629. callback();
  20630. return;
  20631. }
  20632. var _loop_1 = function () {
  20633. texture = textures[i];
  20634. if (texture.isReady()) {
  20635. if (--numRemaining === 0) {
  20636. callback();
  20637. }
  20638. }
  20639. else {
  20640. onLoadObservable = texture.onLoadObservable;
  20641. var onLoadCallback_1 = function () {
  20642. onLoadObservable.removeCallback(onLoadCallback_1);
  20643. if (--numRemaining === 0) {
  20644. callback();
  20645. }
  20646. };
  20647. onLoadObservable.add(onLoadCallback_1);
  20648. }
  20649. };
  20650. var texture, onLoadObservable;
  20651. for (var i = 0; i < textures.length; i++) {
  20652. _loop_1();
  20653. }
  20654. };
  20655. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20656. __decorate([
  20657. BABYLON.serialize()
  20658. ], BaseTexture.prototype, "name", void 0);
  20659. __decorate([
  20660. BABYLON.serialize("hasAlpha")
  20661. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20662. __decorate([
  20663. BABYLON.serialize()
  20664. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20665. __decorate([
  20666. BABYLON.serialize()
  20667. ], BaseTexture.prototype, "level", void 0);
  20668. __decorate([
  20669. BABYLON.serialize()
  20670. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20671. __decorate([
  20672. BABYLON.serialize("coordinatesMode")
  20673. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20674. __decorate([
  20675. BABYLON.serialize()
  20676. ], BaseTexture.prototype, "wrapU", void 0);
  20677. __decorate([
  20678. BABYLON.serialize()
  20679. ], BaseTexture.prototype, "wrapV", void 0);
  20680. __decorate([
  20681. BABYLON.serialize()
  20682. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20683. __decorate([
  20684. BABYLON.serialize()
  20685. ], BaseTexture.prototype, "isCube", void 0);
  20686. __decorate([
  20687. BABYLON.serialize()
  20688. ], BaseTexture.prototype, "gammaSpace", void 0);
  20689. __decorate([
  20690. BABYLON.serialize()
  20691. ], BaseTexture.prototype, "invertZ", void 0);
  20692. __decorate([
  20693. BABYLON.serialize()
  20694. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20695. __decorate([
  20696. BABYLON.serialize()
  20697. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20698. __decorate([
  20699. BABYLON.serialize()
  20700. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20701. __decorate([
  20702. BABYLON.serialize()
  20703. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20704. return BaseTexture;
  20705. }());
  20706. BABYLON.BaseTexture = BaseTexture;
  20707. })(BABYLON || (BABYLON = {}));
  20708. //# sourceMappingURL=babylon.baseTexture.js.map
  20709. var BABYLON;
  20710. (function (BABYLON) {
  20711. var Texture = (function (_super) {
  20712. __extends(Texture, _super);
  20713. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20714. if (noMipmap === void 0) { noMipmap = false; }
  20715. if (invertY === void 0) { invertY = true; }
  20716. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20717. if (onLoad === void 0) { onLoad = null; }
  20718. if (onError === void 0) { onError = null; }
  20719. if (buffer === void 0) { buffer = null; }
  20720. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20721. var _this = _super.call(this, scene) || this;
  20722. _this.uOffset = 0;
  20723. _this.vOffset = 0;
  20724. _this.uScale = 1.0;
  20725. _this.vScale = 1.0;
  20726. _this.uAng = 0;
  20727. _this.vAng = 0;
  20728. _this.wAng = 0;
  20729. _this._isBlocking = true;
  20730. _this.name = url;
  20731. _this.url = url;
  20732. _this._noMipmap = noMipmap;
  20733. _this._invertY = invertY;
  20734. _this._samplingMode = samplingMode;
  20735. _this._buffer = buffer;
  20736. _this._deleteBuffer = deleteBuffer;
  20737. _this._format = format;
  20738. scene = _this.getScene();
  20739. var load = function () {
  20740. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20741. _this.onLoadObservable.notifyObservers(_this);
  20742. }
  20743. if (onLoad) {
  20744. onLoad();
  20745. }
  20746. if (!_this.isBlocking) {
  20747. scene.resetCachedMaterial();
  20748. }
  20749. };
  20750. if (!url) {
  20751. _this._delayedOnLoad = load;
  20752. _this._delayedOnError = onError;
  20753. return _this;
  20754. }
  20755. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20756. if (!_this._texture) {
  20757. if (!scene.useDelayedTextureLoading) {
  20758. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20759. if (deleteBuffer) {
  20760. delete _this._buffer;
  20761. }
  20762. }
  20763. else {
  20764. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20765. _this._delayedOnLoad = load;
  20766. _this._delayedOnError = onError;
  20767. }
  20768. }
  20769. else {
  20770. if (_this._texture.isReady) {
  20771. BABYLON.Tools.SetImmediate(function () { return load(); });
  20772. }
  20773. else {
  20774. _this._texture.onLoadedObservable.add(load);
  20775. }
  20776. }
  20777. return _this;
  20778. }
  20779. Object.defineProperty(Texture.prototype, "noMipmap", {
  20780. get: function () {
  20781. return this._noMipmap;
  20782. },
  20783. enumerable: true,
  20784. configurable: true
  20785. });
  20786. Object.defineProperty(Texture.prototype, "isBlocking", {
  20787. get: function () {
  20788. return this._isBlocking;
  20789. },
  20790. set: function (value) {
  20791. this._isBlocking = value;
  20792. },
  20793. enumerable: true,
  20794. configurable: true
  20795. });
  20796. Object.defineProperty(Texture.prototype, "samplingMode", {
  20797. get: function () {
  20798. return this._samplingMode;
  20799. },
  20800. enumerable: true,
  20801. configurable: true
  20802. });
  20803. Texture.prototype.updateURL = function (url) {
  20804. this.url = url;
  20805. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20806. this.delayLoad();
  20807. };
  20808. Texture.prototype.delayLoad = function () {
  20809. var _this = this;
  20810. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20811. return;
  20812. }
  20813. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20814. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20815. if (!this._texture) {
  20816. 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);
  20817. if (this._deleteBuffer) {
  20818. delete this._buffer;
  20819. }
  20820. }
  20821. else {
  20822. if (this._texture.isReady) {
  20823. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20824. }
  20825. else {
  20826. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20827. }
  20828. }
  20829. };
  20830. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20831. if (!this._texture) {
  20832. return;
  20833. }
  20834. this._samplingMode = samplingMode;
  20835. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20836. };
  20837. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20838. x *= this.uScale;
  20839. y *= this.vScale;
  20840. x -= 0.5 * this.uScale;
  20841. y -= 0.5 * this.vScale;
  20842. z -= 0.5;
  20843. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20844. t.x += 0.5 * this.uScale + this.uOffset;
  20845. t.y += 0.5 * this.vScale + this.vOffset;
  20846. t.z += 0.5;
  20847. };
  20848. Texture.prototype.getTextureMatrix = function () {
  20849. var _this = this;
  20850. if (this.uOffset === this._cachedUOffset &&
  20851. this.vOffset === this._cachedVOffset &&
  20852. this.uScale === this._cachedUScale &&
  20853. this.vScale === this._cachedVScale &&
  20854. this.uAng === this._cachedUAng &&
  20855. this.vAng === this._cachedVAng &&
  20856. this.wAng === this._cachedWAng) {
  20857. return this._cachedTextureMatrix;
  20858. }
  20859. this._cachedUOffset = this.uOffset;
  20860. this._cachedVOffset = this.vOffset;
  20861. this._cachedUScale = this.uScale;
  20862. this._cachedVScale = this.vScale;
  20863. this._cachedUAng = this.uAng;
  20864. this._cachedVAng = this.vAng;
  20865. this._cachedWAng = this.wAng;
  20866. if (!this._cachedTextureMatrix) {
  20867. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20868. this._rowGenerationMatrix = new BABYLON.Matrix();
  20869. this._t0 = BABYLON.Vector3.Zero();
  20870. this._t1 = BABYLON.Vector3.Zero();
  20871. this._t2 = BABYLON.Vector3.Zero();
  20872. }
  20873. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20874. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20875. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20876. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20877. this._t1.subtractInPlace(this._t0);
  20878. this._t2.subtractInPlace(this._t0);
  20879. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20880. this._cachedTextureMatrix.m[0] = this._t1.x;
  20881. this._cachedTextureMatrix.m[1] = this._t1.y;
  20882. this._cachedTextureMatrix.m[2] = this._t1.z;
  20883. this._cachedTextureMatrix.m[4] = this._t2.x;
  20884. this._cachedTextureMatrix.m[5] = this._t2.y;
  20885. this._cachedTextureMatrix.m[6] = this._t2.z;
  20886. this._cachedTextureMatrix.m[8] = this._t0.x;
  20887. this._cachedTextureMatrix.m[9] = this._t0.y;
  20888. this._cachedTextureMatrix.m[10] = this._t0.z;
  20889. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20890. return mat.hasTexture(_this);
  20891. });
  20892. return this._cachedTextureMatrix;
  20893. };
  20894. Texture.prototype.getReflectionTextureMatrix = function () {
  20895. var _this = this;
  20896. var scene = this.getScene();
  20897. if (this.uOffset === this._cachedUOffset &&
  20898. this.vOffset === this._cachedVOffset &&
  20899. this.uScale === this._cachedUScale &&
  20900. this.vScale === this._cachedVScale &&
  20901. this.coordinatesMode === this._cachedCoordinatesMode) {
  20902. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20903. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20904. return this._cachedTextureMatrix;
  20905. }
  20906. }
  20907. else {
  20908. return this._cachedTextureMatrix;
  20909. }
  20910. }
  20911. if (!this._cachedTextureMatrix) {
  20912. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20913. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20914. }
  20915. this._cachedUOffset = this.uOffset;
  20916. this._cachedVOffset = this.vOffset;
  20917. this._cachedUScale = this.uScale;
  20918. this._cachedVScale = this.vScale;
  20919. this._cachedCoordinatesMode = this.coordinatesMode;
  20920. switch (this.coordinatesMode) {
  20921. case Texture.PLANAR_MODE:
  20922. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20923. this._cachedTextureMatrix[0] = this.uScale;
  20924. this._cachedTextureMatrix[5] = this.vScale;
  20925. this._cachedTextureMatrix[12] = this.uOffset;
  20926. this._cachedTextureMatrix[13] = this.vOffset;
  20927. break;
  20928. case Texture.PROJECTION_MODE:
  20929. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20930. this._projectionModeMatrix.m[0] = 0.5;
  20931. this._projectionModeMatrix.m[5] = -0.5;
  20932. this._projectionModeMatrix.m[10] = 0.0;
  20933. this._projectionModeMatrix.m[12] = 0.5;
  20934. this._projectionModeMatrix.m[13] = 0.5;
  20935. this._projectionModeMatrix.m[14] = 1.0;
  20936. this._projectionModeMatrix.m[15] = 1.0;
  20937. var projectionMatrix = scene.getProjectionMatrix();
  20938. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20939. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20940. break;
  20941. default:
  20942. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20943. break;
  20944. }
  20945. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20946. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20947. });
  20948. return this._cachedTextureMatrix;
  20949. };
  20950. Texture.prototype.clone = function () {
  20951. var _this = this;
  20952. return BABYLON.SerializationHelper.Clone(function () {
  20953. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20954. }, this);
  20955. };
  20956. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20957. get: function () {
  20958. if (!this._onLoadObservable) {
  20959. this._onLoadObservable = new BABYLON.Observable();
  20960. }
  20961. return this._onLoadObservable;
  20962. },
  20963. enumerable: true,
  20964. configurable: true
  20965. });
  20966. Texture.prototype.serialize = function () {
  20967. var serializationObject = _super.prototype.serialize.call(this);
  20968. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20969. serializationObject.base64String = this._buffer;
  20970. serializationObject.name = serializationObject.name.replace("data:", "");
  20971. }
  20972. return serializationObject;
  20973. };
  20974. Texture.prototype.getClassName = function () {
  20975. return "Texture";
  20976. };
  20977. Texture.prototype.dispose = function () {
  20978. _super.prototype.dispose.call(this);
  20979. if (this.onLoadObservable) {
  20980. this.onLoadObservable.clear();
  20981. this._onLoadObservable = null;
  20982. }
  20983. this._delayedOnLoad = null;
  20984. this._delayedOnError = null;
  20985. };
  20986. // Statics
  20987. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20988. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20989. if (onLoad === void 0) { onLoad = null; }
  20990. if (onError === void 0) { onError = null; }
  20991. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20992. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20993. };
  20994. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20995. if (parsedTexture.customType) {
  20996. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20997. // Update Sampling Mode
  20998. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20999. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21000. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21001. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21002. }
  21003. }
  21004. return parsedCustomTexture;
  21005. }
  21006. if (parsedTexture.isCube) {
  21007. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21008. }
  21009. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21010. return null;
  21011. }
  21012. var texture = BABYLON.SerializationHelper.Parse(function () {
  21013. if (parsedTexture.mirrorPlane) {
  21014. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21015. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21016. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21017. return mirrorTexture;
  21018. }
  21019. else if (parsedTexture.isRenderTarget) {
  21020. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21021. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21022. return renderTargetTexture;
  21023. }
  21024. else {
  21025. var texture;
  21026. if (parsedTexture.base64String) {
  21027. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21028. }
  21029. else {
  21030. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21031. }
  21032. return texture;
  21033. }
  21034. }, parsedTexture, scene);
  21035. // Update Sampling Mode
  21036. if (parsedTexture.samplingMode) {
  21037. var sampling = parsedTexture.samplingMode;
  21038. if (texture._samplingMode !== sampling) {
  21039. texture.updateSamplingMode(sampling);
  21040. }
  21041. }
  21042. // Animations
  21043. if (parsedTexture.animations) {
  21044. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21045. var parsedAnimation = parsedTexture.animations[animationIndex];
  21046. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21047. }
  21048. }
  21049. return texture;
  21050. };
  21051. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21052. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21053. if (noMipmap === void 0) { noMipmap = false; }
  21054. if (invertY === void 0) { invertY = true; }
  21055. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21056. if (onLoad === void 0) { onLoad = null; }
  21057. if (onError === void 0) { onError = null; }
  21058. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21059. if (name.substr(0, 5) !== "data:") {
  21060. name = "data:" + name;
  21061. }
  21062. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21063. };
  21064. // Constants
  21065. Texture.NEAREST_SAMPLINGMODE = 1;
  21066. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21067. Texture.BILINEAR_SAMPLINGMODE = 2;
  21068. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21069. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21070. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21071. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21072. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21073. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21074. Texture.NEAREST_LINEAR = 7;
  21075. Texture.NEAREST_NEAREST = 8;
  21076. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21077. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21078. Texture.LINEAR_LINEAR = 11;
  21079. Texture.LINEAR_NEAREST = 12;
  21080. Texture.EXPLICIT_MODE = 0;
  21081. Texture.SPHERICAL_MODE = 1;
  21082. Texture.PLANAR_MODE = 2;
  21083. Texture.CUBIC_MODE = 3;
  21084. Texture.PROJECTION_MODE = 4;
  21085. Texture.SKYBOX_MODE = 5;
  21086. Texture.INVCUBIC_MODE = 6;
  21087. Texture.EQUIRECTANGULAR_MODE = 7;
  21088. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21089. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21090. Texture.CLAMP_ADDRESSMODE = 0;
  21091. Texture.WRAP_ADDRESSMODE = 1;
  21092. Texture.MIRROR_ADDRESSMODE = 2;
  21093. __decorate([
  21094. BABYLON.serialize()
  21095. ], Texture.prototype, "url", void 0);
  21096. __decorate([
  21097. BABYLON.serialize()
  21098. ], Texture.prototype, "uOffset", void 0);
  21099. __decorate([
  21100. BABYLON.serialize()
  21101. ], Texture.prototype, "vOffset", void 0);
  21102. __decorate([
  21103. BABYLON.serialize()
  21104. ], Texture.prototype, "uScale", void 0);
  21105. __decorate([
  21106. BABYLON.serialize()
  21107. ], Texture.prototype, "vScale", void 0);
  21108. __decorate([
  21109. BABYLON.serialize()
  21110. ], Texture.prototype, "uAng", void 0);
  21111. __decorate([
  21112. BABYLON.serialize()
  21113. ], Texture.prototype, "vAng", void 0);
  21114. __decorate([
  21115. BABYLON.serialize()
  21116. ], Texture.prototype, "wAng", void 0);
  21117. __decorate([
  21118. BABYLON.serialize()
  21119. ], Texture.prototype, "isBlocking", null);
  21120. return Texture;
  21121. }(BABYLON.BaseTexture));
  21122. BABYLON.Texture = Texture;
  21123. })(BABYLON || (BABYLON = {}));
  21124. //# sourceMappingURL=babylon.texture.js.map
  21125. var BABYLON;
  21126. (function (BABYLON) {
  21127. var _InstancesBatch = (function () {
  21128. function _InstancesBatch() {
  21129. this.mustReturn = false;
  21130. this.visibleInstances = new Array();
  21131. this.renderSelf = new Array();
  21132. }
  21133. return _InstancesBatch;
  21134. }());
  21135. BABYLON._InstancesBatch = _InstancesBatch;
  21136. var Mesh = (function (_super) {
  21137. __extends(Mesh, _super);
  21138. /**
  21139. * @constructor
  21140. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21141. * @param {Scene} scene The scene to add this mesh to.
  21142. * @param {Node} parent The parent of this mesh, if it has one
  21143. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21144. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21145. * When false, achieved by calling a clone(), also passing False.
  21146. * This will make creation of children, recursive.
  21147. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21148. */
  21149. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21150. if (parent === void 0) { parent = null; }
  21151. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21152. var _this = _super.call(this, name, scene) || this;
  21153. // Events
  21154. /**
  21155. * An event triggered before rendering the mesh
  21156. * @type {BABYLON.Observable}
  21157. */
  21158. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21159. /**
  21160. * An event triggered after rendering the mesh
  21161. * @type {BABYLON.Observable}
  21162. */
  21163. _this.onAfterRenderObservable = new BABYLON.Observable();
  21164. /**
  21165. * An event triggered before drawing the mesh
  21166. * @type {BABYLON.Observable}
  21167. */
  21168. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21169. // Members
  21170. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21171. _this.instances = new Array();
  21172. _this._LODLevels = new Array();
  21173. _this._visibleInstances = {};
  21174. _this._renderIdForInstances = new Array();
  21175. _this._batchCache = new _InstancesBatch();
  21176. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21177. _this._sideOrientation = Mesh._DEFAULTSIDE;
  21178. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21179. // Will be used to save a source mesh reference, If any
  21180. _this._source = null;
  21181. if (source) {
  21182. // Source mesh
  21183. _this._source = source;
  21184. // Geometry
  21185. if (source._geometry) {
  21186. source._geometry.applyToMesh(_this);
  21187. }
  21188. // Deep copy
  21189. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21190. // Parent
  21191. _this.parent = source.parent;
  21192. // Pivot
  21193. _this.setPivotMatrix(source.getPivotMatrix());
  21194. _this.id = name + "." + source.id;
  21195. // Material
  21196. _this.material = source.material;
  21197. var index;
  21198. if (!doNotCloneChildren) {
  21199. // Children
  21200. for (index = 0; index < scene.meshes.length; index++) {
  21201. var mesh = scene.meshes[index];
  21202. if (mesh.parent === source) {
  21203. // doNotCloneChildren is always going to be False
  21204. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21205. }
  21206. }
  21207. }
  21208. // Physics clone
  21209. var physicsEngine = _this.getScene().getPhysicsEngine();
  21210. if (clonePhysicsImpostor && physicsEngine) {
  21211. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21212. if (impostor) {
  21213. _this.physicsImpostor = impostor.clone(_this);
  21214. }
  21215. }
  21216. // Particles
  21217. for (index = 0; index < scene.particleSystems.length; index++) {
  21218. var system = scene.particleSystems[index];
  21219. if (system.emitter === source) {
  21220. system.clone(system.name, _this);
  21221. }
  21222. }
  21223. _this.computeWorldMatrix(true);
  21224. }
  21225. // Parent
  21226. if (parent !== null) {
  21227. _this.parent = parent;
  21228. }
  21229. return _this;
  21230. }
  21231. Object.defineProperty(Mesh, "FRONTSIDE", {
  21232. /**
  21233. * Mesh side orientation : usually the external or front surface
  21234. */
  21235. get: function () {
  21236. return Mesh._FRONTSIDE;
  21237. },
  21238. enumerable: true,
  21239. configurable: true
  21240. });
  21241. Object.defineProperty(Mesh, "BACKSIDE", {
  21242. /**
  21243. * Mesh side orientation : usually the internal or back surface
  21244. */
  21245. get: function () {
  21246. return Mesh._BACKSIDE;
  21247. },
  21248. enumerable: true,
  21249. configurable: true
  21250. });
  21251. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21252. /**
  21253. * Mesh side orientation : both internal and external or front and back surfaces
  21254. */
  21255. get: function () {
  21256. return Mesh._DOUBLESIDE;
  21257. },
  21258. enumerable: true,
  21259. configurable: true
  21260. });
  21261. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21262. /**
  21263. * Mesh side orientation : by default, `FRONTSIDE`
  21264. */
  21265. get: function () {
  21266. return Mesh._DEFAULTSIDE;
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(Mesh, "NO_CAP", {
  21272. /**
  21273. * Mesh cap setting : no cap
  21274. */
  21275. get: function () {
  21276. return Mesh._NO_CAP;
  21277. },
  21278. enumerable: true,
  21279. configurable: true
  21280. });
  21281. Object.defineProperty(Mesh, "CAP_START", {
  21282. /**
  21283. * Mesh cap setting : one cap at the beginning of the mesh
  21284. */
  21285. get: function () {
  21286. return Mesh._CAP_START;
  21287. },
  21288. enumerable: true,
  21289. configurable: true
  21290. });
  21291. Object.defineProperty(Mesh, "CAP_END", {
  21292. /**
  21293. * Mesh cap setting : one cap at the end of the mesh
  21294. */
  21295. get: function () {
  21296. return Mesh._CAP_END;
  21297. },
  21298. enumerable: true,
  21299. configurable: true
  21300. });
  21301. Object.defineProperty(Mesh, "CAP_ALL", {
  21302. /**
  21303. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21304. */
  21305. get: function () {
  21306. return Mesh._CAP_ALL;
  21307. },
  21308. enumerable: true,
  21309. configurable: true
  21310. });
  21311. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21312. set: function (callback) {
  21313. if (this._onBeforeDrawObserver) {
  21314. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21315. }
  21316. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21317. },
  21318. enumerable: true,
  21319. configurable: true
  21320. });
  21321. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21322. get: function () {
  21323. return this._morphTargetManager;
  21324. },
  21325. set: function (value) {
  21326. if (this._morphTargetManager === value) {
  21327. return;
  21328. }
  21329. this._morphTargetManager = value;
  21330. this._syncGeometryWithMorphTargetManager();
  21331. },
  21332. enumerable: true,
  21333. configurable: true
  21334. });
  21335. Object.defineProperty(Mesh.prototype, "source", {
  21336. get: function () {
  21337. return this._source;
  21338. },
  21339. enumerable: true,
  21340. configurable: true
  21341. });
  21342. // Methods
  21343. /**
  21344. * Returns the string "Mesh".
  21345. */
  21346. Mesh.prototype.getClassName = function () {
  21347. return "Mesh";
  21348. };
  21349. /**
  21350. * Returns a string.
  21351. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21352. */
  21353. Mesh.prototype.toString = function (fullDetails) {
  21354. var ret = _super.prototype.toString.call(this, fullDetails);
  21355. ret += ", n vertices: " + this.getTotalVertices();
  21356. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21357. if (this.animations) {
  21358. for (var i = 0; i < this.animations.length; i++) {
  21359. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21360. }
  21361. }
  21362. if (fullDetails) {
  21363. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21364. }
  21365. return ret;
  21366. };
  21367. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21368. /**
  21369. * True if the mesh has some Levels Of Details (LOD).
  21370. * Returns a boolean.
  21371. */
  21372. get: function () {
  21373. return this._LODLevels.length > 0;
  21374. },
  21375. enumerable: true,
  21376. configurable: true
  21377. });
  21378. Mesh.prototype._sortLODLevels = function () {
  21379. this._LODLevels.sort(function (a, b) {
  21380. if (a.distance < b.distance) {
  21381. return 1;
  21382. }
  21383. if (a.distance > b.distance) {
  21384. return -1;
  21385. }
  21386. return 0;
  21387. });
  21388. };
  21389. /**
  21390. * Add a mesh as LOD level triggered at the given distance.
  21391. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21392. * @param {number} distance The distance from the center of the object to show this level
  21393. * @param {Mesh} mesh The mesh to be added as LOD level
  21394. * @return {Mesh} This mesh (for chaining)
  21395. */
  21396. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21397. if (mesh && mesh._masterMesh) {
  21398. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21399. return this;
  21400. }
  21401. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21402. this._LODLevels.push(level);
  21403. if (mesh) {
  21404. mesh._masterMesh = this;
  21405. }
  21406. this._sortLODLevels();
  21407. return this;
  21408. };
  21409. /**
  21410. * Returns the LOD level mesh at the passed distance or null if not found.
  21411. * It is related to the method `addLODLevel(distance, mesh)`.
  21412. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21413. * Returns an object Mesh or `null`.
  21414. */
  21415. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21416. for (var index = 0; index < this._LODLevels.length; index++) {
  21417. var level = this._LODLevels[index];
  21418. if (level.distance === distance) {
  21419. return level.mesh;
  21420. }
  21421. }
  21422. return null;
  21423. };
  21424. /**
  21425. * Remove a mesh from the LOD array
  21426. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21427. * @param {Mesh} mesh The mesh to be removed.
  21428. * @return {Mesh} This mesh (for chaining)
  21429. */
  21430. Mesh.prototype.removeLODLevel = function (mesh) {
  21431. for (var index = 0; index < this._LODLevels.length; index++) {
  21432. if (this._LODLevels[index].mesh === mesh) {
  21433. this._LODLevels.splice(index, 1);
  21434. if (mesh) {
  21435. mesh._masterMesh = null;
  21436. }
  21437. }
  21438. }
  21439. this._sortLODLevels();
  21440. return this;
  21441. };
  21442. /**
  21443. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21444. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21445. */
  21446. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21447. if (!this._LODLevels || this._LODLevels.length === 0) {
  21448. return this;
  21449. }
  21450. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21451. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21452. if (this.onLODLevelSelection) {
  21453. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21454. }
  21455. return this;
  21456. }
  21457. for (var index = 0; index < this._LODLevels.length; index++) {
  21458. var level = this._LODLevels[index];
  21459. if (level.distance < distanceToCamera) {
  21460. if (level.mesh) {
  21461. level.mesh._preActivate();
  21462. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21463. }
  21464. if (this.onLODLevelSelection) {
  21465. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21466. }
  21467. return level.mesh;
  21468. }
  21469. }
  21470. if (this.onLODLevelSelection) {
  21471. this.onLODLevelSelection(distanceToCamera, this, this);
  21472. }
  21473. return this;
  21474. };
  21475. Object.defineProperty(Mesh.prototype, "geometry", {
  21476. /**
  21477. * Returns the mesh internal Geometry object.
  21478. */
  21479. get: function () {
  21480. return this._geometry;
  21481. },
  21482. enumerable: true,
  21483. configurable: true
  21484. });
  21485. /**
  21486. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21487. */
  21488. Mesh.prototype.getTotalVertices = function () {
  21489. if (!this._geometry) {
  21490. return 0;
  21491. }
  21492. return this._geometry.getTotalVertices();
  21493. };
  21494. /**
  21495. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21496. * 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.
  21497. * You can force the copy with forceCopy === true
  21498. * Returns null if the mesh has no geometry or no vertex buffer.
  21499. * Possible `kind` values :
  21500. * - BABYLON.VertexBuffer.PositionKind
  21501. * - BABYLON.VertexBuffer.UVKind
  21502. * - BABYLON.VertexBuffer.UV2Kind
  21503. * - BABYLON.VertexBuffer.UV3Kind
  21504. * - BABYLON.VertexBuffer.UV4Kind
  21505. * - BABYLON.VertexBuffer.UV5Kind
  21506. * - BABYLON.VertexBuffer.UV6Kind
  21507. * - BABYLON.VertexBuffer.ColorKind
  21508. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21509. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21510. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21511. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21512. */
  21513. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21514. if (!this._geometry) {
  21515. return null;
  21516. }
  21517. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21518. };
  21519. /**
  21520. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21521. * Returns `undefined` if the mesh has no geometry.
  21522. * Possible `kind` values :
  21523. * - BABYLON.VertexBuffer.PositionKind
  21524. * - BABYLON.VertexBuffer.UVKind
  21525. * - BABYLON.VertexBuffer.UV2Kind
  21526. * - BABYLON.VertexBuffer.UV3Kind
  21527. * - BABYLON.VertexBuffer.UV4Kind
  21528. * - BABYLON.VertexBuffer.UV5Kind
  21529. * - BABYLON.VertexBuffer.UV6Kind
  21530. * - BABYLON.VertexBuffer.ColorKind
  21531. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21532. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21533. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21534. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21535. */
  21536. Mesh.prototype.getVertexBuffer = function (kind) {
  21537. if (!this._geometry) {
  21538. return undefined;
  21539. }
  21540. return this._geometry.getVertexBuffer(kind);
  21541. };
  21542. /**
  21543. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21544. * Possible `kind` values :
  21545. * - BABYLON.VertexBuffer.PositionKind
  21546. * - BABYLON.VertexBuffer.UVKind
  21547. * - BABYLON.VertexBuffer.UV2Kind
  21548. * - BABYLON.VertexBuffer.UV3Kind
  21549. * - BABYLON.VertexBuffer.UV4Kind
  21550. * - BABYLON.VertexBuffer.UV5Kind
  21551. * - BABYLON.VertexBuffer.UV6Kind
  21552. * - BABYLON.VertexBuffer.ColorKind
  21553. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21554. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21555. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21556. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21557. */
  21558. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21559. if (!this._geometry) {
  21560. if (this._delayInfo) {
  21561. return this._delayInfo.indexOf(kind) !== -1;
  21562. }
  21563. return false;
  21564. }
  21565. return this._geometry.isVerticesDataPresent(kind);
  21566. };
  21567. /**
  21568. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21569. * Possible `kind` values :
  21570. * - BABYLON.VertexBuffer.PositionKind
  21571. * - BABYLON.VertexBuffer.UVKind
  21572. * - BABYLON.VertexBuffer.UV2Kind
  21573. * - BABYLON.VertexBuffer.UV3Kind
  21574. * - BABYLON.VertexBuffer.UV4Kind
  21575. * - BABYLON.VertexBuffer.UV5Kind
  21576. * - BABYLON.VertexBuffer.UV6Kind
  21577. * - BABYLON.VertexBuffer.ColorKind
  21578. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21579. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21580. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21581. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21582. */
  21583. Mesh.prototype.getVerticesDataKinds = function () {
  21584. if (!this._geometry) {
  21585. var result = [];
  21586. if (this._delayInfo) {
  21587. this._delayInfo.forEach(function (kind, index, array) {
  21588. result.push(kind);
  21589. });
  21590. }
  21591. return result;
  21592. }
  21593. return this._geometry.getVerticesDataKinds();
  21594. };
  21595. /**
  21596. * Returns a positive integer : the total number of indices in this mesh geometry.
  21597. * Returns zero if the mesh has no geometry.
  21598. */
  21599. Mesh.prototype.getTotalIndices = function () {
  21600. if (!this._geometry) {
  21601. return 0;
  21602. }
  21603. return this._geometry.getTotalIndices();
  21604. };
  21605. /**
  21606. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21607. * 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.
  21608. * Returns an empty array if the mesh has no geometry.
  21609. */
  21610. Mesh.prototype.getIndices = function (copyWhenShared) {
  21611. if (!this._geometry) {
  21612. return [];
  21613. }
  21614. return this._geometry.getIndices(copyWhenShared);
  21615. };
  21616. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21617. get: function () {
  21618. return this._masterMesh !== null && this._masterMesh !== undefined;
  21619. },
  21620. enumerable: true,
  21621. configurable: true
  21622. });
  21623. /**
  21624. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21625. */
  21626. Mesh.prototype.isReady = function () {
  21627. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21628. return false;
  21629. }
  21630. return _super.prototype.isReady.call(this);
  21631. };
  21632. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21633. get: function () {
  21634. return this._sideOrientation;
  21635. },
  21636. /**
  21637. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21638. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21639. */
  21640. set: function (sideO) {
  21641. this._sideOrientation = sideO;
  21642. },
  21643. enumerable: true,
  21644. configurable: true
  21645. });
  21646. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21647. /**
  21648. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21649. * This property is pertinent only for updatable parametric shapes.
  21650. */
  21651. get: function () {
  21652. return this._areNormalsFrozen;
  21653. },
  21654. enumerable: true,
  21655. configurable: true
  21656. });
  21657. /**
  21658. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21659. * It has no effect at all on other shapes.
  21660. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21661. * Returns the Mesh.
  21662. */
  21663. Mesh.prototype.freezeNormals = function () {
  21664. this._areNormalsFrozen = true;
  21665. return this;
  21666. };
  21667. /**
  21668. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21669. * It has no effect at all on other shapes.
  21670. * It reactivates the mesh normals computation if it was previously frozen.
  21671. * Returns the Mesh.
  21672. */
  21673. Mesh.prototype.unfreezeNormals = function () {
  21674. this._areNormalsFrozen = false;
  21675. return this;
  21676. };
  21677. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21678. /**
  21679. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21680. */
  21681. set: function (count) {
  21682. this._overridenInstanceCount = count;
  21683. },
  21684. enumerable: true,
  21685. configurable: true
  21686. });
  21687. // Methods
  21688. Mesh.prototype._preActivate = function () {
  21689. var sceneRenderId = this.getScene().getRenderId();
  21690. if (this._preActivateId === sceneRenderId) {
  21691. return this;
  21692. }
  21693. this._preActivateId = sceneRenderId;
  21694. this._visibleInstances = null;
  21695. return this;
  21696. };
  21697. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21698. if (this._visibleInstances) {
  21699. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21700. }
  21701. return this;
  21702. };
  21703. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21704. if (!this._visibleInstances) {
  21705. this._visibleInstances = {};
  21706. this._visibleInstances.defaultRenderId = renderId;
  21707. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21708. }
  21709. if (!this._visibleInstances[renderId]) {
  21710. this._visibleInstances[renderId] = new Array();
  21711. }
  21712. this._visibleInstances[renderId].push(instance);
  21713. return this;
  21714. };
  21715. /**
  21716. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21717. * This means the mesh underlying bounding box and sphere are recomputed.
  21718. * Returns the Mesh.
  21719. */
  21720. Mesh.prototype.refreshBoundingInfo = function () {
  21721. if (this._boundingInfo.isLocked) {
  21722. return;
  21723. }
  21724. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21725. if (data) {
  21726. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21727. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21728. }
  21729. if (this.subMeshes) {
  21730. for (var index = 0; index < this.subMeshes.length; index++) {
  21731. this.subMeshes[index].refreshBoundingInfo();
  21732. }
  21733. }
  21734. this._updateBoundingInfo();
  21735. return this;
  21736. };
  21737. Mesh.prototype._createGlobalSubMesh = function (force) {
  21738. var totalVertices = this.getTotalVertices();
  21739. if (!totalVertices || !this.getIndices()) {
  21740. return null;
  21741. }
  21742. // Check if we need to recreate the submeshes
  21743. if (this.subMeshes && this.subMeshes.length > 0) {
  21744. var totalIndices = this.getIndices().length;
  21745. var needToRecreate = false;
  21746. if (force) {
  21747. needToRecreate = true;
  21748. }
  21749. else {
  21750. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21751. var submesh = _a[_i];
  21752. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21753. needToRecreate = true;
  21754. break;
  21755. }
  21756. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21757. needToRecreate = true;
  21758. break;
  21759. }
  21760. }
  21761. }
  21762. if (!needToRecreate) {
  21763. return;
  21764. }
  21765. }
  21766. this.releaseSubMeshes();
  21767. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21768. };
  21769. Mesh.prototype.subdivide = function (count) {
  21770. if (count < 1) {
  21771. return;
  21772. }
  21773. var totalIndices = this.getTotalIndices();
  21774. var subdivisionSize = (totalIndices / count) | 0;
  21775. var offset = 0;
  21776. // Ensure that subdivisionSize is a multiple of 3
  21777. while (subdivisionSize % 3 !== 0) {
  21778. subdivisionSize++;
  21779. }
  21780. this.releaseSubMeshes();
  21781. for (var index = 0; index < count; index++) {
  21782. if (offset >= totalIndices) {
  21783. break;
  21784. }
  21785. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21786. offset += subdivisionSize;
  21787. }
  21788. this.synchronizeInstances();
  21789. };
  21790. /**
  21791. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21792. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21793. * The `data` are either a numeric array either a Float32Array.
  21794. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21795. * 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).
  21796. * Note that a new underlying VertexBuffer object is created each call.
  21797. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21798. *
  21799. * Possible `kind` values :
  21800. * - BABYLON.VertexBuffer.PositionKind
  21801. * - BABYLON.VertexBuffer.UVKind
  21802. * - BABYLON.VertexBuffer.UV2Kind
  21803. * - BABYLON.VertexBuffer.UV3Kind
  21804. * - BABYLON.VertexBuffer.UV4Kind
  21805. * - BABYLON.VertexBuffer.UV5Kind
  21806. * - BABYLON.VertexBuffer.UV6Kind
  21807. * - BABYLON.VertexBuffer.ColorKind
  21808. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21809. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21810. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21811. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21812. *
  21813. * Returns the Mesh.
  21814. */
  21815. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21816. if (!this._geometry) {
  21817. var vertexData = new BABYLON.VertexData();
  21818. vertexData.set(data, kind);
  21819. var scene = this.getScene();
  21820. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21821. }
  21822. else {
  21823. this._geometry.setVerticesData(kind, data, updatable, stride);
  21824. }
  21825. return this;
  21826. };
  21827. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21828. if (updatable === void 0) { updatable = true; }
  21829. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21830. return;
  21831. }
  21832. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21833. };
  21834. /**
  21835. * Sets the mesh VertexBuffer.
  21836. * Returns the Mesh.
  21837. */
  21838. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21839. if (!this._geometry) {
  21840. var scene = this.getScene();
  21841. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21842. }
  21843. this._geometry.setVerticesBuffer(buffer);
  21844. return this;
  21845. };
  21846. /**
  21847. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21848. * If the mesh has no geometry, it is simply returned as it is.
  21849. * The `data` are either a numeric array either a Float32Array.
  21850. * No new underlying VertexBuffer object is created.
  21851. * 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.
  21852. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21853. *
  21854. * Possible `kind` values :
  21855. * - BABYLON.VertexBuffer.PositionKind
  21856. * - BABYLON.VertexBuffer.UVKind
  21857. * - BABYLON.VertexBuffer.UV2Kind
  21858. * - BABYLON.VertexBuffer.UV3Kind
  21859. * - BABYLON.VertexBuffer.UV4Kind
  21860. * - BABYLON.VertexBuffer.UV5Kind
  21861. * - BABYLON.VertexBuffer.UV6Kind
  21862. * - BABYLON.VertexBuffer.ColorKind
  21863. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21864. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21865. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21866. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21867. *
  21868. * Returns the Mesh.
  21869. */
  21870. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21871. if (!this._geometry) {
  21872. return;
  21873. }
  21874. if (!makeItUnique) {
  21875. this._geometry.updateVerticesData(kind, data, updateExtends);
  21876. }
  21877. else {
  21878. this.makeGeometryUnique();
  21879. this.updateVerticesData(kind, data, updateExtends, false);
  21880. }
  21881. return this;
  21882. };
  21883. /**
  21884. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21885. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21886. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21887. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21888. * Returns the Mesh.
  21889. */
  21890. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21891. if (computeNormals === void 0) { computeNormals = true; }
  21892. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21893. positionFunction(positions);
  21894. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21895. if (computeNormals) {
  21896. var indices = this.getIndices();
  21897. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21898. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21899. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21900. }
  21901. return this;
  21902. };
  21903. /**
  21904. * Creates a un-shared specific occurence of the geometry for the mesh.
  21905. * Returns the Mesh.
  21906. */
  21907. Mesh.prototype.makeGeometryUnique = function () {
  21908. if (!this._geometry) {
  21909. return;
  21910. }
  21911. var oldGeometry = this._geometry;
  21912. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21913. oldGeometry.releaseForMesh(this, true);
  21914. geometry.applyToMesh(this);
  21915. return this;
  21916. };
  21917. /**
  21918. * Sets the mesh indices.
  21919. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21920. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21921. * This method creates a new index buffer each call.
  21922. * Returns the Mesh.
  21923. */
  21924. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21925. if (!this._geometry) {
  21926. var vertexData = new BABYLON.VertexData();
  21927. vertexData.indices = indices;
  21928. var scene = this.getScene();
  21929. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21930. }
  21931. else {
  21932. this._geometry.setIndices(indices, totalVertices);
  21933. }
  21934. return this;
  21935. };
  21936. /**
  21937. * Invert the geometry to move from a right handed system to a left handed one.
  21938. * Returns the Mesh.
  21939. */
  21940. Mesh.prototype.toLeftHanded = function () {
  21941. if (!this._geometry) {
  21942. return;
  21943. }
  21944. this._geometry.toLeftHanded();
  21945. return this;
  21946. };
  21947. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21948. var engine = this.getScene().getEngine();
  21949. // Wireframe
  21950. var indexToBind;
  21951. if (this._unIndexed) {
  21952. indexToBind = null;
  21953. }
  21954. else {
  21955. switch (fillMode) {
  21956. case BABYLON.Material.PointFillMode:
  21957. indexToBind = null;
  21958. break;
  21959. case BABYLON.Material.WireFrameFillMode:
  21960. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21961. break;
  21962. default:
  21963. case BABYLON.Material.TriangleFillMode:
  21964. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21965. break;
  21966. }
  21967. }
  21968. // VBOs
  21969. this._geometry._bind(effect, indexToBind);
  21970. return this;
  21971. };
  21972. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21973. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21974. return this;
  21975. }
  21976. this.onBeforeDrawObservable.notifyObservers(this);
  21977. var engine = this.getScene().getEngine();
  21978. // Draw order
  21979. switch (fillMode) {
  21980. case BABYLON.Material.PointFillMode:
  21981. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21982. break;
  21983. case BABYLON.Material.WireFrameFillMode:
  21984. if (this._unIndexed) {
  21985. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21986. }
  21987. else {
  21988. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21989. }
  21990. break;
  21991. default:
  21992. if (this._unIndexed) {
  21993. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21994. }
  21995. else {
  21996. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21997. }
  21998. }
  21999. return this;
  22000. };
  22001. /**
  22002. * Registers for this mesh a javascript function called just before the rendering process.
  22003. * This function is passed the current mesh.
  22004. * Return the Mesh.
  22005. */
  22006. Mesh.prototype.registerBeforeRender = function (func) {
  22007. this.onBeforeRenderObservable.add(func);
  22008. return this;
  22009. };
  22010. /**
  22011. * Disposes a previously registered javascript function called before the rendering.
  22012. * This function is passed the current mesh.
  22013. * Returns the Mesh.
  22014. */
  22015. Mesh.prototype.unregisterBeforeRender = function (func) {
  22016. this.onBeforeRenderObservable.removeCallback(func);
  22017. return this;
  22018. };
  22019. /**
  22020. * Registers for this mesh a javascript function called just after the rendering is complete.
  22021. * This function is passed the current mesh.
  22022. * Returns the Mesh.
  22023. */
  22024. Mesh.prototype.registerAfterRender = function (func) {
  22025. this.onAfterRenderObservable.add(func);
  22026. return this;
  22027. };
  22028. /**
  22029. * Disposes a previously registered javascript function called after the rendering.
  22030. * This function is passed the current mesh.
  22031. * Return the Mesh.
  22032. */
  22033. Mesh.prototype.unregisterAfterRender = function (func) {
  22034. this.onAfterRenderObservable.removeCallback(func);
  22035. return this;
  22036. };
  22037. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22038. var scene = this.getScene();
  22039. this._batchCache.mustReturn = false;
  22040. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22041. this._batchCache.visibleInstances[subMeshId] = null;
  22042. if (this._visibleInstances) {
  22043. var currentRenderId = scene.getRenderId();
  22044. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22045. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22046. var selfRenderId = this._renderId;
  22047. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22048. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22049. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22050. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22051. }
  22052. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22053. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22054. this._batchCache.mustReturn = true;
  22055. return this._batchCache;
  22056. }
  22057. if (currentRenderId !== selfRenderId) {
  22058. this._batchCache.renderSelf[subMeshId] = false;
  22059. }
  22060. }
  22061. this._renderIdForInstances[subMeshId] = currentRenderId;
  22062. }
  22063. return this._batchCache;
  22064. };
  22065. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22066. var visibleInstances = batch.visibleInstances[subMesh._id];
  22067. var matricesCount = visibleInstances.length + 1;
  22068. var bufferSize = matricesCount * 16 * 4;
  22069. var currentInstancesBufferSize = this._instancesBufferSize;
  22070. var instancesBuffer = this._instancesBuffer;
  22071. while (this._instancesBufferSize < bufferSize) {
  22072. this._instancesBufferSize *= 2;
  22073. }
  22074. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22075. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22076. }
  22077. var offset = 0;
  22078. var instancesCount = 0;
  22079. var world = this.getWorldMatrix();
  22080. if (batch.renderSelf[subMesh._id]) {
  22081. world.copyToArray(this._instancesData, offset);
  22082. offset += 16;
  22083. instancesCount++;
  22084. }
  22085. if (visibleInstances) {
  22086. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22087. var instance = visibleInstances[instanceIndex];
  22088. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22089. offset += 16;
  22090. instancesCount++;
  22091. }
  22092. }
  22093. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22094. if (instancesBuffer) {
  22095. instancesBuffer.dispose();
  22096. }
  22097. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22098. this._instancesBuffer = instancesBuffer;
  22099. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22100. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22101. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22102. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22103. }
  22104. else {
  22105. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22106. }
  22107. this._bind(subMesh, effect, fillMode);
  22108. this._draw(subMesh, fillMode, instancesCount);
  22109. engine.unbindInstanceAttributes();
  22110. return this;
  22111. };
  22112. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22113. var scene = this.getScene();
  22114. var engine = scene.getEngine();
  22115. if (hardwareInstancedRendering) {
  22116. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22117. }
  22118. else {
  22119. if (batch.renderSelf[subMesh._id]) {
  22120. // Draw
  22121. if (onBeforeDraw) {
  22122. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22123. }
  22124. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22125. }
  22126. if (batch.visibleInstances[subMesh._id]) {
  22127. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22128. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22129. // World
  22130. var world = instance.getWorldMatrix();
  22131. if (onBeforeDraw) {
  22132. onBeforeDraw(true, world, effectiveMaterial);
  22133. }
  22134. // Draw
  22135. this._draw(subMesh, fillMode);
  22136. }
  22137. }
  22138. }
  22139. return this;
  22140. };
  22141. /**
  22142. * Triggers the draw call for the mesh.
  22143. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22144. * Returns the Mesh.
  22145. */
  22146. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22147. this.checkOcclusionQuery();
  22148. if (this._isOccluded) {
  22149. return;
  22150. }
  22151. var scene = this.getScene();
  22152. // Managing instances
  22153. var batch = this._getInstancesRenderList(subMesh._id);
  22154. if (batch.mustReturn) {
  22155. return this;
  22156. }
  22157. // Checking geometry state
  22158. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22159. return this;
  22160. }
  22161. var callbackIndex;
  22162. this.onBeforeRenderObservable.notifyObservers(this);
  22163. var engine = scene.getEngine();
  22164. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22165. // Material
  22166. var effectiveMaterial = subMesh.getMaterial();
  22167. if (!effectiveMaterial) {
  22168. return this;
  22169. }
  22170. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22171. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22172. return this;
  22173. }
  22174. }
  22175. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22176. return this;
  22177. }
  22178. // Alpha mode
  22179. if (enableAlphaMode) {
  22180. engine.setAlphaMode(effectiveMaterial.alphaMode);
  22181. }
  22182. // Outline - step 1
  22183. var savedDepthWrite = engine.getDepthWrite();
  22184. if (this.renderOutline) {
  22185. engine.setDepthWrite(false);
  22186. scene.getOutlineRenderer().render(subMesh, batch);
  22187. engine.setDepthWrite(savedDepthWrite);
  22188. }
  22189. var effect;
  22190. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22191. effect = subMesh.effect;
  22192. }
  22193. else {
  22194. effect = effectiveMaterial.getEffect();
  22195. }
  22196. effectiveMaterial._preBind(effect);
  22197. // Bind
  22198. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  22199. if (!hardwareInstancedRendering) {
  22200. this._bind(subMesh, effect, fillMode);
  22201. }
  22202. var world = this.getWorldMatrix();
  22203. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22204. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22205. }
  22206. else {
  22207. effectiveMaterial.bind(world, this);
  22208. }
  22209. // Draw
  22210. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  22211. // Unbind
  22212. effectiveMaterial.unbind();
  22213. // Outline - step 2
  22214. if (this.renderOutline && savedDepthWrite) {
  22215. engine.setDepthWrite(true);
  22216. engine.setColorWrite(false);
  22217. scene.getOutlineRenderer().render(subMesh, batch);
  22218. engine.setColorWrite(true);
  22219. }
  22220. // Overlay
  22221. if (this.renderOverlay) {
  22222. var currentMode = engine.getAlphaMode();
  22223. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22224. scene.getOutlineRenderer().render(subMesh, batch, true);
  22225. engine.setAlphaMode(currentMode);
  22226. }
  22227. this.onAfterRenderObservable.notifyObservers(this);
  22228. return this;
  22229. };
  22230. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22231. if (isInstance) {
  22232. effectiveMaterial.bindOnlyWorldMatrix(world);
  22233. }
  22234. return this;
  22235. };
  22236. /**
  22237. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22238. */
  22239. Mesh.prototype.getEmittedParticleSystems = function () {
  22240. var results = new Array();
  22241. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22242. var particleSystem = this.getScene().particleSystems[index];
  22243. if (particleSystem.emitter === this) {
  22244. results.push(particleSystem);
  22245. }
  22246. }
  22247. return results;
  22248. };
  22249. /**
  22250. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22251. */
  22252. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22253. var results = new Array();
  22254. var descendants = this.getDescendants();
  22255. descendants.push(this);
  22256. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22257. var particleSystem = this.getScene().particleSystems[index];
  22258. var emitter = particleSystem.emitter;
  22259. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22260. results.push(particleSystem);
  22261. }
  22262. }
  22263. return results;
  22264. };
  22265. Mesh.prototype._checkDelayState = function () {
  22266. var scene = this.getScene();
  22267. if (this._geometry) {
  22268. this._geometry.load(scene);
  22269. }
  22270. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22271. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22272. this._queueLoad(this, scene);
  22273. }
  22274. return this;
  22275. };
  22276. Mesh.prototype._queueLoad = function (mesh, scene) {
  22277. var _this = this;
  22278. scene._addPendingData(mesh);
  22279. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22280. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22281. if (data instanceof ArrayBuffer) {
  22282. _this._delayLoadingFunction(data, _this);
  22283. }
  22284. else {
  22285. _this._delayLoadingFunction(JSON.parse(data), _this);
  22286. }
  22287. _this.instances.forEach(function (instance) {
  22288. instance._syncSubMeshes();
  22289. });
  22290. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22291. scene._removePendingData(_this);
  22292. }, function () { }, scene.database, getBinaryData);
  22293. return this;
  22294. };
  22295. /**
  22296. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22297. */
  22298. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22299. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22300. return false;
  22301. }
  22302. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22303. return false;
  22304. }
  22305. this._checkDelayState();
  22306. return true;
  22307. };
  22308. /**
  22309. * Sets the mesh material by the material or multiMaterial `id` property.
  22310. * The material `id` is a string identifying the material or the multiMaterial.
  22311. * This method returns the Mesh.
  22312. */
  22313. Mesh.prototype.setMaterialByID = function (id) {
  22314. var materials = this.getScene().materials;
  22315. var index;
  22316. for (index = materials.length - 1; index > -1; index--) {
  22317. if (materials[index].id === id) {
  22318. this.material = materials[index];
  22319. return this;
  22320. }
  22321. }
  22322. // Multi
  22323. var multiMaterials = this.getScene().multiMaterials;
  22324. for (index = multiMaterials.length - 1; index > -1; index--) {
  22325. if (multiMaterials[index].id === id) {
  22326. this.material = multiMaterials[index];
  22327. return this;
  22328. }
  22329. }
  22330. return this;
  22331. };
  22332. /**
  22333. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22334. */
  22335. Mesh.prototype.getAnimatables = function () {
  22336. var results = [];
  22337. if (this.material) {
  22338. results.push(this.material);
  22339. }
  22340. if (this.skeleton) {
  22341. results.push(this.skeleton);
  22342. }
  22343. return results;
  22344. };
  22345. /**
  22346. * Modifies the mesh geometry according to the passed transformation matrix.
  22347. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22348. * The mesh normals are modified accordingly the same transformation.
  22349. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22350. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22351. * Returns the Mesh.
  22352. */
  22353. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22354. // Position
  22355. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22356. return this;
  22357. }
  22358. var submeshes = this.subMeshes.splice(0);
  22359. this._resetPointsArrayCache();
  22360. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22361. var temp = [];
  22362. var index;
  22363. for (index = 0; index < data.length; index += 3) {
  22364. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22365. }
  22366. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22367. // Normals
  22368. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22369. return this;
  22370. }
  22371. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22372. temp = [];
  22373. for (index = 0; index < data.length; index += 3) {
  22374. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22375. }
  22376. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22377. // flip faces?
  22378. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22379. this.flipFaces();
  22380. }
  22381. // Restore submeshes
  22382. this.releaseSubMeshes();
  22383. this.subMeshes = submeshes;
  22384. return this;
  22385. };
  22386. /**
  22387. * Modifies the mesh geometry according to its own current World Matrix.
  22388. * The mesh World Matrix is then reset.
  22389. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22390. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22391. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22392. * Returns the Mesh.
  22393. */
  22394. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22395. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22396. this.scaling.copyFromFloats(1, 1, 1);
  22397. this.position.copyFromFloats(0, 0, 0);
  22398. this.rotation.copyFromFloats(0, 0, 0);
  22399. //only if quaternion is already set
  22400. if (this.rotationQuaternion) {
  22401. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22402. }
  22403. this._worldMatrix = BABYLON.Matrix.Identity();
  22404. return this;
  22405. };
  22406. Object.defineProperty(Mesh.prototype, "_positions", {
  22407. // Cache
  22408. get: function () {
  22409. if (this._geometry) {
  22410. return this._geometry._positions;
  22411. }
  22412. return null;
  22413. },
  22414. enumerable: true,
  22415. configurable: true
  22416. });
  22417. Mesh.prototype._resetPointsArrayCache = function () {
  22418. if (this._geometry) {
  22419. this._geometry._resetPointsArrayCache();
  22420. }
  22421. return this;
  22422. };
  22423. Mesh.prototype._generatePointsArray = function () {
  22424. if (this._geometry) {
  22425. return this._geometry._generatePointsArray();
  22426. }
  22427. return false;
  22428. };
  22429. /**
  22430. * Returns a new Mesh object generated from the current mesh properties.
  22431. * This method must not get confused with createInstance().
  22432. * The parameter `name` is a string, the name given to the new mesh.
  22433. * The optional parameter `newParent` can be any Node object (default `null`).
  22434. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22435. * 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.
  22436. */
  22437. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22438. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22439. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22440. };
  22441. /**
  22442. * Disposes the mesh.
  22443. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22444. */
  22445. Mesh.prototype.dispose = function (doNotRecurse) {
  22446. var _this = this;
  22447. this.morphTargetManager = undefined;
  22448. if (this._geometry) {
  22449. this._geometry.releaseForMesh(this, true);
  22450. }
  22451. // Sources
  22452. var meshes = this.getScene().meshes;
  22453. meshes.forEach(function (mesh) {
  22454. if (mesh._source && mesh._source === _this) {
  22455. mesh._source = null;
  22456. }
  22457. });
  22458. this._source = null;
  22459. // Instances
  22460. if (this._instancesBuffer) {
  22461. this._instancesBuffer.dispose();
  22462. this._instancesBuffer = null;
  22463. }
  22464. while (this.instances.length) {
  22465. this.instances[0].dispose();
  22466. }
  22467. // Highlight layers.
  22468. var highlightLayers = this.getScene().highlightLayers;
  22469. for (var i = 0; i < highlightLayers.length; i++) {
  22470. var highlightLayer = highlightLayers[i];
  22471. if (highlightLayer) {
  22472. highlightLayer.removeMesh(this);
  22473. highlightLayer.removeExcludedMesh(this);
  22474. }
  22475. }
  22476. _super.prototype.dispose.call(this, doNotRecurse);
  22477. };
  22478. /**
  22479. * Modifies the mesh geometry according to a displacement map.
  22480. * 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.
  22481. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22482. * This method returns nothing.
  22483. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22484. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22485. * 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.
  22486. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22487. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22488. *
  22489. * Returns the Mesh.
  22490. */
  22491. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22492. var _this = this;
  22493. var scene = this.getScene();
  22494. var onload = function (img) {
  22495. // Getting height map data
  22496. var canvas = document.createElement("canvas");
  22497. var context = canvas.getContext("2d");
  22498. var heightMapWidth = img.width;
  22499. var heightMapHeight = img.height;
  22500. canvas.width = heightMapWidth;
  22501. canvas.height = heightMapHeight;
  22502. context.drawImage(img, 0, 0);
  22503. // Create VertexData from map data
  22504. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22505. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22506. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22507. //execute success callback, if set
  22508. if (onSuccess) {
  22509. onSuccess(_this);
  22510. }
  22511. };
  22512. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22513. return this;
  22514. };
  22515. /**
  22516. * Modifies the mesh geometry according to a displacementMap buffer.
  22517. * 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.
  22518. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22519. * This method returns nothing.
  22520. * 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.
  22521. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22522. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22523. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22524. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22525. *
  22526. * Returns the Mesh.
  22527. */
  22528. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22529. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22530. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22531. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22532. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22533. return this;
  22534. }
  22535. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22536. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22537. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22538. var position = BABYLON.Vector3.Zero();
  22539. var normal = BABYLON.Vector3.Zero();
  22540. var uv = BABYLON.Vector2.Zero();
  22541. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22542. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22543. for (var index = 0; index < positions.length; index += 3) {
  22544. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22545. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22546. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22547. // Compute height
  22548. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22549. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22550. var pos = (u + v * heightMapWidth) * 4;
  22551. var r = buffer[pos] / 255.0;
  22552. var g = buffer[pos + 1] / 255.0;
  22553. var b = buffer[pos + 2] / 255.0;
  22554. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22555. normal.normalize();
  22556. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22557. position = position.add(normal);
  22558. position.toArray(positions, index);
  22559. }
  22560. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22561. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22562. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22563. return this;
  22564. };
  22565. /**
  22566. * Modify the mesh to get a flat shading rendering.
  22567. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22568. * This method returns the Mesh.
  22569. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22570. */
  22571. Mesh.prototype.convertToFlatShadedMesh = function () {
  22572. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22573. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22574. var kinds = this.getVerticesDataKinds();
  22575. var vbs = [];
  22576. var data = [];
  22577. var newdata = [];
  22578. var updatableNormals = false;
  22579. var kindIndex;
  22580. var kind;
  22581. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22582. kind = kinds[kindIndex];
  22583. var vertexBuffer = this.getVertexBuffer(kind);
  22584. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22585. updatableNormals = vertexBuffer.isUpdatable();
  22586. kinds.splice(kindIndex, 1);
  22587. kindIndex--;
  22588. continue;
  22589. }
  22590. vbs[kind] = vertexBuffer;
  22591. data[kind] = vbs[kind].getData();
  22592. newdata[kind] = [];
  22593. }
  22594. // Save previous submeshes
  22595. var previousSubmeshes = this.subMeshes.slice(0);
  22596. var indices = this.getIndices();
  22597. var totalIndices = this.getTotalIndices();
  22598. // Generating unique vertices per face
  22599. var index;
  22600. for (index = 0; index < totalIndices; index++) {
  22601. var vertexIndex = indices[index];
  22602. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22603. kind = kinds[kindIndex];
  22604. var stride = vbs[kind].getStrideSize();
  22605. for (var offset = 0; offset < stride; offset++) {
  22606. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22607. }
  22608. }
  22609. }
  22610. // Updating faces & normal
  22611. var normals = [];
  22612. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22613. for (index = 0; index < totalIndices; index += 3) {
  22614. indices[index] = index;
  22615. indices[index + 1] = index + 1;
  22616. indices[index + 2] = index + 2;
  22617. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22618. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22619. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22620. var p1p2 = p1.subtract(p2);
  22621. var p3p2 = p3.subtract(p2);
  22622. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22623. // Store same normals for every vertex
  22624. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22625. normals.push(normal.x);
  22626. normals.push(normal.y);
  22627. normals.push(normal.z);
  22628. }
  22629. }
  22630. this.setIndices(indices);
  22631. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22632. // Updating vertex buffers
  22633. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22634. kind = kinds[kindIndex];
  22635. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22636. }
  22637. // Updating submeshes
  22638. this.releaseSubMeshes();
  22639. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22640. var previousOne = previousSubmeshes[submeshIndex];
  22641. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22642. }
  22643. this.synchronizeInstances();
  22644. return this;
  22645. };
  22646. /**
  22647. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22648. * In other words, more vertices, no more indices and a single bigger VBO.
  22649. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22650. * Returns the Mesh.
  22651. */
  22652. Mesh.prototype.convertToUnIndexedMesh = function () {
  22653. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22654. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22655. var kinds = this.getVerticesDataKinds();
  22656. var vbs = [];
  22657. var data = [];
  22658. var newdata = [];
  22659. var updatableNormals = false;
  22660. var kindIndex;
  22661. var kind;
  22662. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22663. kind = kinds[kindIndex];
  22664. var vertexBuffer = this.getVertexBuffer(kind);
  22665. vbs[kind] = vertexBuffer;
  22666. data[kind] = vbs[kind].getData();
  22667. newdata[kind] = [];
  22668. }
  22669. // Save previous submeshes
  22670. var previousSubmeshes = this.subMeshes.slice(0);
  22671. var indices = this.getIndices();
  22672. var totalIndices = this.getTotalIndices();
  22673. // Generating unique vertices per face
  22674. var index;
  22675. for (index = 0; index < totalIndices; index++) {
  22676. var vertexIndex = indices[index];
  22677. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22678. kind = kinds[kindIndex];
  22679. var stride = vbs[kind].getStrideSize();
  22680. for (var offset = 0; offset < stride; offset++) {
  22681. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22682. }
  22683. }
  22684. }
  22685. // Updating indices
  22686. for (index = 0; index < totalIndices; index += 3) {
  22687. indices[index] = index;
  22688. indices[index + 1] = index + 1;
  22689. indices[index + 2] = index + 2;
  22690. }
  22691. this.setIndices(indices);
  22692. // Updating vertex buffers
  22693. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22694. kind = kinds[kindIndex];
  22695. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22696. }
  22697. // Updating submeshes
  22698. this.releaseSubMeshes();
  22699. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22700. var previousOne = previousSubmeshes[submeshIndex];
  22701. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22702. }
  22703. this._unIndexed = true;
  22704. this.synchronizeInstances();
  22705. return this;
  22706. };
  22707. /**
  22708. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22709. * This method returns the Mesh.
  22710. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22711. */
  22712. Mesh.prototype.flipFaces = function (flipNormals) {
  22713. if (flipNormals === void 0) { flipNormals = false; }
  22714. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22715. var i;
  22716. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22717. for (i = 0; i < vertex_data.normals.length; i++) {
  22718. vertex_data.normals[i] *= -1;
  22719. }
  22720. }
  22721. var temp;
  22722. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22723. // reassign indices
  22724. temp = vertex_data.indices[i + 1];
  22725. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22726. vertex_data.indices[i + 2] = temp;
  22727. }
  22728. vertex_data.applyToMesh(this);
  22729. return this;
  22730. };
  22731. // Instances
  22732. /**
  22733. * Creates a new InstancedMesh object from the mesh model.
  22734. * An instance shares the same properties and the same material than its model.
  22735. * Only these properties of each instance can then be set individually :
  22736. * - position
  22737. * - rotation
  22738. * - rotationQuaternion
  22739. * - setPivotMatrix
  22740. * - scaling
  22741. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22742. * Warning : this method is not supported for Line mesh and LineSystem
  22743. */
  22744. Mesh.prototype.createInstance = function (name) {
  22745. return new BABYLON.InstancedMesh(name, this);
  22746. };
  22747. /**
  22748. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22749. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22750. * This method returns the Mesh.
  22751. */
  22752. Mesh.prototype.synchronizeInstances = function () {
  22753. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22754. var instance = this.instances[instanceIndex];
  22755. instance._syncSubMeshes();
  22756. }
  22757. return this;
  22758. };
  22759. /**
  22760. * Simplify the mesh according to the given array of settings.
  22761. * Function will return immediately and will simplify async. It returns the Mesh.
  22762. * @param settings a collection of simplification settings.
  22763. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22764. * @param type the type of simplification to run.
  22765. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22766. */
  22767. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22768. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22769. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22770. this.getScene().simplificationQueue.addTask({
  22771. settings: settings,
  22772. parallelProcessing: parallelProcessing,
  22773. mesh: this,
  22774. simplificationType: simplificationType,
  22775. successCallback: successCallback
  22776. });
  22777. return this;
  22778. };
  22779. /**
  22780. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22781. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22782. * This should be used together with the simplification to avoid disappearing triangles.
  22783. * Returns the Mesh.
  22784. * @param successCallback an optional success callback to be called after the optimization finished.
  22785. */
  22786. Mesh.prototype.optimizeIndices = function (successCallback) {
  22787. var _this = this;
  22788. var indices = this.getIndices();
  22789. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22790. var vectorPositions = [];
  22791. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22792. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22793. }
  22794. var dupes = [];
  22795. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22796. var realPos = vectorPositions.length - 1 - iteration;
  22797. var testedPosition = vectorPositions[realPos];
  22798. for (var j = 0; j < realPos; ++j) {
  22799. var againstPosition = vectorPositions[j];
  22800. if (testedPosition.equals(againstPosition)) {
  22801. dupes[realPos] = j;
  22802. break;
  22803. }
  22804. }
  22805. }, function () {
  22806. for (var i = 0; i < indices.length; ++i) {
  22807. indices[i] = dupes[indices[i]] || indices[i];
  22808. }
  22809. //indices are now reordered
  22810. var originalSubMeshes = _this.subMeshes.slice(0);
  22811. _this.setIndices(indices);
  22812. _this.subMeshes = originalSubMeshes;
  22813. if (successCallback) {
  22814. successCallback(_this);
  22815. }
  22816. });
  22817. return this;
  22818. };
  22819. Mesh.prototype.serialize = function (serializationObject) {
  22820. serializationObject.name = this.name;
  22821. serializationObject.id = this.id;
  22822. serializationObject.type = this.getClassName();
  22823. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22824. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22825. }
  22826. serializationObject.position = this.position.asArray();
  22827. if (this.rotationQuaternion) {
  22828. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22829. }
  22830. else if (this.rotation) {
  22831. serializationObject.rotation = this.rotation.asArray();
  22832. }
  22833. serializationObject.scaling = this.scaling.asArray();
  22834. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22835. serializationObject.isEnabled = this.isEnabled();
  22836. serializationObject.isVisible = this.isVisible;
  22837. serializationObject.infiniteDistance = this.infiniteDistance;
  22838. serializationObject.pickable = this.isPickable;
  22839. serializationObject.receiveShadows = this.receiveShadows;
  22840. serializationObject.billboardMode = this.billboardMode;
  22841. serializationObject.visibility = this.visibility;
  22842. serializationObject.checkCollisions = this.checkCollisions;
  22843. serializationObject.isBlocker = this.isBlocker;
  22844. // Parent
  22845. if (this.parent) {
  22846. serializationObject.parentId = this.parent.id;
  22847. }
  22848. // Geometry
  22849. var geometry = this._geometry;
  22850. if (geometry) {
  22851. var geometryId = geometry.id;
  22852. serializationObject.geometryId = geometryId;
  22853. // SubMeshes
  22854. serializationObject.subMeshes = [];
  22855. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22856. var subMesh = this.subMeshes[subIndex];
  22857. serializationObject.subMeshes.push({
  22858. materialIndex: subMesh.materialIndex,
  22859. verticesStart: subMesh.verticesStart,
  22860. verticesCount: subMesh.verticesCount,
  22861. indexStart: subMesh.indexStart,
  22862. indexCount: subMesh.indexCount
  22863. });
  22864. }
  22865. }
  22866. // Material
  22867. if (this.material) {
  22868. serializationObject.materialId = this.material.id;
  22869. }
  22870. else {
  22871. this.material = null;
  22872. }
  22873. // Morph targets
  22874. if (this.morphTargetManager) {
  22875. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22876. }
  22877. // Skeleton
  22878. if (this.skeleton) {
  22879. serializationObject.skeletonId = this.skeleton.id;
  22880. }
  22881. // Physics
  22882. //TODO implement correct serialization for physics impostors.
  22883. if (this.getPhysicsImpostor()) {
  22884. var impostor = this.getPhysicsImpostor();
  22885. serializationObject.physicsMass = impostor.getParam("mass");
  22886. serializationObject.physicsFriction = impostor.getParam("friction");
  22887. serializationObject.physicsRestitution = impostor.getParam("mass");
  22888. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22889. }
  22890. // Metadata
  22891. if (this.metadata) {
  22892. serializationObject.metadata = this.metadata;
  22893. }
  22894. // Instances
  22895. serializationObject.instances = [];
  22896. for (var index = 0; index < this.instances.length; index++) {
  22897. var instance = this.instances[index];
  22898. var serializationInstance = {
  22899. name: instance.name,
  22900. position: instance.position.asArray(),
  22901. scaling: instance.scaling.asArray()
  22902. };
  22903. if (instance.rotationQuaternion) {
  22904. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22905. }
  22906. else if (instance.rotation) {
  22907. serializationInstance.rotation = instance.rotation.asArray();
  22908. }
  22909. serializationObject.instances.push(serializationInstance);
  22910. // Animations
  22911. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22912. serializationInstance.ranges = instance.serializeAnimationRanges();
  22913. }
  22914. //
  22915. // Animations
  22916. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22917. serializationObject.ranges = this.serializeAnimationRanges();
  22918. // Layer mask
  22919. serializationObject.layerMask = this.layerMask;
  22920. // Alpha
  22921. serializationObject.alphaIndex = this.alphaIndex;
  22922. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22923. // Overlay
  22924. serializationObject.overlayAlpha = this.overlayAlpha;
  22925. serializationObject.overlayColor = this.overlayColor.asArray();
  22926. serializationObject.renderOverlay = this.renderOverlay;
  22927. // Fog
  22928. serializationObject.applyFog = this.applyFog;
  22929. // Action Manager
  22930. if (this.actionManager) {
  22931. serializationObject.actions = this.actionManager.serialize(this.name);
  22932. }
  22933. };
  22934. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22935. if (!this.geometry) {
  22936. return;
  22937. }
  22938. this._markSubMeshesAsAttributesDirty();
  22939. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22940. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22941. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22942. this.morphTargetManager = undefined;
  22943. return;
  22944. }
  22945. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22946. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22947. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22948. if (morphTarget.hasNormals) {
  22949. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22950. }
  22951. if (morphTarget.hasTangents) {
  22952. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22953. }
  22954. }
  22955. }
  22956. else {
  22957. var index = 0;
  22958. // Positions
  22959. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22960. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22961. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22962. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22963. }
  22964. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22965. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22966. }
  22967. index++;
  22968. }
  22969. }
  22970. };
  22971. // Statics
  22972. /**
  22973. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22974. * The parameter `parsedMesh` is the mesh to be copied.
  22975. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22976. */
  22977. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22978. var mesh;
  22979. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22980. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22981. }
  22982. else {
  22983. mesh = new Mesh(parsedMesh.name, scene);
  22984. }
  22985. mesh.id = parsedMesh.id;
  22986. if (BABYLON.Tags) {
  22987. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22988. }
  22989. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22990. if (parsedMesh.metadata !== undefined) {
  22991. mesh.metadata = parsedMesh.metadata;
  22992. }
  22993. if (parsedMesh.rotationQuaternion) {
  22994. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22995. }
  22996. else if (parsedMesh.rotation) {
  22997. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22998. }
  22999. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23000. if (parsedMesh.localMatrix) {
  23001. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23002. }
  23003. else if (parsedMesh.pivotMatrix) {
  23004. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23005. }
  23006. mesh.setEnabled(parsedMesh.isEnabled);
  23007. mesh.isVisible = parsedMesh.isVisible;
  23008. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23009. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23010. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23011. if (parsedMesh.applyFog !== undefined) {
  23012. mesh.applyFog = parsedMesh.applyFog;
  23013. }
  23014. if (parsedMesh.pickable !== undefined) {
  23015. mesh.isPickable = parsedMesh.pickable;
  23016. }
  23017. if (parsedMesh.alphaIndex !== undefined) {
  23018. mesh.alphaIndex = parsedMesh.alphaIndex;
  23019. }
  23020. mesh.receiveShadows = parsedMesh.receiveShadows;
  23021. mesh.billboardMode = parsedMesh.billboardMode;
  23022. if (parsedMesh.visibility !== undefined) {
  23023. mesh.visibility = parsedMesh.visibility;
  23024. }
  23025. mesh.checkCollisions = parsedMesh.checkCollisions;
  23026. if (parsedMesh.isBlocker !== undefined) {
  23027. mesh.isBlocker = parsedMesh.isBlocker;
  23028. }
  23029. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23030. // freezeWorldMatrix
  23031. if (parsedMesh.freezeWorldMatrix) {
  23032. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23033. }
  23034. // Parent
  23035. if (parsedMesh.parentId) {
  23036. mesh._waitingParentId = parsedMesh.parentId;
  23037. }
  23038. // Actions
  23039. if (parsedMesh.actions !== undefined) {
  23040. mesh._waitingActions = parsedMesh.actions;
  23041. }
  23042. // Overlay
  23043. if (parsedMesh.overlayAlpha !== undefined) {
  23044. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23045. }
  23046. if (parsedMesh.overlayColor !== undefined) {
  23047. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23048. }
  23049. if (parsedMesh.renderOverlay !== undefined) {
  23050. mesh.renderOverlay = parsedMesh.renderOverlay;
  23051. }
  23052. // Geometry
  23053. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23054. if (parsedMesh.delayLoadingFile) {
  23055. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23056. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23057. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23058. if (parsedMesh._binaryInfo) {
  23059. mesh._binaryInfo = parsedMesh._binaryInfo;
  23060. }
  23061. mesh._delayInfo = [];
  23062. if (parsedMesh.hasUVs) {
  23063. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23064. }
  23065. if (parsedMesh.hasUVs2) {
  23066. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23067. }
  23068. if (parsedMesh.hasUVs3) {
  23069. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23070. }
  23071. if (parsedMesh.hasUVs4) {
  23072. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23073. }
  23074. if (parsedMesh.hasUVs5) {
  23075. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23076. }
  23077. if (parsedMesh.hasUVs6) {
  23078. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23079. }
  23080. if (parsedMesh.hasColors) {
  23081. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23082. }
  23083. if (parsedMesh.hasMatricesIndices) {
  23084. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23085. }
  23086. if (parsedMesh.hasMatricesWeights) {
  23087. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23088. }
  23089. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23090. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23091. mesh._checkDelayState();
  23092. }
  23093. }
  23094. else {
  23095. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23096. }
  23097. // Material
  23098. if (parsedMesh.materialId) {
  23099. mesh.setMaterialByID(parsedMesh.materialId);
  23100. }
  23101. else {
  23102. mesh.material = null;
  23103. }
  23104. // Morph targets
  23105. if (parsedMesh.morphTargetManagerId > -1) {
  23106. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23107. }
  23108. // Skeleton
  23109. if (parsedMesh.skeletonId > -1) {
  23110. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23111. if (parsedMesh.numBoneInfluencers) {
  23112. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23113. }
  23114. }
  23115. // Animations
  23116. if (parsedMesh.animations) {
  23117. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23118. var parsedAnimation = parsedMesh.animations[animationIndex];
  23119. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23120. }
  23121. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23122. }
  23123. if (parsedMesh.autoAnimate) {
  23124. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23125. }
  23126. // Layer Mask
  23127. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23128. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23129. }
  23130. else {
  23131. mesh.layerMask = 0x0FFFFFFF;
  23132. }
  23133. // Physics
  23134. if (parsedMesh.physicsImpostor) {
  23135. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23136. mass: parsedMesh.physicsMass,
  23137. friction: parsedMesh.physicsFriction,
  23138. restitution: parsedMesh.physicsRestitution
  23139. }, scene);
  23140. }
  23141. // Instances
  23142. if (parsedMesh.instances) {
  23143. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23144. var parsedInstance = parsedMesh.instances[index];
  23145. var instance = mesh.createInstance(parsedInstance.name);
  23146. if (BABYLON.Tags) {
  23147. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23148. }
  23149. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23150. if (parsedInstance.parentId) {
  23151. instance._waitingParentId = parsedInstance.parentId;
  23152. }
  23153. if (parsedInstance.rotationQuaternion) {
  23154. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23155. }
  23156. else if (parsedInstance.rotation) {
  23157. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23158. }
  23159. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23160. instance.checkCollisions = mesh.checkCollisions;
  23161. if (parsedMesh.animations) {
  23162. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23163. parsedAnimation = parsedMesh.animations[animationIndex];
  23164. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23165. }
  23166. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23167. }
  23168. }
  23169. }
  23170. return mesh;
  23171. };
  23172. /**
  23173. * Creates a ribbon mesh.
  23174. * Please consider using the same method from the MeshBuilder class instead.
  23175. * 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.
  23176. *
  23177. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23178. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23179. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23180. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23181. * 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.
  23182. * 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.
  23183. * 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
  23184. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23185. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23187. */
  23188. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23189. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23190. pathArray: pathArray,
  23191. closeArray: closeArray,
  23192. closePath: closePath,
  23193. offset: offset,
  23194. updatable: updatable,
  23195. sideOrientation: sideOrientation,
  23196. instance: instance
  23197. }, scene);
  23198. };
  23199. /**
  23200. * Creates a plane polygonal mesh. By default, this is a disc.
  23201. * Please consider using the same method from the MeshBuilder class instead.
  23202. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23203. * 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.
  23204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23205. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23207. */
  23208. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23209. var options = {
  23210. radius: radius,
  23211. tessellation: tessellation,
  23212. sideOrientation: sideOrientation,
  23213. updatable: updatable
  23214. };
  23215. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23216. };
  23217. /**
  23218. * Creates a box mesh.
  23219. * Please consider using the same method from the MeshBuilder class instead.
  23220. * The parameter `size` sets the size (float) of each box side (default 1).
  23221. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23222. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23223. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23224. */
  23225. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23226. var options = {
  23227. size: size,
  23228. sideOrientation: sideOrientation,
  23229. updatable: updatable
  23230. };
  23231. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23232. };
  23233. /**
  23234. * Creates a sphere mesh.
  23235. * Please consider using the same method from the MeshBuilder class instead.
  23236. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23237. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23238. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23239. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23241. */
  23242. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23243. var options = {
  23244. segments: segments,
  23245. diameterX: diameter,
  23246. diameterY: diameter,
  23247. diameterZ: diameter,
  23248. sideOrientation: sideOrientation,
  23249. updatable: updatable
  23250. };
  23251. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23252. };
  23253. /**
  23254. * Creates a cylinder or a cone mesh.
  23255. * Please consider using the same method from the MeshBuilder class instead.
  23256. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23257. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23258. * 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.
  23259. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23260. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23261. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23262. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23264. */
  23265. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23266. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23267. if (scene !== undefined) {
  23268. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23269. updatable = scene;
  23270. }
  23271. scene = subdivisions;
  23272. subdivisions = 1;
  23273. }
  23274. var options = {
  23275. height: height,
  23276. diameterTop: diameterTop,
  23277. diameterBottom: diameterBottom,
  23278. tessellation: tessellation,
  23279. subdivisions: subdivisions,
  23280. sideOrientation: sideOrientation,
  23281. updatable: updatable
  23282. };
  23283. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23284. };
  23285. // Torus (Code from SharpDX.org)
  23286. /**
  23287. * Creates a torus mesh.
  23288. * Please consider using the same method from the MeshBuilder class instead.
  23289. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23290. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23291. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23292. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23293. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23295. */
  23296. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23297. var options = {
  23298. diameter: diameter,
  23299. thickness: thickness,
  23300. tessellation: tessellation,
  23301. sideOrientation: sideOrientation,
  23302. updatable: updatable
  23303. };
  23304. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23305. };
  23306. /**
  23307. * Creates a torus knot mesh.
  23308. * Please consider using the same method from the MeshBuilder class instead.
  23309. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23310. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23311. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23312. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23313. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23314. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23315. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23316. */
  23317. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23318. var options = {
  23319. radius: radius,
  23320. tube: tube,
  23321. radialSegments: radialSegments,
  23322. tubularSegments: tubularSegments,
  23323. p: p,
  23324. q: q,
  23325. sideOrientation: sideOrientation,
  23326. updatable: updatable
  23327. };
  23328. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23329. };
  23330. /**
  23331. * Creates a line mesh.
  23332. * Please consider using the same method from the MeshBuilder class instead.
  23333. * 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.
  23334. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23335. * The parameter `points` is an array successive Vector3.
  23336. * 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
  23337. * When updating an instance, remember that only point positions can change, not the number of points.
  23338. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23339. */
  23340. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23341. var options = {
  23342. points: points,
  23343. updatable: updatable,
  23344. instance: instance
  23345. };
  23346. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23347. };
  23348. /**
  23349. * Creates a dashed line mesh.
  23350. * Please consider using the same method from the MeshBuilder class instead.
  23351. * 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.
  23352. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23353. * The parameter `points` is an array successive Vector3.
  23354. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23355. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23356. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23357. * 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
  23358. * When updating an instance, remember that only point positions can change, not the number of points.
  23359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23360. */
  23361. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23362. var options = {
  23363. points: points,
  23364. dashSize: dashSize,
  23365. gapSize: gapSize,
  23366. dashNb: dashNb,
  23367. updatable: updatable,
  23368. instance: instance
  23369. };
  23370. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23371. };
  23372. /**
  23373. * Creates a polygon mesh.
  23374. * Please consider using the same method from the MeshBuilder class instead.
  23375. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23376. * 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.
  23377. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23378. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23379. * Remember you can only change the shape positions, not their number when updating a polygon.
  23380. */
  23381. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23382. var options = {
  23383. shape: shape,
  23384. holes: holes,
  23385. updatable: updatable,
  23386. sideOrientation: sideOrientation
  23387. };
  23388. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23389. };
  23390. /**
  23391. * Creates an extruded polygon mesh, with depth in the Y direction.
  23392. * Please consider using the same method from the MeshBuilder class instead.
  23393. */
  23394. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23395. var options = {
  23396. shape: shape,
  23397. holes: holes,
  23398. depth: depth,
  23399. updatable: updatable,
  23400. sideOrientation: sideOrientation
  23401. };
  23402. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23403. };
  23404. /**
  23405. * Creates an extruded shape mesh.
  23406. * 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.
  23407. * Please consider using the same method from the MeshBuilder class instead.
  23408. *
  23409. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23410. * 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
  23411. * extruded along the Z axis.
  23412. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23413. * 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.
  23414. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23415. * 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
  23416. * 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
  23417. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23418. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23419. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23420. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23421. */
  23422. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23423. var options = {
  23424. shape: shape,
  23425. path: path,
  23426. scale: scale,
  23427. rotation: rotation,
  23428. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23429. sideOrientation: sideOrientation,
  23430. instance: instance,
  23431. updatable: updatable
  23432. };
  23433. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23434. };
  23435. /**
  23436. * Creates an custom extruded shape mesh.
  23437. * 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.
  23438. * Please consider using the same method from the MeshBuilder class instead.
  23439. *
  23440. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23441. * 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
  23442. * extruded along the Z axis.
  23443. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23444. * 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
  23445. * and the distance of this point from the begining of the path :
  23446. * ```javascript
  23447. * var rotationFunction = function(i, distance) {
  23448. * // do things
  23449. * return rotationValue; }
  23450. * ```
  23451. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23452. * 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
  23453. * and the distance of this point from the begining of the path :
  23454. * ```javascript
  23455. * var scaleFunction = function(i, distance) {
  23456. * // do things
  23457. * return scaleValue;}
  23458. * ```
  23459. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23460. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23461. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23462. * 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
  23463. * 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
  23464. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23468. */
  23469. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23470. var options = {
  23471. shape: shape,
  23472. path: path,
  23473. scaleFunction: scaleFunction,
  23474. rotationFunction: rotationFunction,
  23475. ribbonCloseArray: ribbonCloseArray,
  23476. ribbonClosePath: ribbonClosePath,
  23477. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23478. sideOrientation: sideOrientation,
  23479. instance: instance,
  23480. updatable: updatable
  23481. };
  23482. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23483. };
  23484. /**
  23485. * Creates lathe mesh.
  23486. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23487. * Please consider using the same method from the MeshBuilder class instead.
  23488. * 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
  23489. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23490. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23491. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23493. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23494. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23495. */
  23496. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23497. var options = {
  23498. shape: shape,
  23499. radius: radius,
  23500. tessellation: tessellation,
  23501. sideOrientation: sideOrientation,
  23502. updatable: updatable
  23503. };
  23504. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23505. };
  23506. /**
  23507. * Creates a plane mesh.
  23508. * Please consider using the same method from the MeshBuilder class instead.
  23509. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23513. */
  23514. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23515. var options = {
  23516. size: size,
  23517. width: size,
  23518. height: size,
  23519. sideOrientation: sideOrientation,
  23520. updatable: updatable
  23521. };
  23522. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23523. };
  23524. /**
  23525. * Creates a ground mesh.
  23526. * Please consider using the same method from the MeshBuilder class instead.
  23527. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23528. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23529. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23530. */
  23531. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23532. var options = {
  23533. width: width,
  23534. height: height,
  23535. subdivisions: subdivisions,
  23536. updatable: updatable
  23537. };
  23538. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23539. };
  23540. /**
  23541. * Creates a tiled ground mesh.
  23542. * Please consider using the same method from the MeshBuilder class instead.
  23543. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23544. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23545. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23546. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23547. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23548. * numbers of subdivisions on the ground width and height of each tile.
  23549. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23550. */
  23551. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23552. var options = {
  23553. xmin: xmin,
  23554. zmin: zmin,
  23555. xmax: xmax,
  23556. zmax: zmax,
  23557. subdivisions: subdivisions,
  23558. precision: precision,
  23559. updatable: updatable
  23560. };
  23561. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23562. };
  23563. /**
  23564. * Creates a ground mesh from a height map.
  23565. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23566. * Please consider using the same method from the MeshBuilder class instead.
  23567. * The parameter `url` sets the URL of the height map image resource.
  23568. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23569. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23570. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23571. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23572. * 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).
  23573. * This function is passed the newly built mesh :
  23574. * ```javascript
  23575. * function(mesh) { // do things
  23576. * return; }
  23577. * ```
  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.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23581. var options = {
  23582. width: width,
  23583. height: height,
  23584. subdivisions: subdivisions,
  23585. minHeight: minHeight,
  23586. maxHeight: maxHeight,
  23587. updatable: updatable,
  23588. onReady: onReady
  23589. };
  23590. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23591. };
  23592. /**
  23593. * Creates a tube mesh.
  23594. * 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.
  23595. * Please consider using the same method from the MeshBuilder class instead.
  23596. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23597. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23598. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23599. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23600. * 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.
  23601. * It must return a radius value (positive float) :
  23602. * ```javascript
  23603. * var radiusFunction = function(i, distance) {
  23604. * // do things
  23605. * return radius; }
  23606. * ```
  23607. * 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
  23608. * 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
  23609. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23610. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23611. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23612. */
  23613. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23614. var options = {
  23615. path: path,
  23616. radius: radius,
  23617. tessellation: tessellation,
  23618. radiusFunction: radiusFunction,
  23619. arc: 1,
  23620. cap: cap,
  23621. updatable: updatable,
  23622. sideOrientation: sideOrientation,
  23623. instance: instance
  23624. };
  23625. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23626. };
  23627. /**
  23628. * Creates a polyhedron mesh.
  23629. * Please consider using the same method from the MeshBuilder class instead.
  23630. * 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
  23631. * to choose the wanted type.
  23632. * The parameter `size` (positive float, default 1) sets the polygon size.
  23633. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23634. * 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`.
  23635. * 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
  23636. * 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)`).
  23637. * 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
  23638. * 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.
  23639. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23640. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23642. */
  23643. Mesh.CreatePolyhedron = function (name, options, scene) {
  23644. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23645. };
  23646. /**
  23647. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23648. * Please consider using the same method from the MeshBuilder class instead.
  23649. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23650. * 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`).
  23651. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23652. * 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.
  23653. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23654. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23655. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23656. */
  23657. Mesh.CreateIcoSphere = function (name, options, scene) {
  23658. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23659. };
  23660. /**
  23661. * Creates a decal mesh.
  23662. * Please consider using the same method from the MeshBuilder class instead.
  23663. * 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.
  23664. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23665. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23666. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23667. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23668. */
  23669. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23670. var options = {
  23671. position: position,
  23672. normal: normal,
  23673. size: size,
  23674. angle: angle
  23675. };
  23676. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23677. };
  23678. // Skeletons
  23679. /**
  23680. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23681. */
  23682. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23683. var source;
  23684. if (!this._sourcePositions) {
  23685. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23686. this._sourcePositions = new Float32Array(source);
  23687. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23688. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23689. }
  23690. }
  23691. return this._sourcePositions;
  23692. };
  23693. /**
  23694. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23695. */
  23696. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23697. var source;
  23698. if (!this._sourceNormals) {
  23699. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23700. this._sourceNormals = new Float32Array(source);
  23701. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23702. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23703. }
  23704. }
  23705. return this._sourceNormals;
  23706. };
  23707. /**
  23708. * Updates the vertex buffer by applying transformation from the bones.
  23709. * Returns the Mesh.
  23710. *
  23711. * @param {skeleton} skeleton to apply
  23712. */
  23713. Mesh.prototype.applySkeleton = function (skeleton) {
  23714. if (!this.geometry) {
  23715. return this;
  23716. }
  23717. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23718. return this;
  23719. }
  23720. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23721. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23722. return this;
  23723. }
  23724. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23725. return this;
  23726. }
  23727. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23728. return this;
  23729. }
  23730. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23731. return this;
  23732. }
  23733. if (!this._sourcePositions) {
  23734. var submeshes = this.subMeshes.slice();
  23735. this.setPositionsForCPUSkinning();
  23736. this.subMeshes = submeshes;
  23737. }
  23738. if (!this._sourceNormals) {
  23739. this.setNormalsForCPUSkinning();
  23740. }
  23741. // positionsData checks for not being Float32Array will only pass at most once
  23742. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23743. if (!(positionsData instanceof Float32Array)) {
  23744. positionsData = new Float32Array(positionsData);
  23745. }
  23746. // normalsData checks for not being Float32Array will only pass at most once
  23747. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23748. if (!(normalsData instanceof Float32Array)) {
  23749. normalsData = new Float32Array(normalsData);
  23750. }
  23751. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23752. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23753. var needExtras = this.numBoneInfluencers > 4;
  23754. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23755. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23756. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23757. var tempVector3 = BABYLON.Vector3.Zero();
  23758. var finalMatrix = new BABYLON.Matrix();
  23759. var tempMatrix = new BABYLON.Matrix();
  23760. var matWeightIdx = 0;
  23761. var inf;
  23762. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23763. var weight;
  23764. for (inf = 0; inf < 4; inf++) {
  23765. weight = matricesWeightsData[matWeightIdx + inf];
  23766. if (weight > 0) {
  23767. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23768. finalMatrix.addToSelf(tempMatrix);
  23769. }
  23770. else
  23771. break;
  23772. }
  23773. if (needExtras) {
  23774. for (inf = 0; inf < 4; inf++) {
  23775. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23776. if (weight > 0) {
  23777. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23778. finalMatrix.addToSelf(tempMatrix);
  23779. }
  23780. else
  23781. break;
  23782. }
  23783. }
  23784. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23785. tempVector3.toArray(positionsData, index);
  23786. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23787. tempVector3.toArray(normalsData, index);
  23788. finalMatrix.reset();
  23789. }
  23790. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23791. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23792. return this;
  23793. };
  23794. // Tools
  23795. /**
  23796. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23797. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23798. */
  23799. Mesh.MinMax = function (meshes) {
  23800. var minVector = null;
  23801. var maxVector = null;
  23802. meshes.forEach(function (mesh, index, array) {
  23803. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23804. if (!minVector) {
  23805. minVector = boundingBox.minimumWorld;
  23806. maxVector = boundingBox.maximumWorld;
  23807. }
  23808. else {
  23809. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23810. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23811. }
  23812. });
  23813. return {
  23814. min: minVector,
  23815. max: maxVector
  23816. };
  23817. };
  23818. /**
  23819. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23820. */
  23821. Mesh.Center = function (meshesOrMinMaxVector) {
  23822. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23823. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23824. };
  23825. /**
  23826. * Merge the array of meshes into a single mesh for performance reasons.
  23827. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23828. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23829. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23830. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23831. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23832. */
  23833. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23834. if (disposeSource === void 0) { disposeSource = true; }
  23835. var index;
  23836. if (!allow32BitsIndices) {
  23837. var totalVertices = 0;
  23838. // Counting vertices
  23839. for (index = 0; index < meshes.length; index++) {
  23840. if (meshes[index]) {
  23841. totalVertices += meshes[index].getTotalVertices();
  23842. if (totalVertices > 65536) {
  23843. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23844. return null;
  23845. }
  23846. }
  23847. }
  23848. }
  23849. // Merge
  23850. var vertexData;
  23851. var otherVertexData;
  23852. var indiceArray = new Array();
  23853. var source;
  23854. for (index = 0; index < meshes.length; index++) {
  23855. if (meshes[index]) {
  23856. meshes[index].computeWorldMatrix(true);
  23857. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23858. otherVertexData.transform(meshes[index].getWorldMatrix());
  23859. if (vertexData) {
  23860. vertexData.merge(otherVertexData);
  23861. }
  23862. else {
  23863. vertexData = otherVertexData;
  23864. source = meshes[index];
  23865. }
  23866. if (subdivideWithSubMeshes) {
  23867. indiceArray.push(meshes[index].getTotalIndices());
  23868. }
  23869. }
  23870. }
  23871. if (!meshSubclass) {
  23872. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23873. }
  23874. vertexData.applyToMesh(meshSubclass);
  23875. // Setting properties
  23876. meshSubclass.material = source.material;
  23877. meshSubclass.checkCollisions = source.checkCollisions;
  23878. // Cleaning
  23879. if (disposeSource) {
  23880. for (index = 0; index < meshes.length; index++) {
  23881. if (meshes[index]) {
  23882. meshes[index].dispose();
  23883. }
  23884. }
  23885. }
  23886. // Subdivide
  23887. if (subdivideWithSubMeshes) {
  23888. //-- Suppresions du submesh global
  23889. meshSubclass.releaseSubMeshes();
  23890. index = 0;
  23891. var offset = 0;
  23892. //-- aplique la subdivision en fonction du tableau d'indices
  23893. while (index < indiceArray.length) {
  23894. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23895. offset += indiceArray[index];
  23896. index++;
  23897. }
  23898. }
  23899. return meshSubclass;
  23900. };
  23901. // Consts
  23902. Mesh._FRONTSIDE = 0;
  23903. Mesh._BACKSIDE = 1;
  23904. Mesh._DOUBLESIDE = 2;
  23905. Mesh._DEFAULTSIDE = 0;
  23906. Mesh._NO_CAP = 0;
  23907. Mesh._CAP_START = 1;
  23908. Mesh._CAP_END = 2;
  23909. Mesh._CAP_ALL = 3;
  23910. return Mesh;
  23911. }(BABYLON.AbstractMesh));
  23912. BABYLON.Mesh = Mesh;
  23913. })(BABYLON || (BABYLON = {}));
  23914. //# sourceMappingURL=babylon.mesh.js.map
  23915. var BABYLON;
  23916. (function (BABYLON) {
  23917. var BaseSubMesh = (function () {
  23918. function BaseSubMesh() {
  23919. }
  23920. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23921. get: function () {
  23922. return this._materialEffect;
  23923. },
  23924. enumerable: true,
  23925. configurable: true
  23926. });
  23927. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23928. if (this._materialEffect === effect) {
  23929. if (!effect) {
  23930. this._materialDefines = undefined;
  23931. }
  23932. return;
  23933. }
  23934. this._materialDefines = defines;
  23935. this._materialEffect = effect;
  23936. };
  23937. return BaseSubMesh;
  23938. }());
  23939. BABYLON.BaseSubMesh = BaseSubMesh;
  23940. var SubMesh = (function (_super) {
  23941. __extends(SubMesh, _super);
  23942. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23943. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23944. var _this = _super.call(this) || this;
  23945. _this.materialIndex = materialIndex;
  23946. _this.verticesStart = verticesStart;
  23947. _this.verticesCount = verticesCount;
  23948. _this.indexStart = indexStart;
  23949. _this.indexCount = indexCount;
  23950. _this._renderId = 0;
  23951. _this._mesh = mesh;
  23952. _this._renderingMesh = renderingMesh || mesh;
  23953. mesh.subMeshes.push(_this);
  23954. _this._trianglePlanes = [];
  23955. _this._id = mesh.subMeshes.length - 1;
  23956. if (createBoundingBox) {
  23957. _this.refreshBoundingInfo();
  23958. mesh.computeWorldMatrix(true);
  23959. }
  23960. return _this;
  23961. }
  23962. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23963. get: function () {
  23964. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23965. },
  23966. enumerable: true,
  23967. configurable: true
  23968. });
  23969. /**
  23970. * Returns the submesh BoudingInfo object.
  23971. */
  23972. SubMesh.prototype.getBoundingInfo = function () {
  23973. if (this.IsGlobal) {
  23974. return this._mesh.getBoundingInfo();
  23975. }
  23976. return this._boundingInfo;
  23977. };
  23978. /**
  23979. * Sets the submesh BoundingInfo.
  23980. * Return the SubMesh.
  23981. */
  23982. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23983. this._boundingInfo = boundingInfo;
  23984. return this;
  23985. };
  23986. /**
  23987. * Returns the mesh of the current submesh.
  23988. */
  23989. SubMesh.prototype.getMesh = function () {
  23990. return this._mesh;
  23991. };
  23992. /**
  23993. * Returns the rendering mesh of the submesh.
  23994. */
  23995. SubMesh.prototype.getRenderingMesh = function () {
  23996. return this._renderingMesh;
  23997. };
  23998. /**
  23999. * Returns the submesh material.
  24000. */
  24001. SubMesh.prototype.getMaterial = function () {
  24002. var rootMaterial = this._renderingMesh.material;
  24003. if (rootMaterial && rootMaterial.getSubMaterial) {
  24004. var multiMaterial = rootMaterial;
  24005. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24006. if (this._currentMaterial !== effectiveMaterial) {
  24007. this._currentMaterial = effectiveMaterial;
  24008. this._materialDefines = undefined;
  24009. }
  24010. return effectiveMaterial;
  24011. }
  24012. if (!rootMaterial) {
  24013. return this._mesh.getScene().defaultMaterial;
  24014. }
  24015. return rootMaterial;
  24016. };
  24017. // Methods
  24018. /**
  24019. * Sets a new updated BoundingInfo object to the submesh.
  24020. * Returns the SubMesh.
  24021. */
  24022. SubMesh.prototype.refreshBoundingInfo = function () {
  24023. this._lastColliderWorldVertices = null;
  24024. if (this.IsGlobal) {
  24025. return;
  24026. }
  24027. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24028. if (!data) {
  24029. this._boundingInfo = this._mesh._boundingInfo;
  24030. return;
  24031. }
  24032. var indices = this._renderingMesh.getIndices();
  24033. var extend;
  24034. //is this the only submesh?
  24035. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24036. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24037. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24038. }
  24039. else {
  24040. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24041. }
  24042. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24043. return this;
  24044. };
  24045. SubMesh.prototype._checkCollision = function (collider) {
  24046. return this.getBoundingInfo()._checkCollision(collider);
  24047. };
  24048. /**
  24049. * Updates the submesh BoundingInfo.
  24050. * Returns the Submesh.
  24051. */
  24052. SubMesh.prototype.updateBoundingInfo = function (world) {
  24053. if (!this.getBoundingInfo()) {
  24054. this.refreshBoundingInfo();
  24055. }
  24056. this.getBoundingInfo().update(world);
  24057. return this;
  24058. };
  24059. /**
  24060. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24061. * Boolean returned.
  24062. */
  24063. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24064. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24065. };
  24066. /**
  24067. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24068. * Boolean returned.
  24069. */
  24070. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24071. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24072. };
  24073. /**
  24074. * Renders the submesh.
  24075. * Returns it.
  24076. */
  24077. SubMesh.prototype.render = function (enableAlphaMode) {
  24078. this._renderingMesh.render(this, enableAlphaMode);
  24079. return this;
  24080. };
  24081. /**
  24082. * Returns a new Index Buffer.
  24083. * Type returned : WebGLBuffer.
  24084. */
  24085. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24086. if (!this._linesIndexBuffer) {
  24087. var linesIndices = [];
  24088. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24089. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24090. }
  24091. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24092. this.linesIndexCount = linesIndices.length;
  24093. }
  24094. return this._linesIndexBuffer;
  24095. };
  24096. /**
  24097. * True is the passed Ray intersects the submesh bounding box.
  24098. * Boolean returned.
  24099. */
  24100. SubMesh.prototype.canIntersects = function (ray) {
  24101. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24102. };
  24103. /**
  24104. * Returns an object IntersectionInfo.
  24105. */
  24106. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24107. var intersectInfo = null;
  24108. // LineMesh first as it's also a Mesh...
  24109. if (this._mesh instanceof BABYLON.LinesMesh) {
  24110. var lineMesh = this._mesh;
  24111. // Line test
  24112. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24113. var p0 = positions[indices[index]];
  24114. var p1 = positions[indices[index + 1]];
  24115. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24116. if (length < 0) {
  24117. continue;
  24118. }
  24119. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24120. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24121. if (fastCheck) {
  24122. break;
  24123. }
  24124. }
  24125. }
  24126. }
  24127. else {
  24128. // Triangles test
  24129. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24130. var p0 = positions[indices[index]];
  24131. var p1 = positions[indices[index + 1]];
  24132. var p2 = positions[indices[index + 2]];
  24133. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24134. if (currentIntersectInfo) {
  24135. if (currentIntersectInfo.distance < 0) {
  24136. continue;
  24137. }
  24138. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24139. intersectInfo = currentIntersectInfo;
  24140. intersectInfo.faceId = index / 3;
  24141. if (fastCheck) {
  24142. break;
  24143. }
  24144. }
  24145. }
  24146. }
  24147. }
  24148. return intersectInfo;
  24149. };
  24150. SubMesh.prototype._rebuild = function () {
  24151. if (this._linesIndexBuffer) {
  24152. this._linesIndexBuffer = null;
  24153. }
  24154. };
  24155. // Clone
  24156. /**
  24157. * Creates a new Submesh from the passed Mesh.
  24158. */
  24159. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24160. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24161. if (!this.IsGlobal) {
  24162. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24163. }
  24164. return result;
  24165. };
  24166. // Dispose
  24167. /**
  24168. * Disposes the Submesh.
  24169. * Returns nothing.
  24170. */
  24171. SubMesh.prototype.dispose = function () {
  24172. if (this._linesIndexBuffer) {
  24173. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24174. this._linesIndexBuffer = null;
  24175. }
  24176. // Remove from mesh
  24177. var index = this._mesh.subMeshes.indexOf(this);
  24178. this._mesh.subMeshes.splice(index, 1);
  24179. };
  24180. // Statics
  24181. /**
  24182. * Creates a new Submesh from the passed parameters :
  24183. * - materialIndex (integer) : the index of the main mesh material.
  24184. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24185. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24186. * - mesh (Mesh) : the main mesh to create the submesh from.
  24187. * - renderingMesh (optional Mesh) : rendering mesh.
  24188. */
  24189. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24190. var minVertexIndex = Number.MAX_VALUE;
  24191. var maxVertexIndex = -Number.MAX_VALUE;
  24192. renderingMesh = renderingMesh || mesh;
  24193. var indices = renderingMesh.getIndices();
  24194. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24195. var vertexIndex = indices[index];
  24196. if (vertexIndex < minVertexIndex)
  24197. minVertexIndex = vertexIndex;
  24198. if (vertexIndex > maxVertexIndex)
  24199. maxVertexIndex = vertexIndex;
  24200. }
  24201. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24202. };
  24203. return SubMesh;
  24204. }(BaseSubMesh));
  24205. BABYLON.SubMesh = SubMesh;
  24206. })(BABYLON || (BABYLON = {}));
  24207. //# sourceMappingURL=babylon.subMesh.js.map
  24208. var BABYLON;
  24209. (function (BABYLON) {
  24210. var EffectFallbacks = (function () {
  24211. function EffectFallbacks() {
  24212. this._defines = {};
  24213. this._currentRank = 32;
  24214. this._maxRank = -1;
  24215. }
  24216. EffectFallbacks.prototype.unBindMesh = function () {
  24217. this._mesh = null;
  24218. };
  24219. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24220. if (!this._defines[rank]) {
  24221. if (rank < this._currentRank) {
  24222. this._currentRank = rank;
  24223. }
  24224. if (rank > this._maxRank) {
  24225. this._maxRank = rank;
  24226. }
  24227. this._defines[rank] = new Array();
  24228. }
  24229. this._defines[rank].push(define);
  24230. };
  24231. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24232. this._meshRank = rank;
  24233. this._mesh = mesh;
  24234. if (rank < this._currentRank) {
  24235. this._currentRank = rank;
  24236. }
  24237. if (rank > this._maxRank) {
  24238. this._maxRank = rank;
  24239. }
  24240. };
  24241. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24242. get: function () {
  24243. return this._currentRank <= this._maxRank;
  24244. },
  24245. enumerable: true,
  24246. configurable: true
  24247. });
  24248. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24249. // First we try to switch to CPU skinning
  24250. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24251. this._mesh.computeBonesUsingShaders = false;
  24252. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24253. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24254. var scene = this._mesh.getScene();
  24255. for (var index = 0; index < scene.meshes.length; index++) {
  24256. var otherMesh = scene.meshes[index];
  24257. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24258. otherMesh.computeBonesUsingShaders = false;
  24259. }
  24260. }
  24261. }
  24262. else {
  24263. var currentFallbacks = this._defines[this._currentRank];
  24264. if (currentFallbacks) {
  24265. for (var index = 0; index < currentFallbacks.length; index++) {
  24266. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24267. }
  24268. }
  24269. this._currentRank++;
  24270. }
  24271. return currentDefines;
  24272. };
  24273. return EffectFallbacks;
  24274. }());
  24275. BABYLON.EffectFallbacks = EffectFallbacks;
  24276. var EffectCreationOptions = (function () {
  24277. function EffectCreationOptions() {
  24278. }
  24279. return EffectCreationOptions;
  24280. }());
  24281. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24282. var Effect = (function () {
  24283. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24284. var _this = this;
  24285. this.uniqueId = 0;
  24286. this.onCompileObservable = new BABYLON.Observable();
  24287. this.onErrorObservable = new BABYLON.Observable();
  24288. this.onBindObservable = new BABYLON.Observable();
  24289. this._uniformBuffersNames = {};
  24290. this._isReady = false;
  24291. this._compilationError = "";
  24292. this.name = baseName;
  24293. if (attributesNamesOrOptions.attributes) {
  24294. var options = attributesNamesOrOptions;
  24295. this._engine = uniformsNamesOrEngine;
  24296. this._attributesNames = options.attributes;
  24297. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24298. this._samplers = options.samplers;
  24299. this.defines = options.defines;
  24300. this.onError = options.onError;
  24301. this.onCompiled = options.onCompiled;
  24302. this._fallbacks = options.fallbacks;
  24303. this._indexParameters = options.indexParameters;
  24304. if (options.uniformBuffersNames) {
  24305. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24306. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24307. }
  24308. }
  24309. }
  24310. else {
  24311. this._engine = engine;
  24312. this.defines = defines;
  24313. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24314. this._samplers = samplers;
  24315. this._attributesNames = attributesNamesOrOptions;
  24316. this.onError = onError;
  24317. this.onCompiled = onCompiled;
  24318. this._indexParameters = indexParameters;
  24319. this._fallbacks = fallbacks;
  24320. }
  24321. this.uniqueId = Effect._uniqueIdSeed++;
  24322. var vertexSource;
  24323. var fragmentSource;
  24324. if (baseName.vertexElement) {
  24325. vertexSource = document.getElementById(baseName.vertexElement);
  24326. if (!vertexSource) {
  24327. vertexSource = baseName.vertexElement;
  24328. }
  24329. }
  24330. else {
  24331. vertexSource = baseName.vertex || baseName;
  24332. }
  24333. if (baseName.fragmentElement) {
  24334. fragmentSource = document.getElementById(baseName.fragmentElement);
  24335. if (!fragmentSource) {
  24336. fragmentSource = baseName.fragmentElement;
  24337. }
  24338. }
  24339. else {
  24340. fragmentSource = baseName.fragment || baseName;
  24341. }
  24342. this._loadVertexShader(vertexSource, function (vertexCode) {
  24343. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24344. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24345. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24346. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24347. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24348. if (baseName) {
  24349. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24350. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24351. }
  24352. else {
  24353. _this._vertexSourceCode = migratedVertexCode;
  24354. _this._fragmentSourceCode = migratedFragmentCode;
  24355. }
  24356. _this._prepareEffect();
  24357. });
  24358. });
  24359. });
  24360. });
  24361. });
  24362. });
  24363. }
  24364. Object.defineProperty(Effect.prototype, "key", {
  24365. get: function () {
  24366. return this._key;
  24367. },
  24368. enumerable: true,
  24369. configurable: true
  24370. });
  24371. // Properties
  24372. Effect.prototype.isReady = function () {
  24373. return this._isReady;
  24374. };
  24375. Effect.prototype.getEngine = function () {
  24376. return this._engine;
  24377. };
  24378. Effect.prototype.getProgram = function () {
  24379. return this._program;
  24380. };
  24381. Effect.prototype.getAttributesNames = function () {
  24382. return this._attributesNames;
  24383. };
  24384. Effect.prototype.getAttributeLocation = function (index) {
  24385. return this._attributes[index];
  24386. };
  24387. Effect.prototype.getAttributeLocationByName = function (name) {
  24388. var index = this._attributesNames.indexOf(name);
  24389. return this._attributes[index];
  24390. };
  24391. Effect.prototype.getAttributesCount = function () {
  24392. return this._attributes.length;
  24393. };
  24394. Effect.prototype.getUniformIndex = function (uniformName) {
  24395. return this._uniformsNames.indexOf(uniformName);
  24396. };
  24397. Effect.prototype.getUniform = function (uniformName) {
  24398. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24399. };
  24400. Effect.prototype.getSamplers = function () {
  24401. return this._samplers;
  24402. };
  24403. Effect.prototype.getCompilationError = function () {
  24404. return this._compilationError;
  24405. };
  24406. // Methods
  24407. Effect.prototype.executeWhenCompiled = function (func) {
  24408. if (this.isReady()) {
  24409. func(this);
  24410. return;
  24411. }
  24412. this.onCompileObservable.add(function (effect) {
  24413. func(effect);
  24414. });
  24415. };
  24416. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24417. // DOM element ?
  24418. if (vertex instanceof HTMLElement) {
  24419. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24420. callback(vertexCode);
  24421. return;
  24422. }
  24423. // Base64 encoded ?
  24424. if (vertex.substr(0, 7) === "base64:") {
  24425. var vertexBinary = window.atob(vertex.substr(7));
  24426. callback(vertexBinary);
  24427. return;
  24428. }
  24429. // Is in local store ?
  24430. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24431. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24432. return;
  24433. }
  24434. var vertexShaderUrl;
  24435. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24436. vertexShaderUrl = vertex;
  24437. }
  24438. else {
  24439. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24440. }
  24441. // Vertex shader
  24442. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24443. };
  24444. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24445. // DOM element ?
  24446. if (fragment instanceof HTMLElement) {
  24447. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24448. callback(fragmentCode);
  24449. return;
  24450. }
  24451. // Base64 encoded ?
  24452. if (fragment.substr(0, 7) === "base64:") {
  24453. var fragmentBinary = window.atob(fragment.substr(7));
  24454. callback(fragmentBinary);
  24455. return;
  24456. }
  24457. // Is in local store ?
  24458. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24459. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24460. return;
  24461. }
  24462. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24463. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24464. return;
  24465. }
  24466. var fragmentShaderUrl;
  24467. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24468. fragmentShaderUrl = fragment;
  24469. }
  24470. else {
  24471. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24472. }
  24473. // Fragment shader
  24474. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24475. };
  24476. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24477. // Rebuild shaders source code
  24478. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24479. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24480. vertexCode = prefix + vertexCode;
  24481. fragmentCode = prefix + fragmentCode;
  24482. // Number lines of shaders source code
  24483. var i = 2;
  24484. var regex = /\n/gm;
  24485. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24486. i = 2;
  24487. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24488. // Dump shaders name and formatted source code
  24489. if (this.name.vertexElement) {
  24490. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24491. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24492. }
  24493. else if (this.name.vertex) {
  24494. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24495. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24496. }
  24497. else {
  24498. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24499. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24500. }
  24501. };
  24502. ;
  24503. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24504. var preparedSourceCode = this._processPrecision(sourceCode);
  24505. if (this._engine.webGLVersion == 1) {
  24506. callback(preparedSourceCode);
  24507. return;
  24508. }
  24509. // Already converted
  24510. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24511. callback(preparedSourceCode.replace("#version 300 es", ""));
  24512. return;
  24513. }
  24514. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24515. // Remove extensions
  24516. // #extension GL_OES_standard_derivatives : enable
  24517. // #extension GL_EXT_shader_texture_lod : enable
  24518. // #extension GL_EXT_frag_depth : enable
  24519. // #extension GL_EXT_draw_buffers : require
  24520. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24521. var result = preparedSourceCode.replace(regex, "");
  24522. // Migrate to GLSL v300
  24523. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24524. result = result.replace(/attribute[ \t]/g, "in ");
  24525. result = result.replace(/[ \t]attribute/g, " in");
  24526. if (isFragment) {
  24527. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24528. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24529. result = result.replace(/texture2D\(/g, "texture(");
  24530. result = result.replace(/textureCube\(/g, "texture(");
  24531. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24532. result = result.replace(/gl_FragColor/g, "glFragColor");
  24533. result = result.replace(/gl_FragData/g, "glFragData");
  24534. result = result.replace(/void\s+?main\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  24535. }
  24536. callback(result);
  24537. };
  24538. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24539. var _this = this;
  24540. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24541. var match = regex.exec(sourceCode);
  24542. var returnValue = new String(sourceCode);
  24543. while (match != null) {
  24544. var includeFile = match[1];
  24545. // Uniform declaration
  24546. if (includeFile.indexOf("__decl__") !== -1) {
  24547. includeFile = includeFile.replace(/__decl__/, "");
  24548. if (this._engine.supportsUniformBuffers) {
  24549. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24550. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24551. }
  24552. includeFile = includeFile + "Declaration";
  24553. }
  24554. if (Effect.IncludesShadersStore[includeFile]) {
  24555. // Substitution
  24556. var includeContent = Effect.IncludesShadersStore[includeFile];
  24557. if (match[2]) {
  24558. var splits = match[3].split(",");
  24559. for (var index = 0; index < splits.length; index += 2) {
  24560. var source = new RegExp(splits[index], "g");
  24561. var dest = splits[index + 1];
  24562. includeContent = includeContent.replace(source, dest);
  24563. }
  24564. }
  24565. if (match[4]) {
  24566. var indexString = match[5];
  24567. if (indexString.indexOf("..") !== -1) {
  24568. var indexSplits = indexString.split("..");
  24569. var minIndex = parseInt(indexSplits[0]);
  24570. var maxIndex = parseInt(indexSplits[1]);
  24571. var sourceIncludeContent = includeContent.slice(0);
  24572. includeContent = "";
  24573. if (isNaN(maxIndex)) {
  24574. maxIndex = this._indexParameters[indexSplits[1]];
  24575. }
  24576. for (var i = minIndex; i < maxIndex; i++) {
  24577. if (!this._engine.supportsUniformBuffers) {
  24578. // Ubo replacement
  24579. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24580. return p1 + "{X}";
  24581. });
  24582. }
  24583. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24584. }
  24585. }
  24586. else {
  24587. if (!this._engine.supportsUniformBuffers) {
  24588. // Ubo replacement
  24589. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24590. return p1 + "{X}";
  24591. });
  24592. }
  24593. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24594. }
  24595. }
  24596. // Replace
  24597. returnValue = returnValue.replace(match[0], includeContent);
  24598. }
  24599. else {
  24600. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24601. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24602. Effect.IncludesShadersStore[includeFile] = fileContent;
  24603. _this._processIncludes(returnValue, callback);
  24604. });
  24605. return;
  24606. }
  24607. match = regex.exec(sourceCode);
  24608. }
  24609. callback(returnValue);
  24610. };
  24611. Effect.prototype._processPrecision = function (source) {
  24612. if (source.indexOf("precision highp float") === -1) {
  24613. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24614. source = "precision mediump float;\n" + source;
  24615. }
  24616. else {
  24617. source = "precision highp float;\n" + source;
  24618. }
  24619. }
  24620. else {
  24621. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24622. source = source.replace("precision highp float", "precision mediump float");
  24623. }
  24624. }
  24625. return source;
  24626. };
  24627. Effect.prototype._prepareEffect = function () {
  24628. var attributesNames = this._attributesNames;
  24629. var defines = this.defines;
  24630. var fallbacks = this._fallbacks;
  24631. this._valueCache = {};
  24632. try {
  24633. var engine = this._engine;
  24634. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24635. if (engine.webGLVersion > 1) {
  24636. for (var name in this._uniformBuffersNames) {
  24637. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24638. }
  24639. }
  24640. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24641. this._attributes = engine.getAttributes(this._program, attributesNames);
  24642. var index;
  24643. for (index = 0; index < this._samplers.length; index++) {
  24644. var sampler = this.getUniform(this._samplers[index]);
  24645. if (sampler == null) {
  24646. this._samplers.splice(index, 1);
  24647. index--;
  24648. }
  24649. }
  24650. engine.bindSamplers(this);
  24651. this._compilationError = "";
  24652. this._isReady = true;
  24653. if (this.onCompiled) {
  24654. this.onCompiled(this);
  24655. }
  24656. this.onCompileObservable.notifyObservers(this);
  24657. this.onCompileObservable.clear();
  24658. // Unbind mesh reference in fallbacks
  24659. if (this._fallbacks) {
  24660. this._fallbacks.unBindMesh();
  24661. }
  24662. }
  24663. catch (e) {
  24664. this._compilationError = e.message;
  24665. // Let's go through fallbacks then
  24666. BABYLON.Tools.Error("Unable to compile effect:");
  24667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24668. return " " + uniform;
  24669. }));
  24670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24671. return " " + attribute;
  24672. }));
  24673. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24674. BABYLON.Tools.Error("Error: " + this._compilationError);
  24675. if (fallbacks && fallbacks.isMoreFallbacks) {
  24676. BABYLON.Tools.Error("Trying next fallback.");
  24677. this.defines = fallbacks.reduce(this.defines);
  24678. this._prepareEffect();
  24679. }
  24680. else {
  24681. if (this.onError) {
  24682. this.onError(this, this._compilationError);
  24683. }
  24684. this.onErrorObservable.notifyObservers(this);
  24685. this.onErrorObservable.clear();
  24686. // Unbind mesh reference in fallbacks
  24687. if (this._fallbacks) {
  24688. this._fallbacks.unBindMesh();
  24689. }
  24690. }
  24691. }
  24692. };
  24693. Object.defineProperty(Effect.prototype, "isSupported", {
  24694. get: function () {
  24695. return this._compilationError === "";
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. Effect.prototype._bindTexture = function (channel, texture) {
  24701. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24702. };
  24703. Effect.prototype.setTexture = function (channel, texture) {
  24704. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24705. };
  24706. Effect.prototype.setTextureArray = function (channel, textures) {
  24707. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24708. var initialPos = this._samplers.indexOf(channel);
  24709. for (var index = 1; index < textures.length; index++) {
  24710. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24711. }
  24712. }
  24713. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24714. };
  24715. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24716. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24717. };
  24718. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24719. var cache = this._valueCache[uniformName];
  24720. var flag = matrix.updateFlag;
  24721. if (cache !== undefined && cache === flag) {
  24722. return false;
  24723. }
  24724. this._valueCache[uniformName] = flag;
  24725. return true;
  24726. };
  24727. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24728. var cache = this._valueCache[uniformName];
  24729. if (!cache) {
  24730. cache = [x, y];
  24731. this._valueCache[uniformName] = cache;
  24732. return true;
  24733. }
  24734. var changed = false;
  24735. if (cache[0] !== x) {
  24736. cache[0] = x;
  24737. changed = true;
  24738. }
  24739. if (cache[1] !== y) {
  24740. cache[1] = y;
  24741. changed = true;
  24742. }
  24743. return changed;
  24744. };
  24745. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24746. var cache = this._valueCache[uniformName];
  24747. if (!cache) {
  24748. cache = [x, y, z];
  24749. this._valueCache[uniformName] = cache;
  24750. return true;
  24751. }
  24752. var changed = false;
  24753. if (cache[0] !== x) {
  24754. cache[0] = x;
  24755. changed = true;
  24756. }
  24757. if (cache[1] !== y) {
  24758. cache[1] = y;
  24759. changed = true;
  24760. }
  24761. if (cache[2] !== z) {
  24762. cache[2] = z;
  24763. changed = true;
  24764. }
  24765. return changed;
  24766. };
  24767. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24768. var cache = this._valueCache[uniformName];
  24769. if (!cache) {
  24770. cache = [x, y, z, w];
  24771. this._valueCache[uniformName] = cache;
  24772. return true;
  24773. }
  24774. var changed = false;
  24775. if (cache[0] !== x) {
  24776. cache[0] = x;
  24777. changed = true;
  24778. }
  24779. if (cache[1] !== y) {
  24780. cache[1] = y;
  24781. changed = true;
  24782. }
  24783. if (cache[2] !== z) {
  24784. cache[2] = z;
  24785. changed = true;
  24786. }
  24787. if (cache[3] !== w) {
  24788. cache[3] = w;
  24789. changed = true;
  24790. }
  24791. return changed;
  24792. };
  24793. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24794. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24795. return;
  24796. }
  24797. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24798. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24799. };
  24800. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24801. this._engine.bindUniformBlock(this._program, blockName, index);
  24802. };
  24803. Effect.prototype.setIntArray = function (uniformName, array) {
  24804. this._valueCache[uniformName] = null;
  24805. this._engine.setIntArray(this.getUniform(uniformName), array);
  24806. return this;
  24807. };
  24808. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24809. this._valueCache[uniformName] = null;
  24810. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24811. return this;
  24812. };
  24813. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24814. this._valueCache[uniformName] = null;
  24815. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24816. return this;
  24817. };
  24818. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24819. this._valueCache[uniformName] = null;
  24820. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24821. return this;
  24822. };
  24823. Effect.prototype.setFloatArray = function (uniformName, array) {
  24824. this._valueCache[uniformName] = null;
  24825. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24826. return this;
  24827. };
  24828. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24829. this._valueCache[uniformName] = null;
  24830. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24831. return this;
  24832. };
  24833. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24834. this._valueCache[uniformName] = null;
  24835. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24836. return this;
  24837. };
  24838. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24839. this._valueCache[uniformName] = null;
  24840. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24841. return this;
  24842. };
  24843. Effect.prototype.setArray = function (uniformName, array) {
  24844. this._valueCache[uniformName] = null;
  24845. this._engine.setArray(this.getUniform(uniformName), array);
  24846. return this;
  24847. };
  24848. Effect.prototype.setArray2 = function (uniformName, array) {
  24849. this._valueCache[uniformName] = null;
  24850. this._engine.setArray2(this.getUniform(uniformName), array);
  24851. return this;
  24852. };
  24853. Effect.prototype.setArray3 = function (uniformName, array) {
  24854. this._valueCache[uniformName] = null;
  24855. this._engine.setArray3(this.getUniform(uniformName), array);
  24856. return this;
  24857. };
  24858. Effect.prototype.setArray4 = function (uniformName, array) {
  24859. this._valueCache[uniformName] = null;
  24860. this._engine.setArray4(this.getUniform(uniformName), array);
  24861. return this;
  24862. };
  24863. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24864. if (!matrices) {
  24865. return;
  24866. }
  24867. this._valueCache[uniformName] = null;
  24868. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24869. return this;
  24870. };
  24871. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24872. if (this._cacheMatrix(uniformName, matrix)) {
  24873. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24874. }
  24875. return this;
  24876. };
  24877. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24878. this._valueCache[uniformName] = null;
  24879. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24880. return this;
  24881. };
  24882. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24883. this._valueCache[uniformName] = null;
  24884. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24885. return this;
  24886. };
  24887. Effect.prototype.setFloat = function (uniformName, value) {
  24888. var cache = this._valueCache[uniformName];
  24889. if (cache !== undefined && cache === value)
  24890. return this;
  24891. this._valueCache[uniformName] = value;
  24892. this._engine.setFloat(this.getUniform(uniformName), value);
  24893. return this;
  24894. };
  24895. Effect.prototype.setBool = function (uniformName, bool) {
  24896. var cache = this._valueCache[uniformName];
  24897. if (cache !== undefined && cache === bool)
  24898. return this;
  24899. this._valueCache[uniformName] = bool;
  24900. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24901. return this;
  24902. };
  24903. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24904. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24905. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24906. }
  24907. return this;
  24908. };
  24909. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24910. if (this._cacheFloat2(uniformName, x, y)) {
  24911. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24912. }
  24913. return this;
  24914. };
  24915. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24916. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24917. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24918. }
  24919. return this;
  24920. };
  24921. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24922. if (this._cacheFloat3(uniformName, x, y, z)) {
  24923. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24924. }
  24925. return this;
  24926. };
  24927. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24928. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24929. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24930. }
  24931. return this;
  24932. };
  24933. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24934. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24935. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24936. }
  24937. return this;
  24938. };
  24939. Effect.prototype.setColor3 = function (uniformName, color3) {
  24940. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24941. this._engine.setColor3(this.getUniform(uniformName), color3);
  24942. }
  24943. return this;
  24944. };
  24945. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24946. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24947. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24948. }
  24949. return this;
  24950. };
  24951. Effect.ResetCache = function () {
  24952. Effect._baseCache = {};
  24953. };
  24954. Effect._uniqueIdSeed = 0;
  24955. Effect._baseCache = {};
  24956. // Statics
  24957. Effect.ShadersStore = {};
  24958. Effect.IncludesShadersStore = {};
  24959. return Effect;
  24960. }());
  24961. BABYLON.Effect = Effect;
  24962. })(BABYLON || (BABYLON = {}));
  24963. //# sourceMappingURL=babylon.effect.js.map
  24964. var BABYLON;
  24965. (function (BABYLON) {
  24966. var MaterialHelper = (function () {
  24967. function MaterialHelper() {
  24968. }
  24969. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24970. defines._needUVs = true;
  24971. defines[key] = true;
  24972. if (texture.getTextureMatrix().isIdentity(true)) {
  24973. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24974. if (texture.coordinatesIndex === 0) {
  24975. defines["MAINUV1"] = true;
  24976. }
  24977. else {
  24978. defines["MAINUV2"] = true;
  24979. }
  24980. }
  24981. else {
  24982. defines[key + "DIRECTUV"] = 0;
  24983. }
  24984. };
  24985. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24986. var matrix = texture.getTextureMatrix();
  24987. if (!matrix.isIdentity(true)) {
  24988. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24989. }
  24990. };
  24991. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24992. if (defines._areMiscDirty) {
  24993. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24994. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24995. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24996. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24997. }
  24998. };
  24999. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25000. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25001. var changed = false;
  25002. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25003. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25004. changed = true;
  25005. }
  25006. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25007. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25008. changed = true;
  25009. }
  25010. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25011. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25012. changed = true;
  25013. }
  25014. if (defines["INSTANCES"] !== useInstances) {
  25015. defines["INSTANCES"] = useInstances;
  25016. changed = true;
  25017. }
  25018. if (changed) {
  25019. defines.markAsUnprocessed();
  25020. }
  25021. };
  25022. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25023. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25024. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25025. return false;
  25026. }
  25027. defines._normals = defines._needNormals;
  25028. defines._uvs = defines._needUVs;
  25029. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25030. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25031. defines["TANGENT"] = true;
  25032. }
  25033. if (defines._needUVs) {
  25034. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25035. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25036. }
  25037. else {
  25038. defines["UV1"] = false;
  25039. defines["UV2"] = false;
  25040. }
  25041. if (useVertexColor) {
  25042. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25043. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25044. }
  25045. if (useBones) {
  25046. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25047. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25048. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25049. }
  25050. else {
  25051. defines["NUM_BONE_INFLUENCERS"] = 0;
  25052. defines["BonesPerMesh"] = 0;
  25053. }
  25054. }
  25055. if (useMorphTargets) {
  25056. if (mesh.morphTargetManager) {
  25057. var manager = mesh.morphTargetManager;
  25058. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25059. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25060. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25061. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25062. }
  25063. else {
  25064. defines["MORPHTARGETS_TANGENT"] = false;
  25065. defines["MORPHTARGETS_NORMAL"] = false;
  25066. defines["MORPHTARGETS"] = false;
  25067. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25068. }
  25069. }
  25070. return true;
  25071. };
  25072. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25073. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25074. if (disableLighting === void 0) { disableLighting = false; }
  25075. if (!defines._areLightsDirty) {
  25076. return defines._needNormals;
  25077. }
  25078. var lightIndex = 0;
  25079. var needNormals = false;
  25080. var needRebuild = false;
  25081. var lightmapMode = false;
  25082. var shadowEnabled = false;
  25083. var specularEnabled = false;
  25084. if (scene.lightsEnabled && !disableLighting) {
  25085. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25086. var light = _a[_i];
  25087. needNormals = true;
  25088. if (defines["LIGHT" + lightIndex] === undefined) {
  25089. needRebuild = true;
  25090. }
  25091. defines["LIGHT" + lightIndex] = true;
  25092. defines["SPOTLIGHT" + lightIndex] = false;
  25093. defines["HEMILIGHT" + lightIndex] = false;
  25094. defines["POINTLIGHT" + lightIndex] = false;
  25095. defines["DIRLIGHT" + lightIndex] = false;
  25096. var type;
  25097. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25098. type = "SPOTLIGHT" + lightIndex;
  25099. }
  25100. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25101. type = "HEMILIGHT" + lightIndex;
  25102. }
  25103. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25104. type = "POINTLIGHT" + lightIndex;
  25105. }
  25106. else {
  25107. type = "DIRLIGHT" + lightIndex;
  25108. }
  25109. defines[type] = true;
  25110. // Specular
  25111. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25112. specularEnabled = true;
  25113. }
  25114. // Shadows
  25115. defines["SHADOW" + lightIndex] = false;
  25116. defines["SHADOWPCF" + lightIndex] = false;
  25117. defines["SHADOWESM" + lightIndex] = false;
  25118. defines["SHADOWCUBE" + lightIndex] = false;
  25119. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25120. var shadowGenerator = light.getShadowGenerator();
  25121. if (shadowGenerator) {
  25122. shadowEnabled = true;
  25123. shadowGenerator.prepareDefines(defines, lightIndex);
  25124. }
  25125. }
  25126. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25127. lightmapMode = true;
  25128. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25129. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25130. }
  25131. else {
  25132. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25133. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25134. }
  25135. lightIndex++;
  25136. if (lightIndex === maxSimultaneousLights)
  25137. break;
  25138. }
  25139. }
  25140. defines["SPECULARTERM"] = specularEnabled;
  25141. defines["SHADOWS"] = shadowEnabled;
  25142. // Resetting all other lights if any
  25143. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25144. if (defines["LIGHT" + index] !== undefined) {
  25145. defines["LIGHT" + index] = false;
  25146. defines["HEMILIGHT" + lightIndex] = false;
  25147. defines["POINTLIGHT" + lightIndex] = false;
  25148. defines["DIRLIGHT" + lightIndex] = false;
  25149. defines["SPOTLIGHT" + lightIndex] = false;
  25150. defines["SHADOW" + lightIndex] = false;
  25151. }
  25152. }
  25153. var caps = scene.getEngine().getCaps();
  25154. if (defines["SHADOWFLOAT"] === undefined) {
  25155. needRebuild = true;
  25156. }
  25157. defines["SHADOWFLOAT"] = shadowEnabled &&
  25158. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25159. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25160. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25161. if (needRebuild) {
  25162. defines.rebuild();
  25163. }
  25164. return needNormals;
  25165. };
  25166. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25167. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25168. var uniformsList, uniformBuffersList, samplersList, defines;
  25169. if (uniformsListOrOptions.uniformsNames) {
  25170. var options = uniformsListOrOptions;
  25171. uniformsList = options.uniformsNames;
  25172. uniformBuffersList = options.uniformBuffersNames;
  25173. samplersList = options.samplers;
  25174. defines = options.defines;
  25175. maxSimultaneousLights = options.maxSimultaneousLights;
  25176. }
  25177. else {
  25178. uniformsList = uniformsListOrOptions;
  25179. }
  25180. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25181. if (!defines["LIGHT" + lightIndex]) {
  25182. break;
  25183. }
  25184. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25185. if (uniformBuffersList) {
  25186. uniformBuffersList.push("Light" + lightIndex);
  25187. }
  25188. samplersList.push("shadowSampler" + lightIndex);
  25189. }
  25190. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25191. uniformsList.push("morphTargetInfluences");
  25192. }
  25193. };
  25194. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25195. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25196. if (!defines["SHADOWS"]) {
  25197. return;
  25198. }
  25199. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25200. if (!defines["LIGHT" + lightIndex]) {
  25201. break;
  25202. }
  25203. if (lightIndex > 0) {
  25204. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25205. }
  25206. if (defines["SHADOW" + lightIndex]) {
  25207. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25208. }
  25209. if (defines["SHADOWPCF" + lightIndex]) {
  25210. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25211. }
  25212. if (defines["SHADOWESM" + lightIndex]) {
  25213. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25214. }
  25215. }
  25216. };
  25217. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25218. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25219. if (influencers > 0) {
  25220. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25221. var manager = mesh.morphTargetManager;
  25222. var normal = manager.supportsNormals && defines["NORMAL"];
  25223. var tangent = manager.supportsTangents && defines["TANGENT"];
  25224. for (var index = 0; index < influencers; index++) {
  25225. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25226. if (normal) {
  25227. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25228. }
  25229. if (tangent) {
  25230. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25231. }
  25232. if (attribs.length > maxAttributesCount) {
  25233. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25234. }
  25235. }
  25236. }
  25237. };
  25238. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25239. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25240. fallbacks.addCPUSkinningFallback(0, mesh);
  25241. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25242. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25243. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25244. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25245. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25246. }
  25247. }
  25248. };
  25249. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25250. if (defines["INSTANCES"]) {
  25251. attribs.push("world0");
  25252. attribs.push("world1");
  25253. attribs.push("world2");
  25254. attribs.push("world3");
  25255. }
  25256. };
  25257. // Bindings
  25258. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25259. if (light.shadowEnabled && mesh.receiveShadows) {
  25260. var shadowGenerator = light.getShadowGenerator();
  25261. if (shadowGenerator) {
  25262. shadowGenerator.bindShadowLight(lightIndex, effect);
  25263. }
  25264. }
  25265. };
  25266. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25267. light.transferToEffect(effect, lightIndex + "");
  25268. };
  25269. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25270. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25271. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25272. var lightIndex = 0;
  25273. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25274. var light = _a[_i];
  25275. var scaledIntensity = light.getScaledIntensity();
  25276. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25277. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25278. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25279. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25280. if (defines["SPECULARTERM"]) {
  25281. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25282. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25283. }
  25284. // Shadows
  25285. if (scene.shadowsEnabled) {
  25286. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25287. }
  25288. light._uniformBuffer.update();
  25289. lightIndex++;
  25290. if (lightIndex === maxSimultaneousLights)
  25291. break;
  25292. }
  25293. };
  25294. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25295. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25296. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25297. effect.setColor3("vFogColor", scene.fogColor);
  25298. }
  25299. };
  25300. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25301. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25302. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25303. if (matrices) {
  25304. effect.setMatrices("mBones", matrices);
  25305. }
  25306. }
  25307. };
  25308. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25309. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25310. return;
  25311. }
  25312. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25313. };
  25314. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25315. if (defines["LOGARITHMICDEPTH"]) {
  25316. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25317. }
  25318. };
  25319. MaterialHelper.BindClipPlane = function (effect, scene) {
  25320. if (scene.clipPlane) {
  25321. var clipPlane = scene.clipPlane;
  25322. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25323. }
  25324. };
  25325. return MaterialHelper;
  25326. }());
  25327. BABYLON.MaterialHelper = MaterialHelper;
  25328. })(BABYLON || (BABYLON = {}));
  25329. //# sourceMappingURL=babylon.materialHelper.js.map
  25330. var BABYLON;
  25331. (function (BABYLON) {
  25332. var MaterialDefines = (function () {
  25333. function MaterialDefines() {
  25334. this._isDirty = true;
  25335. this._areLightsDirty = true;
  25336. this._areAttributesDirty = true;
  25337. this._areTexturesDirty = true;
  25338. this._areFresnelDirty = true;
  25339. this._areMiscDirty = true;
  25340. this._areImageProcessingDirty = true;
  25341. this._normals = false;
  25342. this._uvs = false;
  25343. this._needNormals = false;
  25344. this._needUVs = false;
  25345. }
  25346. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25347. get: function () {
  25348. return this._isDirty;
  25349. },
  25350. enumerable: true,
  25351. configurable: true
  25352. });
  25353. MaterialDefines.prototype.markAsProcessed = function () {
  25354. this._isDirty = false;
  25355. this._areAttributesDirty = false;
  25356. this._areTexturesDirty = false;
  25357. this._areFresnelDirty = false;
  25358. this._areLightsDirty = false;
  25359. this._areMiscDirty = false;
  25360. this._areImageProcessingDirty = false;
  25361. };
  25362. MaterialDefines.prototype.markAsUnprocessed = function () {
  25363. this._isDirty = true;
  25364. };
  25365. MaterialDefines.prototype.markAllAsDirty = function () {
  25366. this._areTexturesDirty = true;
  25367. this._areAttributesDirty = true;
  25368. this._areLightsDirty = true;
  25369. this._areFresnelDirty = true;
  25370. this._areMiscDirty = true;
  25371. this._areImageProcessingDirty = true;
  25372. this._isDirty = true;
  25373. };
  25374. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25375. this._areImageProcessingDirty = true;
  25376. this._isDirty = true;
  25377. };
  25378. MaterialDefines.prototype.markAsLightDirty = function () {
  25379. this._areLightsDirty = true;
  25380. this._isDirty = true;
  25381. };
  25382. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25383. this._areAttributesDirty = true;
  25384. this._isDirty = true;
  25385. };
  25386. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25387. this._areTexturesDirty = true;
  25388. this._isDirty = true;
  25389. };
  25390. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25391. this._areFresnelDirty = true;
  25392. this._isDirty = true;
  25393. };
  25394. MaterialDefines.prototype.markAsMiscDirty = function () {
  25395. this._areMiscDirty = true;
  25396. this._isDirty = true;
  25397. };
  25398. MaterialDefines.prototype.rebuild = function () {
  25399. if (this._keys) {
  25400. delete this._keys;
  25401. }
  25402. this._keys = [];
  25403. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25404. var key = _a[_i];
  25405. if (key[0] === "_") {
  25406. continue;
  25407. }
  25408. this._keys.push(key);
  25409. }
  25410. };
  25411. MaterialDefines.prototype.isEqual = function (other) {
  25412. if (this._keys.length !== other._keys.length) {
  25413. return false;
  25414. }
  25415. for (var index = 0; index < this._keys.length; index++) {
  25416. var prop = this._keys[index];
  25417. if (this[prop] !== other[prop]) {
  25418. return false;
  25419. }
  25420. }
  25421. return true;
  25422. };
  25423. MaterialDefines.prototype.cloneTo = function (other) {
  25424. if (this._keys.length !== other._keys.length) {
  25425. other._keys = this._keys.slice(0);
  25426. }
  25427. for (var index = 0; index < this._keys.length; index++) {
  25428. var prop = this._keys[index];
  25429. other[prop] = this[prop];
  25430. }
  25431. };
  25432. MaterialDefines.prototype.reset = function () {
  25433. for (var index = 0; index < this._keys.length; index++) {
  25434. var prop = this._keys[index];
  25435. if (typeof (this[prop]) === "number") {
  25436. this[prop] = 0;
  25437. }
  25438. else {
  25439. this[prop] = false;
  25440. }
  25441. }
  25442. };
  25443. MaterialDefines.prototype.toString = function () {
  25444. var result = "";
  25445. for (var index = 0; index < this._keys.length; index++) {
  25446. var prop = this._keys[index];
  25447. var value = this[prop];
  25448. if (typeof (value) === "number") {
  25449. result += "#define " + prop + " " + this[prop] + "\n";
  25450. }
  25451. else if (value) {
  25452. result += "#define " + prop + "\n";
  25453. }
  25454. }
  25455. return result;
  25456. };
  25457. return MaterialDefines;
  25458. }());
  25459. BABYLON.MaterialDefines = MaterialDefines;
  25460. var Material = (function () {
  25461. function Material(name, scene, doNotAdd) {
  25462. this.checkReadyOnEveryCall = false;
  25463. this.checkReadyOnlyOnce = false;
  25464. this.state = "";
  25465. this.alpha = 1.0;
  25466. this._backFaceCulling = true;
  25467. this.doNotSerialize = false;
  25468. this.storeEffectOnSubMeshes = false;
  25469. /**
  25470. * An event triggered when the material is disposed.
  25471. * @type {BABYLON.Observable}
  25472. */
  25473. this.onDisposeObservable = new BABYLON.Observable();
  25474. /**
  25475. * An event triggered when the material is bound.
  25476. * @type {BABYLON.Observable}
  25477. */
  25478. this.onBindObservable = new BABYLON.Observable();
  25479. /**
  25480. * An event triggered when the material is unbound.
  25481. * @type {BABYLON.Observable}
  25482. */
  25483. this.onUnBindObservable = new BABYLON.Observable();
  25484. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25485. this.needDepthPrePass = false;
  25486. this.disableDepthWrite = false;
  25487. this._fogEnabled = true;
  25488. this.pointSize = 1.0;
  25489. this.zOffset = 0;
  25490. this._wasPreviouslyReady = false;
  25491. this._fillMode = Material.TriangleFillMode;
  25492. this.name = name;
  25493. this.id = name || BABYLON.Tools.RandomId();
  25494. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25495. if (this._scene.useRightHandedSystem) {
  25496. this.sideOrientation = Material.ClockWiseSideOrientation;
  25497. }
  25498. else {
  25499. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25500. }
  25501. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25502. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25503. if (!doNotAdd) {
  25504. this._scene.materials.push(this);
  25505. }
  25506. }
  25507. Object.defineProperty(Material, "TriangleFillMode", {
  25508. get: function () {
  25509. return Material._TriangleFillMode;
  25510. },
  25511. enumerable: true,
  25512. configurable: true
  25513. });
  25514. Object.defineProperty(Material, "WireFrameFillMode", {
  25515. get: function () {
  25516. return Material._WireFrameFillMode;
  25517. },
  25518. enumerable: true,
  25519. configurable: true
  25520. });
  25521. Object.defineProperty(Material, "PointFillMode", {
  25522. get: function () {
  25523. return Material._PointFillMode;
  25524. },
  25525. enumerable: true,
  25526. configurable: true
  25527. });
  25528. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25529. get: function () {
  25530. return Material._ClockWiseSideOrientation;
  25531. },
  25532. enumerable: true,
  25533. configurable: true
  25534. });
  25535. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25536. get: function () {
  25537. return Material._CounterClockWiseSideOrientation;
  25538. },
  25539. enumerable: true,
  25540. configurable: true
  25541. });
  25542. Object.defineProperty(Material, "TextureDirtyFlag", {
  25543. get: function () {
  25544. return Material._TextureDirtyFlag;
  25545. },
  25546. enumerable: true,
  25547. configurable: true
  25548. });
  25549. Object.defineProperty(Material, "LightDirtyFlag", {
  25550. get: function () {
  25551. return Material._LightDirtyFlag;
  25552. },
  25553. enumerable: true,
  25554. configurable: true
  25555. });
  25556. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25557. get: function () {
  25558. return Material._FresnelDirtyFlag;
  25559. },
  25560. enumerable: true,
  25561. configurable: true
  25562. });
  25563. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25564. get: function () {
  25565. return Material._AttributesDirtyFlag;
  25566. },
  25567. enumerable: true,
  25568. configurable: true
  25569. });
  25570. Object.defineProperty(Material, "MiscDirtyFlag", {
  25571. get: function () {
  25572. return Material._MiscDirtyFlag;
  25573. },
  25574. enumerable: true,
  25575. configurable: true
  25576. });
  25577. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25578. get: function () {
  25579. return this._backFaceCulling;
  25580. },
  25581. set: function (value) {
  25582. if (this._backFaceCulling === value) {
  25583. return;
  25584. }
  25585. this._backFaceCulling = value;
  25586. this.markAsDirty(Material.TextureDirtyFlag);
  25587. },
  25588. enumerable: true,
  25589. configurable: true
  25590. });
  25591. Object.defineProperty(Material.prototype, "onDispose", {
  25592. set: function (callback) {
  25593. if (this._onDisposeObserver) {
  25594. this.onDisposeObservable.remove(this._onDisposeObserver);
  25595. }
  25596. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25597. },
  25598. enumerable: true,
  25599. configurable: true
  25600. });
  25601. Object.defineProperty(Material.prototype, "onBind", {
  25602. set: function (callback) {
  25603. if (this._onBindObserver) {
  25604. this.onBindObservable.remove(this._onBindObserver);
  25605. }
  25606. this._onBindObserver = this.onBindObservable.add(callback);
  25607. },
  25608. enumerable: true,
  25609. configurable: true
  25610. });
  25611. Object.defineProperty(Material.prototype, "fogEnabled", {
  25612. get: function () {
  25613. return this._fogEnabled;
  25614. },
  25615. set: function (value) {
  25616. if (this._fogEnabled === value) {
  25617. return;
  25618. }
  25619. this._fogEnabled = value;
  25620. this.markAsDirty(Material.MiscDirtyFlag);
  25621. },
  25622. enumerable: true,
  25623. configurable: true
  25624. });
  25625. Object.defineProperty(Material.prototype, "wireframe", {
  25626. get: function () {
  25627. return this._fillMode === Material.WireFrameFillMode;
  25628. },
  25629. set: function (value) {
  25630. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25631. },
  25632. enumerable: true,
  25633. configurable: true
  25634. });
  25635. Object.defineProperty(Material.prototype, "pointsCloud", {
  25636. get: function () {
  25637. return this._fillMode === Material.PointFillMode;
  25638. },
  25639. set: function (value) {
  25640. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25641. },
  25642. enumerable: true,
  25643. configurable: true
  25644. });
  25645. Object.defineProperty(Material.prototype, "fillMode", {
  25646. get: function () {
  25647. return this._fillMode;
  25648. },
  25649. set: function (value) {
  25650. if (this._fillMode === value) {
  25651. return;
  25652. }
  25653. this._fillMode = value;
  25654. this.markAsDirty(Material.MiscDirtyFlag);
  25655. },
  25656. enumerable: true,
  25657. configurable: true
  25658. });
  25659. /**
  25660. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25661. * subclasses should override adding information pertainent to themselves
  25662. */
  25663. Material.prototype.toString = function (fullDetails) {
  25664. var ret = "Name: " + this.name;
  25665. if (fullDetails) {
  25666. }
  25667. return ret;
  25668. };
  25669. /**
  25670. * Child classes can use it to update shaders
  25671. */
  25672. Material.prototype.getClassName = function () {
  25673. return "Material";
  25674. };
  25675. Object.defineProperty(Material.prototype, "isFrozen", {
  25676. get: function () {
  25677. return this.checkReadyOnlyOnce;
  25678. },
  25679. enumerable: true,
  25680. configurable: true
  25681. });
  25682. Material.prototype.freeze = function () {
  25683. this.checkReadyOnlyOnce = true;
  25684. };
  25685. Material.prototype.unfreeze = function () {
  25686. this.checkReadyOnlyOnce = false;
  25687. };
  25688. Material.prototype.isReady = function (mesh, useInstances) {
  25689. return true;
  25690. };
  25691. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25692. return false;
  25693. };
  25694. Material.prototype.getEffect = function () {
  25695. return this._effect;
  25696. };
  25697. Material.prototype.getScene = function () {
  25698. return this._scene;
  25699. };
  25700. Material.prototype.needAlphaBlending = function () {
  25701. return (this.alpha < 1.0);
  25702. };
  25703. Material.prototype.needAlphaTesting = function () {
  25704. return false;
  25705. };
  25706. Material.prototype.getAlphaTestTexture = function () {
  25707. return null;
  25708. };
  25709. Material.prototype.markDirty = function () {
  25710. this._wasPreviouslyReady = false;
  25711. };
  25712. Material.prototype._preBind = function (effect) {
  25713. var engine = this._scene.getEngine();
  25714. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25715. engine.enableEffect(effect ? effect : this._effect);
  25716. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25717. };
  25718. Material.prototype.bind = function (world, mesh) {
  25719. };
  25720. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25721. };
  25722. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25723. };
  25724. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25725. sceneUbo.bindToEffect(effect, "Scene");
  25726. };
  25727. Material.prototype.bindView = function (effect) {
  25728. if (!this._useUBO) {
  25729. effect.setMatrix("view", this.getScene().getViewMatrix());
  25730. }
  25731. else {
  25732. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25733. }
  25734. };
  25735. Material.prototype.bindViewProjection = function (effect) {
  25736. if (!this._useUBO) {
  25737. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25738. }
  25739. else {
  25740. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25741. }
  25742. };
  25743. Material.prototype._afterBind = function (mesh) {
  25744. this._scene._cachedMaterial = this;
  25745. if (mesh) {
  25746. this._scene._cachedVisibility = mesh.visibility;
  25747. }
  25748. else {
  25749. this._scene._cachedVisibility = 1;
  25750. }
  25751. this.onBindObservable.notifyObservers(mesh);
  25752. if (this.disableDepthWrite) {
  25753. var engine = this._scene.getEngine();
  25754. this._cachedDepthWriteState = engine.getDepthWrite();
  25755. engine.setDepthWrite(false);
  25756. }
  25757. };
  25758. Material.prototype.unbind = function () {
  25759. this.onUnBindObservable.notifyObservers(this);
  25760. if (this.disableDepthWrite) {
  25761. var engine = this._scene.getEngine();
  25762. engine.setDepthWrite(this._cachedDepthWriteState);
  25763. }
  25764. };
  25765. Material.prototype.getActiveTextures = function () {
  25766. return [];
  25767. };
  25768. Material.prototype.hasTexture = function (texture) {
  25769. return false;
  25770. };
  25771. Material.prototype.clone = function (name) {
  25772. return null;
  25773. };
  25774. Material.prototype.getBindedMeshes = function () {
  25775. var result = new Array();
  25776. for (var index = 0; index < this._scene.meshes.length; index++) {
  25777. var mesh = this._scene.meshes[index];
  25778. if (mesh.material === this) {
  25779. result.push(mesh);
  25780. }
  25781. }
  25782. return result;
  25783. };
  25784. /**
  25785. * Force shader compilation including textures ready check
  25786. */
  25787. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25788. var _this = this;
  25789. var subMesh = new BABYLON.BaseSubMesh();
  25790. var scene = this.getScene();
  25791. var engine = scene.getEngine();
  25792. var checkReady = function () {
  25793. if (!_this._scene || !_this._scene.getEngine()) {
  25794. return;
  25795. }
  25796. if (subMesh._materialDefines) {
  25797. subMesh._materialDefines._renderId = -1;
  25798. }
  25799. var alphaTestState = engine.getAlphaTesting();
  25800. var clipPlaneState = scene.clipPlane;
  25801. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25802. if (options && options.clipPlane) {
  25803. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25804. }
  25805. if (_this.storeEffectOnSubMeshes) {
  25806. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25807. if (onCompiled) {
  25808. onCompiled(_this);
  25809. }
  25810. }
  25811. else {
  25812. setTimeout(checkReady, 16);
  25813. }
  25814. }
  25815. else {
  25816. if (_this.isReady(mesh)) {
  25817. if (onCompiled) {
  25818. onCompiled(_this);
  25819. }
  25820. }
  25821. else {
  25822. setTimeout(checkReady, 16);
  25823. }
  25824. }
  25825. engine.setAlphaTesting(alphaTestState);
  25826. if (options && options.clipPlane) {
  25827. scene.clipPlane = clipPlaneState;
  25828. }
  25829. };
  25830. checkReady();
  25831. };
  25832. Material.prototype.markAsDirty = function (flag) {
  25833. if (flag & Material.TextureDirtyFlag) {
  25834. this._markAllSubMeshesAsTexturesDirty();
  25835. }
  25836. if (flag & Material.LightDirtyFlag) {
  25837. this._markAllSubMeshesAsLightsDirty();
  25838. }
  25839. if (flag & Material.FresnelDirtyFlag) {
  25840. this._markAllSubMeshesAsFresnelDirty();
  25841. }
  25842. if (flag & Material.AttributesDirtyFlag) {
  25843. this._markAllSubMeshesAsAttributesDirty();
  25844. }
  25845. if (flag & Material.MiscDirtyFlag) {
  25846. this._markAllSubMeshesAsMiscDirty();
  25847. }
  25848. this.getScene().resetCachedMaterial();
  25849. };
  25850. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25851. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25852. var mesh = _a[_i];
  25853. if (!mesh.subMeshes) {
  25854. continue;
  25855. }
  25856. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25857. var subMesh = _c[_b];
  25858. if (subMesh.getMaterial() !== this) {
  25859. continue;
  25860. }
  25861. if (!subMesh._materialDefines) {
  25862. continue;
  25863. }
  25864. func(subMesh._materialDefines);
  25865. }
  25866. }
  25867. };
  25868. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25869. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25870. };
  25871. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25872. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25873. };
  25874. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25875. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25876. };
  25877. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25878. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25879. };
  25880. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25881. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25882. };
  25883. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25884. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25885. };
  25886. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25887. // Animations
  25888. this.getScene().stopAnimation(this);
  25889. // Remove from scene
  25890. var index = this._scene.materials.indexOf(this);
  25891. if (index >= 0) {
  25892. this._scene.materials.splice(index, 1);
  25893. }
  25894. // Remove from meshes
  25895. for (index = 0; index < this._scene.meshes.length; index++) {
  25896. var mesh = this._scene.meshes[index];
  25897. if (mesh.material === this) {
  25898. mesh.material = null;
  25899. if (mesh.geometry) {
  25900. var geometry = mesh.geometry;
  25901. if (this.storeEffectOnSubMeshes) {
  25902. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25903. var subMesh = _a[_i];
  25904. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25905. }
  25906. }
  25907. else {
  25908. geometry._releaseVertexArrayObject(this._effect);
  25909. }
  25910. }
  25911. }
  25912. }
  25913. this._uniformBuffer.dispose();
  25914. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25915. if (forceDisposeEffect && this._effect) {
  25916. if (this.storeEffectOnSubMeshes) {
  25917. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25918. var subMesh = _c[_b];
  25919. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25920. }
  25921. }
  25922. else {
  25923. this._scene.getEngine()._releaseEffect(this._effect);
  25924. }
  25925. this._effect = null;
  25926. }
  25927. // Callback
  25928. this.onDisposeObservable.notifyObservers(this);
  25929. this.onDisposeObservable.clear();
  25930. this.onBindObservable.clear();
  25931. this.onUnBindObservable.clear();
  25932. };
  25933. Material.prototype.serialize = function () {
  25934. return BABYLON.SerializationHelper.Serialize(this);
  25935. };
  25936. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25937. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25938. multiMaterial.id = parsedMultiMaterial.id;
  25939. if (BABYLON.Tags) {
  25940. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25941. }
  25942. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25943. var subMatId = parsedMultiMaterial.materials[matIndex];
  25944. if (subMatId) {
  25945. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25946. }
  25947. else {
  25948. multiMaterial.subMaterials.push(null);
  25949. }
  25950. }
  25951. return multiMaterial;
  25952. };
  25953. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25954. if (!parsedMaterial.customType) {
  25955. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25956. }
  25957. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25958. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25959. if (!BABYLON.LegacyPBRMaterial) {
  25960. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25961. return;
  25962. }
  25963. }
  25964. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25965. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25966. ;
  25967. };
  25968. Material._TriangleFillMode = 0;
  25969. Material._WireFrameFillMode = 1;
  25970. Material._PointFillMode = 2;
  25971. Material._ClockWiseSideOrientation = 0;
  25972. Material._CounterClockWiseSideOrientation = 1;
  25973. Material._TextureDirtyFlag = 1;
  25974. Material._LightDirtyFlag = 2;
  25975. Material._FresnelDirtyFlag = 4;
  25976. Material._AttributesDirtyFlag = 8;
  25977. Material._MiscDirtyFlag = 16;
  25978. __decorate([
  25979. BABYLON.serialize()
  25980. ], Material.prototype, "id", void 0);
  25981. __decorate([
  25982. BABYLON.serialize()
  25983. ], Material.prototype, "name", void 0);
  25984. __decorate([
  25985. BABYLON.serialize()
  25986. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25987. __decorate([
  25988. BABYLON.serialize()
  25989. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25990. __decorate([
  25991. BABYLON.serialize()
  25992. ], Material.prototype, "state", void 0);
  25993. __decorate([
  25994. BABYLON.serialize()
  25995. ], Material.prototype, "alpha", void 0);
  25996. __decorate([
  25997. BABYLON.serialize("backFaceCulling")
  25998. ], Material.prototype, "_backFaceCulling", void 0);
  25999. __decorate([
  26000. BABYLON.serialize()
  26001. ], Material.prototype, "sideOrientation", void 0);
  26002. __decorate([
  26003. BABYLON.serialize()
  26004. ], Material.prototype, "alphaMode", void 0);
  26005. __decorate([
  26006. BABYLON.serialize()
  26007. ], Material.prototype, "needDepthPrePass", void 0);
  26008. __decorate([
  26009. BABYLON.serialize()
  26010. ], Material.prototype, "disableDepthWrite", void 0);
  26011. __decorate([
  26012. BABYLON.serialize("fogEnabled")
  26013. ], Material.prototype, "_fogEnabled", void 0);
  26014. __decorate([
  26015. BABYLON.serialize()
  26016. ], Material.prototype, "pointSize", void 0);
  26017. __decorate([
  26018. BABYLON.serialize()
  26019. ], Material.prototype, "zOffset", void 0);
  26020. __decorate([
  26021. BABYLON.serialize()
  26022. ], Material.prototype, "wireframe", null);
  26023. __decorate([
  26024. BABYLON.serialize()
  26025. ], Material.prototype, "pointsCloud", null);
  26026. __decorate([
  26027. BABYLON.serialize()
  26028. ], Material.prototype, "fillMode", null);
  26029. return Material;
  26030. }());
  26031. BABYLON.Material = Material;
  26032. })(BABYLON || (BABYLON = {}));
  26033. //# sourceMappingURL=babylon.material.js.map
  26034. var BABYLON;
  26035. (function (BABYLON) {
  26036. var UniformBuffer = (function () {
  26037. /**
  26038. * Uniform buffer objects.
  26039. *
  26040. * Handles blocks of uniform on the GPU.
  26041. *
  26042. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26043. *
  26044. * For more information, please refer to :
  26045. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26046. */
  26047. function UniformBuffer(engine, data, dynamic) {
  26048. this._engine = engine;
  26049. this._noUBO = !engine.supportsUniformBuffers;
  26050. this._dynamic = dynamic;
  26051. this._data = data || [];
  26052. this._uniformLocations = {};
  26053. this._uniformSizes = {};
  26054. this._uniformLocationPointer = 0;
  26055. this._needSync = false;
  26056. if (this._noUBO) {
  26057. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26058. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26059. this.updateFloat = this._updateFloatForEffect;
  26060. this.updateFloat2 = this._updateFloat2ForEffect;
  26061. this.updateFloat3 = this._updateFloat3ForEffect;
  26062. this.updateFloat4 = this._updateFloat4ForEffect;
  26063. this.updateMatrix = this._updateMatrixForEffect;
  26064. this.updateVector3 = this._updateVector3ForEffect;
  26065. this.updateVector4 = this._updateVector4ForEffect;
  26066. this.updateColor3 = this._updateColor3ForEffect;
  26067. this.updateColor4 = this._updateColor4ForEffect;
  26068. }
  26069. else {
  26070. this._engine._uniformBuffers.push(this);
  26071. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26072. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26073. this.updateFloat = this._updateFloatForUniform;
  26074. this.updateFloat2 = this._updateFloat2ForUniform;
  26075. this.updateFloat3 = this._updateFloat3ForUniform;
  26076. this.updateFloat4 = this._updateFloat4ForUniform;
  26077. this.updateMatrix = this._updateMatrixForUniform;
  26078. this.updateVector3 = this._updateVector3ForUniform;
  26079. this.updateVector4 = this._updateVector4ForUniform;
  26080. this.updateColor3 = this._updateColor3ForUniform;
  26081. this.updateColor4 = this._updateColor4ForUniform;
  26082. }
  26083. }
  26084. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26085. // Properties
  26086. /**
  26087. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26088. * or just falling back on setUniformXXX calls.
  26089. */
  26090. get: function () {
  26091. return !this._noUBO;
  26092. },
  26093. enumerable: true,
  26094. configurable: true
  26095. });
  26096. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26097. /**
  26098. * Indicates if the WebGL underlying uniform buffer is in sync
  26099. * with the javascript cache data.
  26100. */
  26101. get: function () {
  26102. return !this._needSync;
  26103. },
  26104. enumerable: true,
  26105. configurable: true
  26106. });
  26107. /**
  26108. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26109. * Also, a dynamic UniformBuffer will disable cache verification and always
  26110. * update the underlying WebGL uniform buffer to the GPU.
  26111. */
  26112. UniformBuffer.prototype.isDynamic = function () {
  26113. return this._dynamic;
  26114. };
  26115. /**
  26116. * The data cache on JS side.
  26117. */
  26118. UniformBuffer.prototype.getData = function () {
  26119. return this._bufferData;
  26120. };
  26121. /**
  26122. * The underlying WebGL Uniform buffer.
  26123. */
  26124. UniformBuffer.prototype.getBuffer = function () {
  26125. return this._buffer;
  26126. };
  26127. /**
  26128. * std140 layout specifies how to align data within an UBO structure.
  26129. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26130. * for specs.
  26131. */
  26132. UniformBuffer.prototype._fillAlignment = function (size) {
  26133. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26134. // and 4x4 matrices
  26135. // TODO : change if other types are used
  26136. var alignment;
  26137. if (size <= 2) {
  26138. alignment = size;
  26139. }
  26140. else {
  26141. alignment = 4;
  26142. }
  26143. if ((this._uniformLocationPointer % alignment) !== 0) {
  26144. var oldPointer = this._uniformLocationPointer;
  26145. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26146. var diff = this._uniformLocationPointer - oldPointer;
  26147. for (var i = 0; i < diff; i++) {
  26148. this._data.push(0);
  26149. }
  26150. }
  26151. };
  26152. /**
  26153. * Adds an uniform in the buffer.
  26154. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26155. * for the layout to be correct !
  26156. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26157. * @param {number|number[]} size Data size, or data directly.
  26158. */
  26159. UniformBuffer.prototype.addUniform = function (name, size) {
  26160. if (this._noUBO) {
  26161. return;
  26162. }
  26163. if (this._uniformLocations[name] !== undefined) {
  26164. // Already existing uniform
  26165. return;
  26166. }
  26167. // This function must be called in the order of the shader layout !
  26168. // size can be the size of the uniform, or data directly
  26169. var data;
  26170. if (size instanceof Array) {
  26171. data = size;
  26172. size = data.length;
  26173. }
  26174. else {
  26175. size = size;
  26176. data = [];
  26177. // Fill with zeros
  26178. for (var i = 0; i < size; i++) {
  26179. data.push(0);
  26180. }
  26181. }
  26182. this._fillAlignment(size);
  26183. this._uniformSizes[name] = size;
  26184. this._uniformLocations[name] = this._uniformLocationPointer;
  26185. this._uniformLocationPointer += size;
  26186. for (var i = 0; i < size; i++) {
  26187. this._data.push(data[i]);
  26188. }
  26189. this._needSync = true;
  26190. };
  26191. /**
  26192. * Wrapper for addUniform.
  26193. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26194. * @param {Matrix} mat A 4x4 matrix.
  26195. */
  26196. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26197. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26198. };
  26199. /**
  26200. * Wrapper for addUniform.
  26201. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26202. * @param {number} x
  26203. * @param {number} y
  26204. */
  26205. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26206. var temp = [x, y];
  26207. this.addUniform(name, temp);
  26208. };
  26209. /**
  26210. * Wrapper for addUniform.
  26211. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26212. * @param {number} x
  26213. * @param {number} y
  26214. * @param {number} z
  26215. */
  26216. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26217. var temp = [x, y, z];
  26218. this.addUniform(name, temp);
  26219. };
  26220. /**
  26221. * Wrapper for addUniform.
  26222. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26223. * @param {Color3} color
  26224. */
  26225. UniformBuffer.prototype.addColor3 = function (name, color) {
  26226. var temp = [];
  26227. color.toArray(temp);
  26228. this.addUniform(name, temp);
  26229. };
  26230. /**
  26231. * Wrapper for addUniform.
  26232. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26233. * @param {Color3} color
  26234. * @param {number} alpha
  26235. */
  26236. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26237. var temp = [];
  26238. color.toArray(temp);
  26239. temp.push(alpha);
  26240. this.addUniform(name, temp);
  26241. };
  26242. /**
  26243. * Wrapper for addUniform.
  26244. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26245. * @param {Vector3} vector
  26246. */
  26247. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26248. var temp = [];
  26249. vector.toArray(temp);
  26250. this.addUniform(name, temp);
  26251. };
  26252. /**
  26253. * Wrapper for addUniform.
  26254. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26255. */
  26256. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26257. this.addUniform(name, 12);
  26258. };
  26259. /**
  26260. * Wrapper for addUniform.
  26261. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26262. */
  26263. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26264. this.addUniform(name, 8);
  26265. };
  26266. /**
  26267. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26268. */
  26269. UniformBuffer.prototype.create = function () {
  26270. if (this._noUBO) {
  26271. return;
  26272. }
  26273. if (this._buffer) {
  26274. return; // nothing to do
  26275. }
  26276. // See spec, alignment must be filled as a vec4
  26277. this._fillAlignment(4);
  26278. this._bufferData = new Float32Array(this._data);
  26279. this._rebuild();
  26280. this._needSync = true;
  26281. };
  26282. UniformBuffer.prototype._rebuild = function () {
  26283. if (this._noUBO) {
  26284. return;
  26285. }
  26286. if (this._dynamic) {
  26287. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26288. }
  26289. else {
  26290. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26291. }
  26292. };
  26293. /**
  26294. * Updates the WebGL Uniform Buffer on the GPU.
  26295. * If the `dynamic` flag is set to true, no cache comparison is done.
  26296. * Otherwise, the buffer will be updated only if the cache differs.
  26297. */
  26298. UniformBuffer.prototype.update = function () {
  26299. if (!this._buffer) {
  26300. this.create();
  26301. return;
  26302. }
  26303. if (!this._dynamic && !this._needSync) {
  26304. return;
  26305. }
  26306. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26307. this._needSync = false;
  26308. };
  26309. /**
  26310. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26311. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26312. * @param {number[]|Float32Array} data Flattened data
  26313. * @param {number} size Size of the data.
  26314. */
  26315. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26316. var location = this._uniformLocations[uniformName];
  26317. if (location === undefined) {
  26318. if (this._buffer) {
  26319. // Cannot add an uniform if the buffer is already created
  26320. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26321. return;
  26322. }
  26323. this.addUniform(uniformName, size);
  26324. location = this._uniformLocations[uniformName];
  26325. }
  26326. if (!this._buffer) {
  26327. this.create();
  26328. }
  26329. if (!this._dynamic) {
  26330. // Cache for static uniform buffers
  26331. var changed = false;
  26332. for (var i = 0; i < size; i++) {
  26333. if (this._bufferData[location + i] !== data[i]) {
  26334. changed = true;
  26335. this._bufferData[location + i] = data[i];
  26336. }
  26337. }
  26338. this._needSync = this._needSync || changed;
  26339. }
  26340. else {
  26341. // No cache for dynamic
  26342. for (var i = 0; i < size; i++) {
  26343. this._bufferData[location + i] = data[i];
  26344. }
  26345. }
  26346. };
  26347. // Update methods
  26348. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26349. // To match std140, matrix must be realigned
  26350. for (var i = 0; i < 3; i++) {
  26351. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26352. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26353. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26354. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26355. }
  26356. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26357. };
  26358. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26359. this._currentEffect.setMatrix3x3(name, matrix);
  26360. };
  26361. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26362. this._currentEffect.setMatrix2x2(name, matrix);
  26363. };
  26364. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26365. // To match std140, matrix must be realigned
  26366. for (var i = 0; i < 2; i++) {
  26367. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26368. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26369. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26370. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26371. }
  26372. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26373. };
  26374. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26375. this._currentEffect.setFloat(name, x);
  26376. };
  26377. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26378. UniformBuffer._tempBuffer[0] = x;
  26379. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26380. };
  26381. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26382. if (suffix === void 0) { suffix = ""; }
  26383. this._currentEffect.setFloat2(name + suffix, x, y);
  26384. };
  26385. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26386. if (suffix === void 0) { suffix = ""; }
  26387. UniformBuffer._tempBuffer[0] = x;
  26388. UniformBuffer._tempBuffer[1] = y;
  26389. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26390. };
  26391. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26392. if (suffix === void 0) { suffix = ""; }
  26393. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26394. };
  26395. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26396. if (suffix === void 0) { suffix = ""; }
  26397. UniformBuffer._tempBuffer[0] = x;
  26398. UniformBuffer._tempBuffer[1] = y;
  26399. UniformBuffer._tempBuffer[2] = z;
  26400. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26401. };
  26402. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26403. if (suffix === void 0) { suffix = ""; }
  26404. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26405. };
  26406. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26407. if (suffix === void 0) { suffix = ""; }
  26408. UniformBuffer._tempBuffer[0] = x;
  26409. UniformBuffer._tempBuffer[1] = y;
  26410. UniformBuffer._tempBuffer[2] = z;
  26411. UniformBuffer._tempBuffer[3] = w;
  26412. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26413. };
  26414. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26415. this._currentEffect.setMatrix(name, mat);
  26416. };
  26417. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26418. this.updateUniform(name, mat.toArray(), 16);
  26419. };
  26420. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26421. this._currentEffect.setVector3(name, vector);
  26422. };
  26423. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26424. vector.toArray(UniformBuffer._tempBuffer);
  26425. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26426. };
  26427. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26428. this._currentEffect.setVector4(name, vector);
  26429. };
  26430. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26431. vector.toArray(UniformBuffer._tempBuffer);
  26432. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26433. };
  26434. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26435. if (suffix === void 0) { suffix = ""; }
  26436. this._currentEffect.setColor3(name + suffix, color);
  26437. };
  26438. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26439. if (suffix === void 0) { suffix = ""; }
  26440. color.toArray(UniformBuffer._tempBuffer);
  26441. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26442. };
  26443. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26444. if (suffix === void 0) { suffix = ""; }
  26445. this._currentEffect.setColor4(name + suffix, color, alpha);
  26446. };
  26447. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26448. if (suffix === void 0) { suffix = ""; }
  26449. color.toArray(UniformBuffer._tempBuffer);
  26450. UniformBuffer._tempBuffer[3] = alpha;
  26451. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26452. };
  26453. /**
  26454. * Sets a sampler uniform on the effect.
  26455. * @param {string} name Name of the sampler.
  26456. * @param {Texture} texture
  26457. */
  26458. UniformBuffer.prototype.setTexture = function (name, texture) {
  26459. this._currentEffect.setTexture(name, texture);
  26460. };
  26461. /**
  26462. * Directly updates the value of the uniform in the cache AND on the GPU.
  26463. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26464. * @param {number[]|Float32Array} data Flattened data
  26465. */
  26466. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26467. this.updateUniform(uniformName, data, data.length);
  26468. this.update();
  26469. };
  26470. /**
  26471. * Binds this uniform buffer to an effect.
  26472. * @param {Effect} effect
  26473. * @param {string} name Name of the uniform block in the shader.
  26474. */
  26475. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26476. this._currentEffect = effect;
  26477. if (this._noUBO) {
  26478. return;
  26479. }
  26480. effect.bindUniformBuffer(this._buffer, name);
  26481. };
  26482. /**
  26483. * Disposes the uniform buffer.
  26484. */
  26485. UniformBuffer.prototype.dispose = function () {
  26486. if (this._noUBO) {
  26487. return;
  26488. }
  26489. var index = this._engine._uniformBuffers.indexOf(this);
  26490. if (index !== -1) {
  26491. this._engine._uniformBuffers.splice(index, 1);
  26492. }
  26493. if (!this._buffer) {
  26494. return;
  26495. }
  26496. if (this._engine._releaseBuffer(this._buffer)) {
  26497. this._buffer = null;
  26498. }
  26499. };
  26500. // Pool for avoiding memory leaks
  26501. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26502. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26503. return UniformBuffer;
  26504. }());
  26505. BABYLON.UniformBuffer = UniformBuffer;
  26506. })(BABYLON || (BABYLON = {}));
  26507. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26508. var BABYLON;
  26509. (function (BABYLON) {
  26510. var PushMaterial = (function (_super) {
  26511. __extends(PushMaterial, _super);
  26512. function PushMaterial(name, scene) {
  26513. var _this = _super.call(this, name, scene) || this;
  26514. _this.storeEffectOnSubMeshes = true;
  26515. return _this;
  26516. }
  26517. PushMaterial.prototype.getEffect = function () {
  26518. return this._activeEffect;
  26519. };
  26520. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26521. if (!mesh) {
  26522. return false;
  26523. }
  26524. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26525. return true;
  26526. }
  26527. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26528. };
  26529. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26530. this._activeEffect.setMatrix("world", world);
  26531. };
  26532. PushMaterial.prototype.bind = function (world, mesh) {
  26533. if (!mesh) {
  26534. return;
  26535. }
  26536. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26537. };
  26538. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26539. _super.prototype._afterBind.call(this, mesh);
  26540. this.getScene()._cachedEffect = effect;
  26541. };
  26542. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26543. if (visibility === void 0) { visibility = 1; }
  26544. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26545. };
  26546. return PushMaterial;
  26547. }(BABYLON.Material));
  26548. BABYLON.PushMaterial = PushMaterial;
  26549. })(BABYLON || (BABYLON = {}));
  26550. //# sourceMappingURL=babylon.pushMaterial.js.map
  26551. var BABYLON;
  26552. (function (BABYLON) {
  26553. var VertexData = (function () {
  26554. function VertexData() {
  26555. }
  26556. VertexData.prototype.set = function (data, kind) {
  26557. switch (kind) {
  26558. case BABYLON.VertexBuffer.PositionKind:
  26559. this.positions = data;
  26560. break;
  26561. case BABYLON.VertexBuffer.NormalKind:
  26562. this.normals = data;
  26563. break;
  26564. case BABYLON.VertexBuffer.TangentKind:
  26565. this.tangents = data;
  26566. break;
  26567. case BABYLON.VertexBuffer.UVKind:
  26568. this.uvs = data;
  26569. break;
  26570. case BABYLON.VertexBuffer.UV2Kind:
  26571. this.uvs2 = data;
  26572. break;
  26573. case BABYLON.VertexBuffer.UV3Kind:
  26574. this.uvs3 = data;
  26575. break;
  26576. case BABYLON.VertexBuffer.UV4Kind:
  26577. this.uvs4 = data;
  26578. break;
  26579. case BABYLON.VertexBuffer.UV5Kind:
  26580. this.uvs5 = data;
  26581. break;
  26582. case BABYLON.VertexBuffer.UV6Kind:
  26583. this.uvs6 = data;
  26584. break;
  26585. case BABYLON.VertexBuffer.ColorKind:
  26586. this.colors = data;
  26587. break;
  26588. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26589. this.matricesIndices = data;
  26590. break;
  26591. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26592. this.matricesWeights = data;
  26593. break;
  26594. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26595. this.matricesIndicesExtra = data;
  26596. break;
  26597. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26598. this.matricesWeightsExtra = data;
  26599. break;
  26600. }
  26601. };
  26602. /**
  26603. * Associates the vertexData to the passed Mesh.
  26604. * Sets it as updatable or not (default `false`).
  26605. * Returns the VertexData.
  26606. */
  26607. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26608. this._applyTo(mesh, updatable);
  26609. return this;
  26610. };
  26611. /**
  26612. * Associates the vertexData to the passed Geometry.
  26613. * Sets it as updatable or not (default `false`).
  26614. * Returns the VertexData.
  26615. */
  26616. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26617. this._applyTo(geometry, updatable);
  26618. return this;
  26619. };
  26620. /**
  26621. * Updates the associated mesh.
  26622. * Returns the VertexData.
  26623. */
  26624. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26625. this._update(mesh);
  26626. return this;
  26627. };
  26628. /**
  26629. * Updates the associated geometry.
  26630. * Returns the VertexData.
  26631. */
  26632. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26633. this._update(geometry);
  26634. return this;
  26635. };
  26636. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26637. if (this.positions) {
  26638. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26639. }
  26640. if (this.normals) {
  26641. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26642. }
  26643. if (this.tangents) {
  26644. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26645. }
  26646. if (this.uvs) {
  26647. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26648. }
  26649. if (this.uvs2) {
  26650. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26651. }
  26652. if (this.uvs3) {
  26653. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26654. }
  26655. if (this.uvs4) {
  26656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26657. }
  26658. if (this.uvs5) {
  26659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26660. }
  26661. if (this.uvs6) {
  26662. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26663. }
  26664. if (this.colors) {
  26665. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26666. }
  26667. if (this.matricesIndices) {
  26668. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26669. }
  26670. if (this.matricesWeights) {
  26671. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26672. }
  26673. if (this.matricesIndicesExtra) {
  26674. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26675. }
  26676. if (this.matricesWeightsExtra) {
  26677. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26678. }
  26679. if (this.indices) {
  26680. meshOrGeometry.setIndices(this.indices);
  26681. }
  26682. return this;
  26683. };
  26684. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26685. if (this.positions) {
  26686. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26687. }
  26688. if (this.normals) {
  26689. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26690. }
  26691. if (this.tangents) {
  26692. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26693. }
  26694. if (this.uvs) {
  26695. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26696. }
  26697. if (this.uvs2) {
  26698. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26699. }
  26700. if (this.uvs3) {
  26701. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26702. }
  26703. if (this.uvs4) {
  26704. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26705. }
  26706. if (this.uvs5) {
  26707. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26708. }
  26709. if (this.uvs6) {
  26710. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26711. }
  26712. if (this.colors) {
  26713. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26714. }
  26715. if (this.matricesIndices) {
  26716. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26717. }
  26718. if (this.matricesWeights) {
  26719. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26720. }
  26721. if (this.matricesIndicesExtra) {
  26722. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26723. }
  26724. if (this.matricesWeightsExtra) {
  26725. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26726. }
  26727. if (this.indices) {
  26728. meshOrGeometry.setIndices(this.indices);
  26729. }
  26730. return this;
  26731. };
  26732. /**
  26733. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26734. * Returns the VertexData.
  26735. */
  26736. VertexData.prototype.transform = function (matrix) {
  26737. var transformed = BABYLON.Vector3.Zero();
  26738. var index;
  26739. if (this.positions) {
  26740. var position = BABYLON.Vector3.Zero();
  26741. for (index = 0; index < this.positions.length; index += 3) {
  26742. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26743. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26744. this.positions[index] = transformed.x;
  26745. this.positions[index + 1] = transformed.y;
  26746. this.positions[index + 2] = transformed.z;
  26747. }
  26748. }
  26749. if (this.normals) {
  26750. var normal = BABYLON.Vector3.Zero();
  26751. for (index = 0; index < this.normals.length; index += 3) {
  26752. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26753. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26754. this.normals[index] = transformed.x;
  26755. this.normals[index + 1] = transformed.y;
  26756. this.normals[index + 2] = transformed.z;
  26757. }
  26758. }
  26759. if (this.tangents) {
  26760. var tangent = BABYLON.Vector4.Zero();
  26761. var tangentTransformed = BABYLON.Vector4.Zero();
  26762. for (index = 0; index < this.tangents.length; index += 4) {
  26763. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26764. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26765. this.tangents[index] = tangentTransformed.x;
  26766. this.tangents[index + 1] = tangentTransformed.y;
  26767. this.tangents[index + 2] = tangentTransformed.z;
  26768. this.tangents[index + 3] = tangentTransformed.w;
  26769. }
  26770. }
  26771. return this;
  26772. };
  26773. /**
  26774. * Merges the passed VertexData into the current one.
  26775. * Returns the modified VertexData.
  26776. */
  26777. VertexData.prototype.merge = function (other) {
  26778. if (other.indices) {
  26779. if (!this.indices) {
  26780. this.indices = [];
  26781. }
  26782. var offset = this.positions ? this.positions.length / 3 : 0;
  26783. for (var index = 0; index < other.indices.length; index++) {
  26784. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26785. this.indices.push(other.indices[index] + offset);
  26786. }
  26787. }
  26788. this.positions = this._mergeElement(this.positions, other.positions);
  26789. this.normals = this._mergeElement(this.normals, other.normals);
  26790. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26791. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26792. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26793. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26794. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26795. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26796. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26797. this.colors = this._mergeElement(this.colors, other.colors);
  26798. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26799. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26800. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26801. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26802. return this;
  26803. };
  26804. VertexData.prototype._mergeElement = function (source, other) {
  26805. if (!other)
  26806. return source;
  26807. if (!source)
  26808. return other;
  26809. var len = other.length + source.length;
  26810. var isSrcTypedArray = source instanceof Float32Array;
  26811. var isOthTypedArray = other instanceof Float32Array;
  26812. // use non-loop method when the source is Float32Array
  26813. if (isSrcTypedArray) {
  26814. var ret32 = new Float32Array(len);
  26815. ret32.set(source);
  26816. ret32.set(other, source.length);
  26817. return ret32;
  26818. // source is number[], when other is also use concat
  26819. }
  26820. else if (!isOthTypedArray) {
  26821. return source.concat(other);
  26822. // source is a number[], but other is a Float32Array, loop required
  26823. }
  26824. else {
  26825. var ret = source.slice(0); // copy source to a separate array
  26826. for (var i = 0, len = other.length; i < len; i++) {
  26827. ret.push(other[i]);
  26828. }
  26829. return ret;
  26830. }
  26831. };
  26832. /**
  26833. * Serializes the VertexData.
  26834. * Returns a serialized object.
  26835. */
  26836. VertexData.prototype.serialize = function () {
  26837. var serializationObject = this.serialize();
  26838. if (this.positions) {
  26839. serializationObject.positions = this.positions;
  26840. }
  26841. if (this.normals) {
  26842. serializationObject.normals = this.normals;
  26843. }
  26844. if (this.tangents) {
  26845. serializationObject.tangents = this.tangents;
  26846. }
  26847. if (this.uvs) {
  26848. serializationObject.uvs = this.uvs;
  26849. }
  26850. if (this.uvs2) {
  26851. serializationObject.uvs2 = this.uvs2;
  26852. }
  26853. if (this.uvs3) {
  26854. serializationObject.uvs3 = this.uvs3;
  26855. }
  26856. if (this.uvs4) {
  26857. serializationObject.uvs4 = this.uvs4;
  26858. }
  26859. if (this.uvs5) {
  26860. serializationObject.uvs5 = this.uvs5;
  26861. }
  26862. if (this.uvs6) {
  26863. serializationObject.uvs6 = this.uvs6;
  26864. }
  26865. if (this.colors) {
  26866. serializationObject.colors = this.colors;
  26867. }
  26868. if (this.matricesIndices) {
  26869. serializationObject.matricesIndices = this.matricesIndices;
  26870. serializationObject.matricesIndices._isExpanded = true;
  26871. }
  26872. if (this.matricesWeights) {
  26873. serializationObject.matricesWeights = this.matricesWeights;
  26874. }
  26875. if (this.matricesIndicesExtra) {
  26876. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26877. serializationObject.matricesIndicesExtra._isExpanded = true;
  26878. }
  26879. if (this.matricesWeightsExtra) {
  26880. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26881. }
  26882. serializationObject.indices = this.indices;
  26883. return serializationObject;
  26884. };
  26885. // Statics
  26886. /**
  26887. * Returns the object VertexData associated to the passed mesh.
  26888. */
  26889. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26890. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26891. };
  26892. /**
  26893. * Returns the object VertexData associated to the passed geometry.
  26894. */
  26895. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26896. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26897. };
  26898. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26899. var result = new VertexData();
  26900. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26901. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26902. }
  26903. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26904. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26905. }
  26906. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26907. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26908. }
  26909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26910. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26911. }
  26912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26913. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26914. }
  26915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26916. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26917. }
  26918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26919. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26920. }
  26921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26922. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26923. }
  26924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26925. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26926. }
  26927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26928. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26929. }
  26930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26931. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26932. }
  26933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26934. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26935. }
  26936. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26937. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26938. }
  26939. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26940. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26941. }
  26942. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26943. return result;
  26944. };
  26945. /**
  26946. * Creates the vertexData of the Ribbon.
  26947. */
  26948. VertexData.CreateRibbon = function (options) {
  26949. var pathArray = options.pathArray;
  26950. var closeArray = options.closeArray || false;
  26951. var closePath = options.closePath || false;
  26952. var invertUV = options.invertUV || false;
  26953. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26954. var offset = options.offset || defaultOffset;
  26955. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26956. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26957. var customUV = options.uvs;
  26958. var customColors = options.colors;
  26959. var positions = [];
  26960. var indices = [];
  26961. var normals = [];
  26962. var uvs = [];
  26963. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26964. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26965. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26966. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26967. var minlg; // minimal length among all paths from pathArray
  26968. var lg = []; // array of path lengths : nb of vertex per path
  26969. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26970. var p; // path iterator
  26971. var i; // point iterator
  26972. var j; // point iterator
  26973. // if single path in pathArray
  26974. if (pathArray.length < 2) {
  26975. var ar1 = [];
  26976. var ar2 = [];
  26977. for (i = 0; i < pathArray[0].length - offset; i++) {
  26978. ar1.push(pathArray[0][i]);
  26979. ar2.push(pathArray[0][i + offset]);
  26980. }
  26981. pathArray = [ar1, ar2];
  26982. }
  26983. // positions and horizontal distances (u)
  26984. var idc = 0;
  26985. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26986. var path;
  26987. var l;
  26988. minlg = pathArray[0].length;
  26989. var vectlg;
  26990. var dist;
  26991. for (p = 0; p < pathArray.length; p++) {
  26992. uTotalDistance[p] = 0;
  26993. us[p] = [0];
  26994. path = pathArray[p];
  26995. l = path.length;
  26996. minlg = (minlg < l) ? minlg : l;
  26997. j = 0;
  26998. while (j < l) {
  26999. positions.push(path[j].x, path[j].y, path[j].z);
  27000. if (j > 0) {
  27001. vectlg = path[j].subtract(path[j - 1]).length();
  27002. dist = vectlg + uTotalDistance[p];
  27003. us[p].push(dist);
  27004. uTotalDistance[p] = dist;
  27005. }
  27006. j++;
  27007. }
  27008. if (closePath) {
  27009. j--;
  27010. positions.push(path[0].x, path[0].y, path[0].z);
  27011. vectlg = path[j].subtract(path[0]).length();
  27012. dist = vectlg + uTotalDistance[p];
  27013. us[p].push(dist);
  27014. uTotalDistance[p] = dist;
  27015. }
  27016. lg[p] = l + closePathCorr;
  27017. idx[p] = idc;
  27018. idc += (l + closePathCorr);
  27019. }
  27020. // vertical distances (v)
  27021. var path1;
  27022. var path2;
  27023. var vertex1;
  27024. var vertex2;
  27025. for (i = 0; i < minlg + closePathCorr; i++) {
  27026. vTotalDistance[i] = 0;
  27027. vs[i] = [0];
  27028. for (p = 0; p < pathArray.length - 1; p++) {
  27029. path1 = pathArray[p];
  27030. path2 = pathArray[p + 1];
  27031. if (i === minlg) {
  27032. vertex1 = path1[0];
  27033. vertex2 = path2[0];
  27034. }
  27035. else {
  27036. vertex1 = path1[i];
  27037. vertex2 = path2[i];
  27038. }
  27039. vectlg = vertex2.subtract(vertex1).length();
  27040. dist = vectlg + vTotalDistance[i];
  27041. vs[i].push(dist);
  27042. vTotalDistance[i] = dist;
  27043. }
  27044. if (closeArray) {
  27045. path1 = pathArray[p];
  27046. path2 = pathArray[0];
  27047. if (i === minlg) {
  27048. vertex2 = path2[0];
  27049. }
  27050. vectlg = vertex2.subtract(vertex1).length();
  27051. dist = vectlg + vTotalDistance[i];
  27052. vTotalDistance[i] = dist;
  27053. }
  27054. }
  27055. // uvs
  27056. var u;
  27057. var v;
  27058. if (customUV) {
  27059. for (p = 0; p < customUV.length; p++) {
  27060. uvs.push(customUV[p].x, customUV[p].y);
  27061. }
  27062. }
  27063. else {
  27064. for (p = 0; p < pathArray.length; p++) {
  27065. for (i = 0; i < minlg + closePathCorr; i++) {
  27066. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27067. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27068. if (invertUV) {
  27069. uvs.push(v, u);
  27070. }
  27071. else {
  27072. uvs.push(u, v);
  27073. }
  27074. }
  27075. }
  27076. }
  27077. // indices
  27078. p = 0; // path index
  27079. var pi = 0; // positions array index
  27080. var l1 = lg[p] - 1; // path1 length
  27081. var l2 = lg[p + 1] - 1; // path2 length
  27082. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27083. var shft = idx[1] - idx[0]; // shift
  27084. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27085. while (pi <= min && p < path1nb) {
  27086. // 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
  27087. indices.push(pi, pi + shft, pi + 1);
  27088. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27089. pi += 1;
  27090. if (pi === min) {
  27091. p++;
  27092. if (p === lg.length - 1) {
  27093. shft = idx[0] - idx[p];
  27094. l1 = lg[p] - 1;
  27095. l2 = lg[0] - 1;
  27096. }
  27097. else {
  27098. shft = idx[p + 1] - idx[p];
  27099. l1 = lg[p] - 1;
  27100. l2 = lg[p + 1] - 1;
  27101. }
  27102. pi = idx[p];
  27103. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27104. }
  27105. }
  27106. // normals
  27107. VertexData.ComputeNormals(positions, indices, normals);
  27108. if (closePath) {
  27109. var indexFirst = 0;
  27110. var indexLast = 0;
  27111. for (p = 0; p < pathArray.length; p++) {
  27112. indexFirst = idx[p] * 3;
  27113. if (p + 1 < pathArray.length) {
  27114. indexLast = (idx[p + 1] - 1) * 3;
  27115. }
  27116. else {
  27117. indexLast = normals.length - 3;
  27118. }
  27119. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27120. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27121. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27122. normals[indexLast] = normals[indexFirst];
  27123. normals[indexLast + 1] = normals[indexFirst + 1];
  27124. normals[indexLast + 2] = normals[indexFirst + 2];
  27125. }
  27126. }
  27127. // sides
  27128. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27129. // Colors
  27130. if (customColors) {
  27131. var colors = new Float32Array(customColors.length * 4);
  27132. for (var c = 0; c < customColors.length; c++) {
  27133. colors[c * 4] = customColors[c].r;
  27134. colors[c * 4 + 1] = customColors[c].g;
  27135. colors[c * 4 + 2] = customColors[c].b;
  27136. colors[c * 4 + 3] = customColors[c].a;
  27137. }
  27138. }
  27139. // Result
  27140. var vertexData = new VertexData();
  27141. var positions32 = new Float32Array(positions);
  27142. var normals32 = new Float32Array(normals);
  27143. var uvs32 = new Float32Array(uvs);
  27144. vertexData.indices = indices;
  27145. vertexData.positions = positions32;
  27146. vertexData.normals = normals32;
  27147. vertexData.uvs = uvs32;
  27148. if (customColors) {
  27149. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27150. }
  27151. if (closePath) {
  27152. vertexData._idx = idx;
  27153. }
  27154. return vertexData;
  27155. };
  27156. /**
  27157. * Creates the VertexData of the Box.
  27158. */
  27159. VertexData.CreateBox = function (options) {
  27160. var normalsSource = [
  27161. new BABYLON.Vector3(0, 0, 1),
  27162. new BABYLON.Vector3(0, 0, -1),
  27163. new BABYLON.Vector3(1, 0, 0),
  27164. new BABYLON.Vector3(-1, 0, 0),
  27165. new BABYLON.Vector3(0, 1, 0),
  27166. new BABYLON.Vector3(0, -1, 0)
  27167. ];
  27168. var indices = [];
  27169. var positions = [];
  27170. var normals = [];
  27171. var uvs = [];
  27172. var width = options.width || options.size || 1;
  27173. var height = options.height || options.size || 1;
  27174. var depth = options.depth || options.size || 1;
  27175. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27176. var faceUV = options.faceUV || new Array(6);
  27177. var faceColors = options.faceColors;
  27178. var colors = [];
  27179. // default face colors and UV if undefined
  27180. for (var f = 0; f < 6; f++) {
  27181. if (faceUV[f] === undefined) {
  27182. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27183. }
  27184. if (faceColors && faceColors[f] === undefined) {
  27185. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27186. }
  27187. }
  27188. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27189. // Create each face in turn.
  27190. for (var index = 0; index < normalsSource.length; index++) {
  27191. var normal = normalsSource[index];
  27192. // Get two vectors perpendicular to the face normal and to each other.
  27193. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27194. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27195. // Six indices (two triangles) per face.
  27196. var verticesLength = positions.length / 3;
  27197. indices.push(verticesLength);
  27198. indices.push(verticesLength + 1);
  27199. indices.push(verticesLength + 2);
  27200. indices.push(verticesLength);
  27201. indices.push(verticesLength + 2);
  27202. indices.push(verticesLength + 3);
  27203. // Four vertices per face.
  27204. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27205. positions.push(vertex.x, vertex.y, vertex.z);
  27206. normals.push(normal.x, normal.y, normal.z);
  27207. uvs.push(faceUV[index].z, faceUV[index].w);
  27208. if (faceColors) {
  27209. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27210. }
  27211. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27212. positions.push(vertex.x, vertex.y, vertex.z);
  27213. normals.push(normal.x, normal.y, normal.z);
  27214. uvs.push(faceUV[index].x, faceUV[index].w);
  27215. if (faceColors) {
  27216. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27217. }
  27218. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27219. positions.push(vertex.x, vertex.y, vertex.z);
  27220. normals.push(normal.x, normal.y, normal.z);
  27221. uvs.push(faceUV[index].x, faceUV[index].y);
  27222. if (faceColors) {
  27223. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27224. }
  27225. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27226. positions.push(vertex.x, vertex.y, vertex.z);
  27227. normals.push(normal.x, normal.y, normal.z);
  27228. uvs.push(faceUV[index].z, faceUV[index].y);
  27229. if (faceColors) {
  27230. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27231. }
  27232. }
  27233. // sides
  27234. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27235. // Result
  27236. var vertexData = new VertexData();
  27237. vertexData.indices = indices;
  27238. vertexData.positions = positions;
  27239. vertexData.normals = normals;
  27240. vertexData.uvs = uvs;
  27241. if (faceColors) {
  27242. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27243. vertexData.colors = totalColors;
  27244. }
  27245. return vertexData;
  27246. };
  27247. /**
  27248. * Creates the VertexData of the Sphere.
  27249. */
  27250. VertexData.CreateSphere = function (options) {
  27251. var segments = options.segments || 32;
  27252. var diameterX = options.diameterX || options.diameter || 1;
  27253. var diameterY = options.diameterY || options.diameter || 1;
  27254. var diameterZ = options.diameterZ || options.diameter || 1;
  27255. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27256. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27257. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27258. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27259. var totalZRotationSteps = 2 + segments;
  27260. var totalYRotationSteps = 2 * totalZRotationSteps;
  27261. var indices = [];
  27262. var positions = [];
  27263. var normals = [];
  27264. var uvs = [];
  27265. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27266. var normalizedZ = zRotationStep / totalZRotationSteps;
  27267. var angleZ = normalizedZ * Math.PI * slice;
  27268. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27269. var normalizedY = yRotationStep / totalYRotationSteps;
  27270. var angleY = normalizedY * Math.PI * 2 * arc;
  27271. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27272. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27273. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27274. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27275. var vertex = complete.multiply(radius);
  27276. var normal = complete.divide(radius).normalize();
  27277. positions.push(vertex.x, vertex.y, vertex.z);
  27278. normals.push(normal.x, normal.y, normal.z);
  27279. uvs.push(normalizedY, normalizedZ);
  27280. }
  27281. if (zRotationStep > 0) {
  27282. var verticesCount = positions.length / 3;
  27283. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27284. indices.push((firstIndex));
  27285. indices.push((firstIndex + 1));
  27286. indices.push(firstIndex + totalYRotationSteps + 1);
  27287. indices.push((firstIndex + totalYRotationSteps + 1));
  27288. indices.push((firstIndex + 1));
  27289. indices.push((firstIndex + totalYRotationSteps + 2));
  27290. }
  27291. }
  27292. }
  27293. // Sides
  27294. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27295. // Result
  27296. var vertexData = new VertexData();
  27297. vertexData.indices = indices;
  27298. vertexData.positions = positions;
  27299. vertexData.normals = normals;
  27300. vertexData.uvs = uvs;
  27301. return vertexData;
  27302. };
  27303. /**
  27304. * Creates the VertexData of the Cylinder or Cone.
  27305. */
  27306. VertexData.CreateCylinder = function (options) {
  27307. var height = options.height || 2;
  27308. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27309. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27310. var tessellation = options.tessellation || 24;
  27311. var subdivisions = options.subdivisions || 1;
  27312. var hasRings = options.hasRings;
  27313. var enclose = options.enclose;
  27314. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27315. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27316. var faceUV = options.faceUV || new Array(3);
  27317. var faceColors = options.faceColors;
  27318. // default face colors and UV if undefined
  27319. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27320. var ringNb = (hasRings) ? subdivisions : 1;
  27321. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27322. var f;
  27323. for (f = 0; f < surfaceNb; f++) {
  27324. if (faceColors && faceColors[f] === undefined) {
  27325. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27326. }
  27327. }
  27328. for (f = 0; f < surfaceNb; f++) {
  27329. if (faceUV && faceUV[f] === undefined) {
  27330. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27331. }
  27332. }
  27333. var indices = [];
  27334. var positions = [];
  27335. var normals = [];
  27336. var uvs = [];
  27337. var colors = [];
  27338. var angle_step = Math.PI * 2 * arc / tessellation;
  27339. var angle;
  27340. var h;
  27341. var radius;
  27342. var tan = (diameterBottom - diameterTop) / 2 / height;
  27343. var ringVertex = BABYLON.Vector3.Zero();
  27344. var ringNormal = BABYLON.Vector3.Zero();
  27345. var ringFirstVertex = BABYLON.Vector3.Zero();
  27346. var ringFirstNormal = BABYLON.Vector3.Zero();
  27347. var quadNormal = BABYLON.Vector3.Zero();
  27348. var Y = BABYLON.Axis.Y;
  27349. // positions, normals, uvs
  27350. var i;
  27351. var j;
  27352. var r;
  27353. var ringIdx = 1;
  27354. var s = 1; // surface index
  27355. var cs = 0;
  27356. var v = 0;
  27357. for (i = 0; i <= subdivisions; i++) {
  27358. h = i / subdivisions;
  27359. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27360. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27361. for (r = 0; r < ringIdx; r++) {
  27362. if (hasRings) {
  27363. s += r;
  27364. }
  27365. if (enclose) {
  27366. s += 2 * r;
  27367. }
  27368. for (j = 0; j <= tessellation; j++) {
  27369. angle = j * angle_step;
  27370. // position
  27371. ringVertex.x = Math.cos(-angle) * radius;
  27372. ringVertex.y = -height / 2 + h * height;
  27373. ringVertex.z = Math.sin(-angle) * radius;
  27374. // normal
  27375. if (diameterTop === 0 && i === subdivisions) {
  27376. // if no top cap, reuse former normals
  27377. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27378. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27379. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27380. }
  27381. else {
  27382. ringNormal.x = ringVertex.x;
  27383. ringNormal.z = ringVertex.z;
  27384. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27385. ringNormal.normalize();
  27386. }
  27387. // keep first ring vertex values for enclose
  27388. if (j === 0) {
  27389. ringFirstVertex.copyFrom(ringVertex);
  27390. ringFirstNormal.copyFrom(ringNormal);
  27391. }
  27392. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27393. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27394. if (hasRings) {
  27395. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27396. }
  27397. else {
  27398. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27399. }
  27400. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27401. if (faceColors) {
  27402. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27403. }
  27404. }
  27405. // if enclose, add four vertices and their dedicated normals
  27406. if (arc !== 1 && enclose) {
  27407. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27408. positions.push(0, ringVertex.y, 0);
  27409. positions.push(0, ringVertex.y, 0);
  27410. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27411. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27412. quadNormal.normalize();
  27413. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27414. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27415. quadNormal.normalize();
  27416. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27417. if (hasRings) {
  27418. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27419. }
  27420. else {
  27421. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27422. }
  27423. uvs.push(faceUV[s + 1].x, v);
  27424. uvs.push(faceUV[s + 1].z, v);
  27425. if (hasRings) {
  27426. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27427. }
  27428. else {
  27429. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27430. }
  27431. uvs.push(faceUV[s + 2].x, v);
  27432. uvs.push(faceUV[s + 2].z, v);
  27433. if (faceColors) {
  27434. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27435. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27436. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27437. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27438. }
  27439. }
  27440. if (cs !== s) {
  27441. cs = s;
  27442. }
  27443. }
  27444. }
  27445. // indices
  27446. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27447. var s;
  27448. i = 0;
  27449. for (s = 0; s < subdivisions; s++) {
  27450. for (j = 0; j < tessellation; j++) {
  27451. var i0 = i * (e + 1) + j;
  27452. var i1 = (i + 1) * (e + 1) + j;
  27453. var i2 = i * (e + 1) + (j + 1);
  27454. var i3 = (i + 1) * (e + 1) + (j + 1);
  27455. indices.push(i0, i1, i2);
  27456. indices.push(i3, i2, i1);
  27457. }
  27458. if (arc !== 1 && enclose) {
  27459. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27460. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27461. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27462. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27463. }
  27464. i = (hasRings) ? (i + 2) : (i + 1);
  27465. }
  27466. // Caps
  27467. var createCylinderCap = function (isTop) {
  27468. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27469. if (radius === 0) {
  27470. return;
  27471. }
  27472. // Cap positions, normals & uvs
  27473. var angle;
  27474. var circleVector;
  27475. var i;
  27476. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27477. var c;
  27478. if (faceColors) {
  27479. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27480. }
  27481. // cap center
  27482. var vbase = positions.length / 3;
  27483. var offset = isTop ? height / 2 : -height / 2;
  27484. var center = new BABYLON.Vector3(0, offset, 0);
  27485. positions.push(center.x, center.y, center.z);
  27486. normals.push(0, isTop ? 1 : -1, 0);
  27487. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27488. if (faceColors) {
  27489. colors.push(c.r, c.g, c.b, c.a);
  27490. }
  27491. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27492. for (i = 0; i <= tessellation; i++) {
  27493. angle = Math.PI * 2 * i * arc / tessellation;
  27494. var cos = Math.cos(-angle);
  27495. var sin = Math.sin(-angle);
  27496. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27497. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27498. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27499. normals.push(0, isTop ? 1 : -1, 0);
  27500. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27501. if (faceColors) {
  27502. colors.push(c.r, c.g, c.b, c.a);
  27503. }
  27504. }
  27505. // Cap indices
  27506. for (i = 0; i < tessellation; i++) {
  27507. if (!isTop) {
  27508. indices.push(vbase);
  27509. indices.push(vbase + (i + 1));
  27510. indices.push(vbase + (i + 2));
  27511. }
  27512. else {
  27513. indices.push(vbase);
  27514. indices.push(vbase + (i + 2));
  27515. indices.push(vbase + (i + 1));
  27516. }
  27517. }
  27518. };
  27519. // add caps to geometry
  27520. createCylinderCap(false);
  27521. createCylinderCap(true);
  27522. // Sides
  27523. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27524. var vertexData = new VertexData();
  27525. vertexData.indices = indices;
  27526. vertexData.positions = positions;
  27527. vertexData.normals = normals;
  27528. vertexData.uvs = uvs;
  27529. if (faceColors) {
  27530. vertexData.colors = colors;
  27531. }
  27532. return vertexData;
  27533. };
  27534. /**
  27535. * Creates the VertexData of the Torus.
  27536. */
  27537. VertexData.CreateTorus = function (options) {
  27538. var indices = [];
  27539. var positions = [];
  27540. var normals = [];
  27541. var uvs = [];
  27542. var diameter = options.diameter || 1;
  27543. var thickness = options.thickness || 0.5;
  27544. var tessellation = options.tessellation || 16;
  27545. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27546. var stride = tessellation + 1;
  27547. for (var i = 0; i <= tessellation; i++) {
  27548. var u = i / tessellation;
  27549. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27550. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27551. for (var j = 0; j <= tessellation; j++) {
  27552. var v = 1 - j / tessellation;
  27553. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27554. var dx = Math.cos(innerAngle);
  27555. var dy = Math.sin(innerAngle);
  27556. // Create a vertex.
  27557. var normal = new BABYLON.Vector3(dx, dy, 0);
  27558. var position = normal.scale(thickness / 2);
  27559. var textureCoordinate = new BABYLON.Vector2(u, v);
  27560. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27561. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27562. positions.push(position.x, position.y, position.z);
  27563. normals.push(normal.x, normal.y, normal.z);
  27564. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27565. // And create indices for two triangles.
  27566. var nextI = (i + 1) % stride;
  27567. var nextJ = (j + 1) % stride;
  27568. indices.push(i * stride + j);
  27569. indices.push(i * stride + nextJ);
  27570. indices.push(nextI * stride + j);
  27571. indices.push(i * stride + nextJ);
  27572. indices.push(nextI * stride + nextJ);
  27573. indices.push(nextI * stride + j);
  27574. }
  27575. }
  27576. // Sides
  27577. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27578. // Result
  27579. var vertexData = new VertexData();
  27580. vertexData.indices = indices;
  27581. vertexData.positions = positions;
  27582. vertexData.normals = normals;
  27583. vertexData.uvs = uvs;
  27584. return vertexData;
  27585. };
  27586. /**
  27587. * Creates the VertexData of the LineSystem.
  27588. */
  27589. VertexData.CreateLineSystem = function (options) {
  27590. var indices = [];
  27591. var positions = [];
  27592. var lines = options.lines;
  27593. var idx = 0;
  27594. for (var l = 0; l < lines.length; l++) {
  27595. var points = lines[l];
  27596. for (var index = 0; index < points.length; index++) {
  27597. positions.push(points[index].x, points[index].y, points[index].z);
  27598. if (index > 0) {
  27599. indices.push(idx - 1);
  27600. indices.push(idx);
  27601. }
  27602. idx++;
  27603. }
  27604. }
  27605. var vertexData = new VertexData();
  27606. vertexData.indices = indices;
  27607. vertexData.positions = positions;
  27608. return vertexData;
  27609. };
  27610. /**
  27611. * Create the VertexData of the DashedLines.
  27612. */
  27613. VertexData.CreateDashedLines = function (options) {
  27614. var dashSize = options.dashSize || 3;
  27615. var gapSize = options.gapSize || 1;
  27616. var dashNb = options.dashNb || 200;
  27617. var points = options.points;
  27618. var positions = new Array();
  27619. var indices = new Array();
  27620. var curvect = BABYLON.Vector3.Zero();
  27621. var lg = 0;
  27622. var nb = 0;
  27623. var shft = 0;
  27624. var dashshft = 0;
  27625. var curshft = 0;
  27626. var idx = 0;
  27627. var i = 0;
  27628. for (i = 0; i < points.length - 1; i++) {
  27629. points[i + 1].subtractToRef(points[i], curvect);
  27630. lg += curvect.length();
  27631. }
  27632. shft = lg / dashNb;
  27633. dashshft = dashSize * shft / (dashSize + gapSize);
  27634. for (i = 0; i < points.length - 1; i++) {
  27635. points[i + 1].subtractToRef(points[i], curvect);
  27636. nb = Math.floor(curvect.length() / shft);
  27637. curvect.normalize();
  27638. for (var j = 0; j < nb; j++) {
  27639. curshft = shft * j;
  27640. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27641. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27642. indices.push(idx, idx + 1);
  27643. idx += 2;
  27644. }
  27645. }
  27646. // Result
  27647. var vertexData = new VertexData();
  27648. vertexData.positions = positions;
  27649. vertexData.indices = indices;
  27650. return vertexData;
  27651. };
  27652. /**
  27653. * Creates the VertexData of the Ground.
  27654. */
  27655. VertexData.CreateGround = function (options) {
  27656. var indices = [];
  27657. var positions = [];
  27658. var normals = [];
  27659. var uvs = [];
  27660. var row, col;
  27661. var width = options.width || 1;
  27662. var height = options.height || 1;
  27663. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27664. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27665. for (row = 0; row <= subdivisionsY; row++) {
  27666. for (col = 0; col <= subdivisionsX; col++) {
  27667. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27668. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27669. positions.push(position.x, position.y, position.z);
  27670. normals.push(normal.x, normal.y, normal.z);
  27671. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27672. }
  27673. }
  27674. for (row = 0; row < subdivisionsY; row++) {
  27675. for (col = 0; col < subdivisionsX; col++) {
  27676. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27677. indices.push(col + 1 + row * (subdivisionsX + 1));
  27678. indices.push(col + row * (subdivisionsX + 1));
  27679. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27680. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27681. indices.push(col + row * (subdivisionsX + 1));
  27682. }
  27683. }
  27684. // Result
  27685. var vertexData = new VertexData();
  27686. vertexData.indices = indices;
  27687. vertexData.positions = positions;
  27688. vertexData.normals = normals;
  27689. vertexData.uvs = uvs;
  27690. return vertexData;
  27691. };
  27692. /**
  27693. * Creates the VertexData of the TiledGround.
  27694. */
  27695. VertexData.CreateTiledGround = function (options) {
  27696. var xmin = options.xmin || -1.0;
  27697. var zmin = options.zmin || -1.0;
  27698. var xmax = options.xmax || 1.0;
  27699. var zmax = options.zmax || 1.0;
  27700. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27701. var precision = options.precision || { w: 1, h: 1 };
  27702. var indices = [];
  27703. var positions = [];
  27704. var normals = [];
  27705. var uvs = [];
  27706. var row, col, tileRow, tileCol;
  27707. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27708. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27709. precision.w = (precision.w < 1) ? 1 : precision.w;
  27710. precision.h = (precision.h < 1) ? 1 : precision.h;
  27711. var tileSize = {
  27712. 'w': (xmax - xmin) / subdivisions.w,
  27713. 'h': (zmax - zmin) / subdivisions.h
  27714. };
  27715. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27716. // Indices
  27717. var base = positions.length / 3;
  27718. var rowLength = precision.w + 1;
  27719. for (row = 0; row < precision.h; row++) {
  27720. for (col = 0; col < precision.w; col++) {
  27721. var square = [
  27722. base + col + row * rowLength,
  27723. base + (col + 1) + row * rowLength,
  27724. base + (col + 1) + (row + 1) * rowLength,
  27725. base + col + (row + 1) * rowLength
  27726. ];
  27727. indices.push(square[1]);
  27728. indices.push(square[2]);
  27729. indices.push(square[3]);
  27730. indices.push(square[0]);
  27731. indices.push(square[1]);
  27732. indices.push(square[3]);
  27733. }
  27734. }
  27735. // Position, normals and uvs
  27736. var position = BABYLON.Vector3.Zero();
  27737. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27738. for (row = 0; row <= precision.h; row++) {
  27739. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27740. for (col = 0; col <= precision.w; col++) {
  27741. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27742. position.y = 0;
  27743. positions.push(position.x, position.y, position.z);
  27744. normals.push(normal.x, normal.y, normal.z);
  27745. uvs.push(col / precision.w, row / precision.h);
  27746. }
  27747. }
  27748. }
  27749. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27750. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27751. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27752. }
  27753. }
  27754. // Result
  27755. var vertexData = new VertexData();
  27756. vertexData.indices = indices;
  27757. vertexData.positions = positions;
  27758. vertexData.normals = normals;
  27759. vertexData.uvs = uvs;
  27760. return vertexData;
  27761. };
  27762. /**
  27763. * Creates the VertexData of the Ground designed from a heightmap.
  27764. */
  27765. VertexData.CreateGroundFromHeightMap = function (options) {
  27766. var indices = [];
  27767. var positions = [];
  27768. var normals = [];
  27769. var uvs = [];
  27770. var row, col;
  27771. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27772. // Vertices
  27773. for (row = 0; row <= options.subdivisions; row++) {
  27774. for (col = 0; col <= options.subdivisions; col++) {
  27775. 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));
  27776. // Compute height
  27777. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27778. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27779. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27780. var r = options.buffer[pos] / 255.0;
  27781. var g = options.buffer[pos + 1] / 255.0;
  27782. var b = options.buffer[pos + 2] / 255.0;
  27783. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27784. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27785. // Add vertex
  27786. positions.push(position.x, position.y, position.z);
  27787. normals.push(0, 0, 0);
  27788. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27789. }
  27790. }
  27791. // Indices
  27792. for (row = 0; row < options.subdivisions; row++) {
  27793. for (col = 0; col < options.subdivisions; col++) {
  27794. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27795. indices.push(col + 1 + row * (options.subdivisions + 1));
  27796. indices.push(col + row * (options.subdivisions + 1));
  27797. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27798. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27799. indices.push(col + row * (options.subdivisions + 1));
  27800. }
  27801. }
  27802. // Normals
  27803. VertexData.ComputeNormals(positions, indices, normals);
  27804. // Result
  27805. var vertexData = new VertexData();
  27806. vertexData.indices = indices;
  27807. vertexData.positions = positions;
  27808. vertexData.normals = normals;
  27809. vertexData.uvs = uvs;
  27810. return vertexData;
  27811. };
  27812. /**
  27813. * Creates the VertexData of the Plane.
  27814. */
  27815. VertexData.CreatePlane = function (options) {
  27816. var indices = [];
  27817. var positions = [];
  27818. var normals = [];
  27819. var uvs = [];
  27820. var width = options.width || options.size || 1;
  27821. var height = options.height || options.size || 1;
  27822. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27823. // Vertices
  27824. var halfWidth = width / 2.0;
  27825. var halfHeight = height / 2.0;
  27826. positions.push(-halfWidth, -halfHeight, 0);
  27827. normals.push(0, 0, -1.0);
  27828. uvs.push(0.0, 0.0);
  27829. positions.push(halfWidth, -halfHeight, 0);
  27830. normals.push(0, 0, -1.0);
  27831. uvs.push(1.0, 0.0);
  27832. positions.push(halfWidth, halfHeight, 0);
  27833. normals.push(0, 0, -1.0);
  27834. uvs.push(1.0, 1.0);
  27835. positions.push(-halfWidth, halfHeight, 0);
  27836. normals.push(0, 0, -1.0);
  27837. uvs.push(0.0, 1.0);
  27838. // Indices
  27839. indices.push(0);
  27840. indices.push(1);
  27841. indices.push(2);
  27842. indices.push(0);
  27843. indices.push(2);
  27844. indices.push(3);
  27845. // Sides
  27846. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27847. // Result
  27848. var vertexData = new VertexData();
  27849. vertexData.indices = indices;
  27850. vertexData.positions = positions;
  27851. vertexData.normals = normals;
  27852. vertexData.uvs = uvs;
  27853. return vertexData;
  27854. };
  27855. /**
  27856. * Creates the VertexData of the Disc or regular Polygon.
  27857. */
  27858. VertexData.CreateDisc = function (options) {
  27859. var positions = [];
  27860. var indices = [];
  27861. var normals = [];
  27862. var uvs = [];
  27863. var radius = options.radius || 0.5;
  27864. var tessellation = options.tessellation || 64;
  27865. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27866. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27867. // positions and uvs
  27868. positions.push(0, 0, 0); // disc center first
  27869. uvs.push(0.5, 0.5);
  27870. var theta = Math.PI * 2 * arc;
  27871. var step = theta / tessellation;
  27872. for (var a = 0; a < theta; a += step) {
  27873. var x = Math.cos(a);
  27874. var y = Math.sin(a);
  27875. var u = (x + 1) / 2;
  27876. var v = (1 - y) / 2;
  27877. positions.push(radius * x, radius * y, 0);
  27878. uvs.push(u, v);
  27879. }
  27880. if (arc === 1) {
  27881. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27882. uvs.push(uvs[2], uvs[3]);
  27883. }
  27884. //indices
  27885. var vertexNb = positions.length / 3;
  27886. for (var i = 1; i < vertexNb - 1; i++) {
  27887. indices.push(i + 1, 0, i);
  27888. }
  27889. // result
  27890. VertexData.ComputeNormals(positions, indices, normals);
  27891. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27892. var vertexData = new VertexData();
  27893. vertexData.indices = indices;
  27894. vertexData.positions = positions;
  27895. vertexData.normals = normals;
  27896. vertexData.uvs = uvs;
  27897. return vertexData;
  27898. };
  27899. /**
  27900. * Re-creates the VertexData of the Polygon for sideOrientation.
  27901. */
  27902. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27903. var faceUV = fUV || new Array(3);
  27904. var faceColors = fColors;
  27905. var colors = [];
  27906. // default face colors and UV if undefined
  27907. for (var f = 0; f < 3; f++) {
  27908. if (faceUV[f] === undefined) {
  27909. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27910. }
  27911. if (faceColors && faceColors[f] === undefined) {
  27912. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27913. }
  27914. }
  27915. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27916. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27917. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27918. var indices = polygon.getIndices();
  27919. // set face colours and textures
  27920. var idx = 0;
  27921. var face = 0;
  27922. for (var index = 0; index < normals.length; index += 3) {
  27923. //Edge Face no. 1
  27924. if (Math.abs(normals[index + 1]) < 0.001) {
  27925. face = 1;
  27926. }
  27927. //Top Face no. 0
  27928. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27929. face = 0;
  27930. }
  27931. //Bottom Face no. 2
  27932. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27933. face = 2;
  27934. }
  27935. idx = index / 3;
  27936. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27937. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27938. if (faceColors) {
  27939. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27940. }
  27941. }
  27942. // sides
  27943. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27944. // Result
  27945. var vertexData = new VertexData();
  27946. vertexData.indices = indices;
  27947. vertexData.positions = positions;
  27948. vertexData.normals = normals;
  27949. vertexData.uvs = uvs;
  27950. if (faceColors) {
  27951. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27952. vertexData.colors = totalColors;
  27953. }
  27954. return vertexData;
  27955. };
  27956. /**
  27957. * Creates the VertexData of the IcoSphere.
  27958. */
  27959. VertexData.CreateIcoSphere = function (options) {
  27960. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27961. var radius = options.radius || 1;
  27962. var flat = (options.flat === undefined) ? true : options.flat;
  27963. var subdivisions = options.subdivisions || 4;
  27964. var radiusX = options.radiusX || radius;
  27965. var radiusY = options.radiusY || radius;
  27966. var radiusZ = options.radiusZ || radius;
  27967. var t = (1 + Math.sqrt(5)) / 2;
  27968. // 12 vertex x,y,z
  27969. var ico_vertices = [
  27970. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27971. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27972. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27973. ];
  27974. // index of 3 vertex makes a face of icopshere
  27975. var ico_indices = [
  27976. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27977. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27978. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27979. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27980. ];
  27981. // vertex for uv have aliased position, not for UV
  27982. var vertices_unalias_id = [
  27983. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27984. // vertex alias
  27985. 0,
  27986. 2,
  27987. 3,
  27988. 3,
  27989. 3,
  27990. 4,
  27991. 7,
  27992. 8,
  27993. 9,
  27994. 9,
  27995. 10,
  27996. 11 // 23: B + 12
  27997. ];
  27998. // uv as integer step (not pixels !)
  27999. var ico_vertexuv = [
  28000. 5, 1, 3, 1, 6, 4, 0, 0,
  28001. 5, 3, 4, 2, 2, 2, 4, 0,
  28002. 2, 0, 1, 1, 6, 0, 6, 2,
  28003. // vertex alias (for same vertex on different faces)
  28004. 0, 4,
  28005. 3, 3,
  28006. 4, 4,
  28007. 3, 1,
  28008. 4, 2,
  28009. 4, 4,
  28010. 0, 2,
  28011. 1, 1,
  28012. 2, 2,
  28013. 3, 3,
  28014. 1, 3,
  28015. 2, 4 // 23: B + 12
  28016. ];
  28017. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28018. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28019. // First island of uv mapping
  28020. // v = 4h 3+ 2
  28021. // v = 3h 9+ 4
  28022. // v = 2h 9+ 5 B
  28023. // v = 1h 9 1 0
  28024. // v = 0h 3 8 7 A
  28025. // u = 0 1 2 3 4 5 6 *a
  28026. // Second island of uv mapping
  28027. // v = 4h 0+ B+ 4+
  28028. // v = 3h A+ 2+
  28029. // v = 2h 7+ 6 3+
  28030. // v = 1h 8+ 3+
  28031. // v = 0h
  28032. // u = 0 1 2 3 4 5 6 *a
  28033. // Face layout on texture UV mapping
  28034. // ============
  28035. // \ 4 /\ 16 / ======
  28036. // \ / \ / /\ 11 /
  28037. // \/ 7 \/ / \ /
  28038. // ======= / 10 \/
  28039. // /\ 17 /\ =======
  28040. // / \ / \ \ 15 /\
  28041. // / 8 \/ 12 \ \ / \
  28042. // ============ \/ 6 \
  28043. // \ 18 /\ ============
  28044. // \ / \ \ 5 /\ 0 /
  28045. // \/ 13 \ \ / \ /
  28046. // ======= \/ 1 \/
  28047. // =============
  28048. // /\ 19 /\ 2 /\
  28049. // / \ / \ / \
  28050. // / 14 \/ 9 \/ 3 \
  28051. // ===================
  28052. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28053. var ustep = 138 / 1024;
  28054. var vstep = 239 / 1024;
  28055. var uoffset = 60 / 1024;
  28056. var voffset = 26 / 1024;
  28057. // Second island should have margin, not to touch the first island
  28058. // avoid any borderline artefact in pixel rounding
  28059. var island_u_offset = -40 / 1024;
  28060. var island_v_offset = +20 / 1024;
  28061. // face is either island 0 or 1 :
  28062. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28063. var island = [
  28064. 0, 0, 0, 0, 1,
  28065. 0, 0, 1, 1, 0,
  28066. 0, 0, 1, 1, 0,
  28067. 0, 1, 1, 1, 0 // 15 - 19
  28068. ];
  28069. var indices = [];
  28070. var positions = [];
  28071. var normals = [];
  28072. var uvs = [];
  28073. var current_indice = 0;
  28074. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28075. var face_vertex_pos = new Array(3);
  28076. var face_vertex_uv = new Array(3);
  28077. var v012;
  28078. for (v012 = 0; v012 < 3; v012++) {
  28079. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28080. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28081. }
  28082. // create all with normals
  28083. for (var face = 0; face < 20; face++) {
  28084. // 3 vertex per face
  28085. for (v012 = 0; v012 < 3; v012++) {
  28086. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28087. var v_id = ico_indices[3 * face + v012];
  28088. // vertex have 3D position (x,y,z)
  28089. 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]);
  28090. // Normalize to get normal, then scale to radius
  28091. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28092. // uv Coordinates from vertex ID
  28093. 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);
  28094. }
  28095. // Subdivide the face (interpolate pos, norm, uv)
  28096. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28097. // - norm is linear interpolation of vertex corner normal
  28098. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28099. // - uv is linear interpolation
  28100. //
  28101. // Topology is as below for sub-divide by 2
  28102. // vertex shown as v0,v1,v2
  28103. // interp index is i1 to progress in range [v0,v1[
  28104. // interp index is i2 to progress in range [v0,v2[
  28105. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28106. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28107. //
  28108. //
  28109. // i2 v2
  28110. // ^ ^
  28111. // / / \
  28112. // / / \
  28113. // / / \
  28114. // / / (0,1) \
  28115. // / #---------\
  28116. // / / \ (0,0)'/ \
  28117. // / / \ / \
  28118. // / / \ / \
  28119. // / / (0,0) \ / (1,0) \
  28120. // / #---------#---------\
  28121. // v0 v1
  28122. //
  28123. // --------------------> i1
  28124. //
  28125. // interp of (i1,i2):
  28126. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28127. // along i1 : lerp(x0,x1, i1/(S-i2))
  28128. //
  28129. // centroid of triangle is needed to get help normal computation
  28130. // (c1,c2) are used for centroid location
  28131. var interp_vertex = function (i1, i2, c1, c2) {
  28132. // vertex is interpolated from
  28133. // - face_vertex_pos[0..2]
  28134. // - face_vertex_uv[0..2]
  28135. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28136. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28137. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28138. pos_interp.normalize();
  28139. var vertex_normal;
  28140. if (flat) {
  28141. // in flat mode, recalculate normal as face centroid normal
  28142. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28143. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28144. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28145. }
  28146. else {
  28147. // in smooth mode, recalculate normal from each single vertex position
  28148. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28149. }
  28150. // Vertex normal need correction due to X,Y,Z radius scaling
  28151. vertex_normal.x /= radiusX;
  28152. vertex_normal.y /= radiusY;
  28153. vertex_normal.z /= radiusZ;
  28154. vertex_normal.normalize();
  28155. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28156. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28157. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28158. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28159. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28160. uvs.push(uv_interp.x, uv_interp.y);
  28161. // push each vertex has member of a face
  28162. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28163. indices.push(current_indice);
  28164. current_indice++;
  28165. };
  28166. for (var i2 = 0; i2 < subdivisions; i2++) {
  28167. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28168. // face : (i1,i2) for /\ :
  28169. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28170. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28171. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28172. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28173. if (i1 + i2 + 1 < subdivisions) {
  28174. // face : (i1,i2)' for \/ :
  28175. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28176. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28177. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28178. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28179. }
  28180. }
  28181. }
  28182. }
  28183. // Sides
  28184. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28185. // Result
  28186. var vertexData = new VertexData();
  28187. vertexData.indices = indices;
  28188. vertexData.positions = positions;
  28189. vertexData.normals = normals;
  28190. vertexData.uvs = uvs;
  28191. return vertexData;
  28192. };
  28193. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28194. /**
  28195. * Creates the VertexData of the Polyhedron.
  28196. */
  28197. VertexData.CreatePolyhedron = function (options) {
  28198. // provided polyhedron types :
  28199. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28200. // 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)
  28201. var polyhedra = [];
  28202. 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]] };
  28203. 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]] };
  28204. polyhedra[2] = {
  28205. 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]],
  28206. 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]]
  28207. };
  28208. polyhedra[3] = {
  28209. 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]],
  28210. 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]]
  28211. };
  28212. polyhedra[4] = {
  28213. 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]],
  28214. 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]]
  28215. };
  28216. 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]] };
  28217. 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]] };
  28218. 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]] };
  28219. 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]] };
  28220. 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]] };
  28221. 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]] };
  28222. 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]] };
  28223. 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]] };
  28224. 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]] };
  28225. polyhedra[14] = {
  28226. 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]],
  28227. 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]]
  28228. };
  28229. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28230. var size = options.size;
  28231. var sizeX = options.sizeX || size || 1;
  28232. var sizeY = options.sizeY || size || 1;
  28233. var sizeZ = options.sizeZ || size || 1;
  28234. var data = options.custom || polyhedra[type];
  28235. var nbfaces = data.face.length;
  28236. var faceUV = options.faceUV || new Array(nbfaces);
  28237. var faceColors = options.faceColors;
  28238. var flat = (options.flat === undefined) ? true : options.flat;
  28239. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28240. var positions = [];
  28241. var indices = [];
  28242. var normals = [];
  28243. var uvs = [];
  28244. var colors = [];
  28245. var index = 0;
  28246. var faceIdx = 0; // face cursor in the array "indexes"
  28247. var indexes = [];
  28248. var i = 0;
  28249. var f = 0;
  28250. var u, v, ang, x, y, tmp;
  28251. // default face colors and UV if undefined
  28252. if (flat) {
  28253. for (f = 0; f < nbfaces; f++) {
  28254. if (faceColors && faceColors[f] === undefined) {
  28255. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28256. }
  28257. if (faceUV && faceUV[f] === undefined) {
  28258. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28259. }
  28260. }
  28261. }
  28262. if (!flat) {
  28263. for (i = 0; i < data.vertex.length; i++) {
  28264. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28265. uvs.push(0, 0);
  28266. }
  28267. for (f = 0; f < nbfaces; f++) {
  28268. for (i = 0; i < data.face[f].length - 2; i++) {
  28269. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28270. }
  28271. }
  28272. }
  28273. else {
  28274. for (f = 0; f < nbfaces; f++) {
  28275. var fl = data.face[f].length; // number of vertices of the current face
  28276. ang = 2 * Math.PI / fl;
  28277. x = 0.5 * Math.tan(ang / 2);
  28278. y = 0.5;
  28279. // positions, uvs, colors
  28280. for (i = 0; i < fl; i++) {
  28281. // positions
  28282. 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);
  28283. indexes.push(index);
  28284. index++;
  28285. // uvs
  28286. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28287. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28288. uvs.push(u, v);
  28289. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28290. y = x * Math.sin(ang) + y * Math.cos(ang);
  28291. x = tmp;
  28292. // colors
  28293. if (faceColors) {
  28294. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28295. }
  28296. }
  28297. // indices from indexes
  28298. for (i = 0; i < fl - 2; i++) {
  28299. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28300. }
  28301. faceIdx += fl;
  28302. }
  28303. }
  28304. VertexData.ComputeNormals(positions, indices, normals);
  28305. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28306. var vertexData = new VertexData();
  28307. vertexData.positions = positions;
  28308. vertexData.indices = indices;
  28309. vertexData.normals = normals;
  28310. vertexData.uvs = uvs;
  28311. if (faceColors && flat) {
  28312. vertexData.colors = colors;
  28313. }
  28314. return vertexData;
  28315. };
  28316. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28317. /**
  28318. * Creates the VertexData of the Torus Knot.
  28319. */
  28320. VertexData.CreateTorusKnot = function (options) {
  28321. var indices = [];
  28322. var positions = [];
  28323. var normals = [];
  28324. var uvs = [];
  28325. var radius = options.radius || 2;
  28326. var tube = options.tube || 0.5;
  28327. var radialSegments = options.radialSegments || 32;
  28328. var tubularSegments = options.tubularSegments || 32;
  28329. var p = options.p || 2;
  28330. var q = options.q || 3;
  28331. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28332. // Helper
  28333. var getPos = function (angle) {
  28334. var cu = Math.cos(angle);
  28335. var su = Math.sin(angle);
  28336. var quOverP = q / p * angle;
  28337. var cs = Math.cos(quOverP);
  28338. var tx = radius * (2 + cs) * 0.5 * cu;
  28339. var ty = radius * (2 + cs) * su * 0.5;
  28340. var tz = radius * Math.sin(quOverP) * 0.5;
  28341. return new BABYLON.Vector3(tx, ty, tz);
  28342. };
  28343. // Vertices
  28344. var i;
  28345. var j;
  28346. for (i = 0; i <= radialSegments; i++) {
  28347. var modI = i % radialSegments;
  28348. var u = modI / radialSegments * 2 * p * Math.PI;
  28349. var p1 = getPos(u);
  28350. var p2 = getPos(u + 0.01);
  28351. var tang = p2.subtract(p1);
  28352. var n = p2.add(p1);
  28353. var bitan = BABYLON.Vector3.Cross(tang, n);
  28354. n = BABYLON.Vector3.Cross(bitan, tang);
  28355. bitan.normalize();
  28356. n.normalize();
  28357. for (j = 0; j < tubularSegments; j++) {
  28358. var modJ = j % tubularSegments;
  28359. var v = modJ / tubularSegments * 2 * Math.PI;
  28360. var cx = -tube * Math.cos(v);
  28361. var cy = tube * Math.sin(v);
  28362. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28363. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28364. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28365. uvs.push(i / radialSegments);
  28366. uvs.push(j / tubularSegments);
  28367. }
  28368. }
  28369. for (i = 0; i < radialSegments; i++) {
  28370. for (j = 0; j < tubularSegments; j++) {
  28371. var jNext = (j + 1) % tubularSegments;
  28372. var a = i * tubularSegments + j;
  28373. var b = (i + 1) * tubularSegments + j;
  28374. var c = (i + 1) * tubularSegments + jNext;
  28375. var d = i * tubularSegments + jNext;
  28376. indices.push(d);
  28377. indices.push(b);
  28378. indices.push(a);
  28379. indices.push(d);
  28380. indices.push(c);
  28381. indices.push(b);
  28382. }
  28383. }
  28384. // Normals
  28385. VertexData.ComputeNormals(positions, indices, normals);
  28386. // Sides
  28387. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28388. // Result
  28389. var vertexData = new VertexData();
  28390. vertexData.indices = indices;
  28391. vertexData.positions = positions;
  28392. vertexData.normals = normals;
  28393. vertexData.uvs = uvs;
  28394. return vertexData;
  28395. };
  28396. // Tools
  28397. /**
  28398. * @param {any} - positions (number[] or Float32Array)
  28399. * @param {any} - indices (number[] or Uint16Array)
  28400. * @param {any} - normals (number[] or Float32Array)
  28401. * options (optional) :
  28402. * facetPositions : optional array of facet positions (vector3)
  28403. * facetNormals : optional array of facet normals (vector3)
  28404. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28405. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28406. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28407. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28408. * bInfo : optional bounding info, required for facetPartitioning computation
  28409. */
  28410. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28411. // temporary scalar variables
  28412. var index = 0; // facet index
  28413. var p1p2x = 0.0; // p1p2 vector x coordinate
  28414. var p1p2y = 0.0; // p1p2 vector y coordinate
  28415. var p1p2z = 0.0; // p1p2 vector z coordinate
  28416. var p3p2x = 0.0; // p3p2 vector x coordinate
  28417. var p3p2y = 0.0; // p3p2 vector y coordinate
  28418. var p3p2z = 0.0; // p3p2 vector z coordinate
  28419. var faceNormalx = 0.0; // facet normal x coordinate
  28420. var faceNormaly = 0.0; // facet normal y coordinate
  28421. var faceNormalz = 0.0; // facet normal z coordinate
  28422. var length = 0.0; // facet normal length before normalization
  28423. var v1x = 0; // vector1 x index in the positions array
  28424. var v1y = 0; // vector1 y index in the positions array
  28425. var v1z = 0; // vector1 z index in the positions array
  28426. var v2x = 0; // vector2 x index in the positions array
  28427. var v2y = 0; // vector2 y index in the positions array
  28428. var v2z = 0; // vector2 z index in the positions array
  28429. var v3x = 0; // vector3 x index in the positions array
  28430. var v3y = 0; // vector3 y index in the positions array
  28431. var v3z = 0; // vector3 z index in the positions array
  28432. var computeFacetNormals = false;
  28433. var computeFacetPositions = false;
  28434. var computeFacetPartitioning = false;
  28435. var faceNormalSign = 1;
  28436. if (options) {
  28437. computeFacetNormals = (options.facetNormals) ? true : false;
  28438. computeFacetPositions = (options.facetPositions) ? true : false;
  28439. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28440. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28441. }
  28442. // facetPartitioning reinit if needed
  28443. if (computeFacetPartitioning) {
  28444. var ox = 0; // X partitioning index for facet position
  28445. var oy = 0; // Y partinioning index for facet position
  28446. var oz = 0; // Z partinioning index for facet position
  28447. var b1x = 0; // X partitioning index for facet v1 vertex
  28448. var b1y = 0; // Y partitioning index for facet v1 vertex
  28449. var b1z = 0; // z partitioning index for facet v1 vertex
  28450. var b2x = 0; // X partitioning index for facet v2 vertex
  28451. var b2y = 0; // Y partitioning index for facet v2 vertex
  28452. var b2z = 0; // Z partitioning index for facet v2 vertex
  28453. var b3x = 0; // X partitioning index for facet v3 vertex
  28454. var b3y = 0; // Y partitioning index for facet v3 vertex
  28455. var b3z = 0; // Z partitioning index for facet v3 vertex
  28456. var block_idx_o = 0; // facet barycenter block index
  28457. var block_idx_v1 = 0; // v1 vertex block index
  28458. var block_idx_v2 = 0; // v2 vertex block index
  28459. var block_idx_v3 = 0; // v3 vertex block index
  28460. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28461. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28462. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28463. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28464. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28465. var subSq = options.subDiv.max * options.subDiv.max;
  28466. options.facetPartitioning.length = 0;
  28467. }
  28468. // reset the normals
  28469. for (index = 0; index < positions.length; index++) {
  28470. normals[index] = 0.0;
  28471. }
  28472. // Loop : 1 indice triplet = 1 facet
  28473. var nbFaces = indices.length / 3;
  28474. for (index = 0; index < nbFaces; index++) {
  28475. // get the indexes of the coordinates of each vertex of the facet
  28476. v1x = indices[index * 3] * 3;
  28477. v1y = v1x + 1;
  28478. v1z = v1x + 2;
  28479. v2x = indices[index * 3 + 1] * 3;
  28480. v2y = v2x + 1;
  28481. v2z = v2x + 2;
  28482. v3x = indices[index * 3 + 2] * 3;
  28483. v3y = v3x + 1;
  28484. v3z = v3x + 2;
  28485. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28486. p1p2y = positions[v1y] - positions[v2y];
  28487. p1p2z = positions[v1z] - positions[v2z];
  28488. p3p2x = positions[v3x] - positions[v2x];
  28489. p3p2y = positions[v3y] - positions[v2y];
  28490. p3p2z = positions[v3z] - positions[v2z];
  28491. // compute the face normal with the cross product
  28492. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28493. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28494. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28495. // normalize this normal and store it in the array facetData
  28496. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28497. length = (length === 0) ? 1.0 : length;
  28498. faceNormalx /= length;
  28499. faceNormaly /= length;
  28500. faceNormalz /= length;
  28501. if (computeFacetNormals) {
  28502. options.facetNormals[index].x = faceNormalx;
  28503. options.facetNormals[index].y = faceNormaly;
  28504. options.facetNormals[index].z = faceNormalz;
  28505. }
  28506. if (computeFacetPositions) {
  28507. // compute and the facet barycenter coordinates in the array facetPositions
  28508. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28509. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28510. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28511. }
  28512. if (computeFacetPartitioning) {
  28513. // store the facet indexes in arrays in the main facetPartitioning array :
  28514. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28515. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28516. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28517. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28518. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28519. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28520. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28521. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28522. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28523. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28524. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28525. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28526. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28527. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28528. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28529. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28530. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28531. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28532. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28533. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28534. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28535. // push each facet index in each block containing the vertex
  28536. options.facetPartitioning[block_idx_v1].push(index);
  28537. if (block_idx_v2 != block_idx_v1) {
  28538. options.facetPartitioning[block_idx_v2].push(index);
  28539. }
  28540. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28541. options.facetPartitioning[block_idx_v3].push(index);
  28542. }
  28543. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28544. options.facetPartitioning[block_idx_o].push(index);
  28545. }
  28546. }
  28547. // compute the normals anyway
  28548. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28549. normals[v1y] += faceNormaly;
  28550. normals[v1z] += faceNormalz;
  28551. normals[v2x] += faceNormalx;
  28552. normals[v2y] += faceNormaly;
  28553. normals[v2z] += faceNormalz;
  28554. normals[v3x] += faceNormalx;
  28555. normals[v3y] += faceNormaly;
  28556. normals[v3z] += faceNormalz;
  28557. }
  28558. // last normalization of each normal
  28559. for (index = 0; index < normals.length / 3; index++) {
  28560. faceNormalx = normals[index * 3];
  28561. faceNormaly = normals[index * 3 + 1];
  28562. faceNormalz = normals[index * 3 + 2];
  28563. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28564. length = (length === 0) ? 1.0 : length;
  28565. faceNormalx /= length;
  28566. faceNormaly /= length;
  28567. faceNormalz /= length;
  28568. normals[index * 3] = faceNormalx;
  28569. normals[index * 3 + 1] = faceNormaly;
  28570. normals[index * 3 + 2] = faceNormalz;
  28571. }
  28572. };
  28573. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28574. var li = indices.length;
  28575. var ln = normals.length;
  28576. var i;
  28577. var n;
  28578. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28579. switch (sideOrientation) {
  28580. case BABYLON.Mesh.FRONTSIDE:
  28581. // nothing changed
  28582. break;
  28583. case BABYLON.Mesh.BACKSIDE:
  28584. var tmp;
  28585. // indices
  28586. for (i = 0; i < li; i += 3) {
  28587. tmp = indices[i];
  28588. indices[i] = indices[i + 2];
  28589. indices[i + 2] = tmp;
  28590. }
  28591. // normals
  28592. for (n = 0; n < ln; n++) {
  28593. normals[n] = -normals[n];
  28594. }
  28595. break;
  28596. case BABYLON.Mesh.DOUBLESIDE:
  28597. // positions
  28598. var lp = positions.length;
  28599. var l = lp / 3;
  28600. for (var p = 0; p < lp; p++) {
  28601. positions[lp + p] = positions[p];
  28602. }
  28603. // indices
  28604. for (i = 0; i < li; i += 3) {
  28605. indices[i + li] = indices[i + 2] + l;
  28606. indices[i + 1 + li] = indices[i + 1] + l;
  28607. indices[i + 2 + li] = indices[i] + l;
  28608. }
  28609. // normals
  28610. for (n = 0; n < ln; n++) {
  28611. normals[ln + n] = -normals[n];
  28612. }
  28613. // uvs
  28614. var lu = uvs.length;
  28615. var u = 0;
  28616. for (u = 0; u < lu; u++) {
  28617. uvs[u + lu] = uvs[u];
  28618. }
  28619. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28620. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28621. u = 0;
  28622. for (i = 0; i < lu / 2; i++) {
  28623. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28624. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28625. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28626. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28627. u += 2;
  28628. }
  28629. break;
  28630. }
  28631. };
  28632. /**
  28633. * Creates a new VertexData from the imported parameters.
  28634. */
  28635. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28636. var vertexData = new VertexData();
  28637. // positions
  28638. var positions = parsedVertexData.positions;
  28639. if (positions) {
  28640. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28641. }
  28642. // normals
  28643. var normals = parsedVertexData.normals;
  28644. if (normals) {
  28645. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28646. }
  28647. // tangents
  28648. var tangents = parsedVertexData.tangents;
  28649. if (tangents) {
  28650. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28651. }
  28652. // uvs
  28653. var uvs = parsedVertexData.uvs;
  28654. if (uvs) {
  28655. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28656. }
  28657. // uv2s
  28658. var uv2s = parsedVertexData.uv2s;
  28659. if (uv2s) {
  28660. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28661. }
  28662. // uv3s
  28663. var uv3s = parsedVertexData.uv3s;
  28664. if (uv3s) {
  28665. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28666. }
  28667. // uv4s
  28668. var uv4s = parsedVertexData.uv4s;
  28669. if (uv4s) {
  28670. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28671. }
  28672. // uv5s
  28673. var uv5s = parsedVertexData.uv5s;
  28674. if (uv5s) {
  28675. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28676. }
  28677. // uv6s
  28678. var uv6s = parsedVertexData.uv6s;
  28679. if (uv6s) {
  28680. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28681. }
  28682. // colors
  28683. var colors = parsedVertexData.colors;
  28684. if (colors) {
  28685. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28686. }
  28687. // matricesIndices
  28688. var matricesIndices = parsedVertexData.matricesIndices;
  28689. if (matricesIndices) {
  28690. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28691. }
  28692. // matricesWeights
  28693. var matricesWeights = parsedVertexData.matricesWeights;
  28694. if (matricesWeights) {
  28695. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28696. }
  28697. // indices
  28698. var indices = parsedVertexData.indices;
  28699. if (indices) {
  28700. vertexData.indices = indices;
  28701. }
  28702. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28703. };
  28704. return VertexData;
  28705. }());
  28706. BABYLON.VertexData = VertexData;
  28707. })(BABYLON || (BABYLON = {}));
  28708. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28709. var BABYLON;
  28710. (function (BABYLON) {
  28711. var Geometry = (function () {
  28712. function Geometry(id, scene, vertexData, updatable, mesh) {
  28713. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28714. this._totalVertices = 0;
  28715. this._isDisposed = false;
  28716. this.id = id;
  28717. this._engine = scene.getEngine();
  28718. this._meshes = [];
  28719. this._scene = scene;
  28720. //Init vertex buffer cache
  28721. this._vertexBuffers = {};
  28722. this._indices = [];
  28723. this._updatable = updatable;
  28724. // vertexData
  28725. if (vertexData) {
  28726. this.setAllVerticesData(vertexData, updatable);
  28727. }
  28728. else {
  28729. this._totalVertices = 0;
  28730. this._indices = [];
  28731. }
  28732. if (this._engine.getCaps().vertexArrayObject) {
  28733. this._vertexArrayObjects = {};
  28734. }
  28735. // applyToMesh
  28736. if (mesh) {
  28737. if (mesh.getClassName() === "LinesMesh") {
  28738. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28739. this.updateExtend();
  28740. }
  28741. this.applyToMesh(mesh);
  28742. mesh.computeWorldMatrix(true);
  28743. }
  28744. }
  28745. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28746. /**
  28747. * 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
  28748. * @returns The Bias Vector
  28749. */
  28750. get: function () {
  28751. return this._boundingBias;
  28752. },
  28753. set: function (value) {
  28754. if (this._boundingBias && this._boundingBias.equals(value)) {
  28755. return;
  28756. }
  28757. this._boundingBias = value.clone();
  28758. this.updateBoundingInfo(true, null);
  28759. },
  28760. enumerable: true,
  28761. configurable: true
  28762. });
  28763. Object.defineProperty(Geometry.prototype, "extend", {
  28764. get: function () {
  28765. return this._extend;
  28766. },
  28767. enumerable: true,
  28768. configurable: true
  28769. });
  28770. Geometry.prototype.getScene = function () {
  28771. return this._scene;
  28772. };
  28773. Geometry.prototype.getEngine = function () {
  28774. return this._engine;
  28775. };
  28776. Geometry.prototype.isReady = function () {
  28777. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28778. };
  28779. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28780. get: function () {
  28781. for (var index = 0; index < this._meshes.length; index++) {
  28782. if (!this._meshes[index].doNotSerialize) {
  28783. return false;
  28784. }
  28785. }
  28786. return true;
  28787. },
  28788. enumerable: true,
  28789. configurable: true
  28790. });
  28791. Geometry.prototype._rebuild = function () {
  28792. if (this._vertexArrayObjects) {
  28793. this._vertexArrayObjects = {};
  28794. }
  28795. // Index buffer
  28796. if (this._meshes.length !== 0 && this._indices) {
  28797. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28798. }
  28799. // Vertex buffers
  28800. for (var key in this._vertexBuffers) {
  28801. var vertexBuffer = this._vertexBuffers[key];
  28802. vertexBuffer._rebuild();
  28803. }
  28804. };
  28805. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28806. vertexData.applyToGeometry(this, updatable);
  28807. this.notifyUpdate();
  28808. };
  28809. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28810. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28811. this.setVerticesBuffer(buffer);
  28812. };
  28813. Geometry.prototype.removeVerticesData = function (kind) {
  28814. if (this._vertexBuffers[kind]) {
  28815. this._vertexBuffers[kind].dispose();
  28816. delete this._vertexBuffers[kind];
  28817. }
  28818. };
  28819. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28820. var kind = buffer.getKind();
  28821. if (this._vertexBuffers[kind]) {
  28822. this._vertexBuffers[kind].dispose();
  28823. }
  28824. this._vertexBuffers[kind] = buffer;
  28825. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28826. var data = buffer.getData();
  28827. var stride = buffer.getStrideSize();
  28828. this._totalVertices = data.length / stride;
  28829. this.updateExtend(data, stride);
  28830. this._resetPointsArrayCache();
  28831. var meshes = this._meshes;
  28832. var numOfMeshes = meshes.length;
  28833. for (var index = 0; index < numOfMeshes; index++) {
  28834. var mesh = meshes[index];
  28835. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28836. mesh._createGlobalSubMesh(false);
  28837. mesh.computeWorldMatrix(true);
  28838. }
  28839. }
  28840. this.notifyUpdate(kind);
  28841. if (this._vertexArrayObjects) {
  28842. this._disposeVertexArrayObjects();
  28843. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28844. }
  28845. };
  28846. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28847. var vertexBuffer = this.getVertexBuffer(kind);
  28848. if (!vertexBuffer) {
  28849. return;
  28850. }
  28851. vertexBuffer.updateDirectly(data, offset);
  28852. this.notifyUpdate(kind);
  28853. };
  28854. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28855. var vertexBuffer = this.getVertexBuffer(kind);
  28856. if (!vertexBuffer) {
  28857. return;
  28858. }
  28859. vertexBuffer.update(data);
  28860. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28861. var stride = vertexBuffer.getStrideSize();
  28862. this._totalVertices = data.length / stride;
  28863. this.updateBoundingInfo(updateExtends, data);
  28864. }
  28865. this.notifyUpdate(kind);
  28866. };
  28867. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28868. if (updateExtends) {
  28869. this.updateExtend(data);
  28870. }
  28871. var meshes = this._meshes;
  28872. var numOfMeshes = meshes.length;
  28873. this._resetPointsArrayCache();
  28874. for (var index = 0; index < numOfMeshes; index++) {
  28875. var mesh = meshes[index];
  28876. if (updateExtends) {
  28877. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28878. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28879. var subMesh = mesh.subMeshes[subIndex];
  28880. subMesh.refreshBoundingInfo();
  28881. }
  28882. }
  28883. }
  28884. };
  28885. Geometry.prototype._bind = function (effect, indexToBind) {
  28886. if (indexToBind === void 0) { indexToBind = undefined; }
  28887. if (indexToBind === undefined) {
  28888. indexToBind = this._indexBuffer;
  28889. }
  28890. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28891. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28892. return;
  28893. }
  28894. // Using VAO
  28895. if (!this._vertexArrayObjects[effect.key]) {
  28896. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28897. }
  28898. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28899. };
  28900. Geometry.prototype.getTotalVertices = function () {
  28901. if (!this.isReady()) {
  28902. return 0;
  28903. }
  28904. return this._totalVertices;
  28905. };
  28906. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28907. var vertexBuffer = this.getVertexBuffer(kind);
  28908. if (!vertexBuffer) {
  28909. return null;
  28910. }
  28911. var orig = vertexBuffer.getData();
  28912. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28913. return orig;
  28914. }
  28915. else {
  28916. var len = orig.length;
  28917. var copy = [];
  28918. for (var i = 0; i < len; i++) {
  28919. copy.push(orig[i]);
  28920. }
  28921. return copy;
  28922. }
  28923. };
  28924. Geometry.prototype.getVertexBuffer = function (kind) {
  28925. if (!this.isReady()) {
  28926. return null;
  28927. }
  28928. return this._vertexBuffers[kind];
  28929. };
  28930. Geometry.prototype.getVertexBuffers = function () {
  28931. if (!this.isReady()) {
  28932. return null;
  28933. }
  28934. return this._vertexBuffers;
  28935. };
  28936. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28937. if (!this._vertexBuffers) {
  28938. if (this._delayInfo) {
  28939. return this._delayInfo.indexOf(kind) !== -1;
  28940. }
  28941. return false;
  28942. }
  28943. return this._vertexBuffers[kind] !== undefined;
  28944. };
  28945. Geometry.prototype.getVerticesDataKinds = function () {
  28946. var result = [];
  28947. var kind;
  28948. if (!this._vertexBuffers && this._delayInfo) {
  28949. for (kind in this._delayInfo) {
  28950. result.push(kind);
  28951. }
  28952. }
  28953. else {
  28954. for (kind in this._vertexBuffers) {
  28955. result.push(kind);
  28956. }
  28957. }
  28958. return result;
  28959. };
  28960. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28961. if (this._indexBuffer) {
  28962. this._engine._releaseBuffer(this._indexBuffer);
  28963. }
  28964. this._disposeVertexArrayObjects();
  28965. this._indices = indices;
  28966. if (this._meshes.length !== 0 && this._indices) {
  28967. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28968. }
  28969. if (totalVertices !== undefined) {
  28970. this._totalVertices = totalVertices;
  28971. }
  28972. var meshes = this._meshes;
  28973. var numOfMeshes = meshes.length;
  28974. for (var index = 0; index < numOfMeshes; index++) {
  28975. meshes[index]._createGlobalSubMesh(true);
  28976. }
  28977. this.notifyUpdate();
  28978. };
  28979. Geometry.prototype.getTotalIndices = function () {
  28980. if (!this.isReady()) {
  28981. return 0;
  28982. }
  28983. return this._indices.length;
  28984. };
  28985. Geometry.prototype.getIndices = function (copyWhenShared) {
  28986. if (!this.isReady()) {
  28987. return null;
  28988. }
  28989. var orig = this._indices;
  28990. if (!copyWhenShared || this._meshes.length === 1) {
  28991. return orig;
  28992. }
  28993. else {
  28994. var len = orig.length;
  28995. var copy = [];
  28996. for (var i = 0; i < len; i++) {
  28997. copy.push(orig[i]);
  28998. }
  28999. return copy;
  29000. }
  29001. };
  29002. Geometry.prototype.getIndexBuffer = function () {
  29003. if (!this.isReady()) {
  29004. return null;
  29005. }
  29006. return this._indexBuffer;
  29007. };
  29008. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29009. if (!effect || !this._vertexArrayObjects) {
  29010. return;
  29011. }
  29012. if (this._vertexArrayObjects[effect.key]) {
  29013. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29014. delete this._vertexArrayObjects[effect.key];
  29015. }
  29016. };
  29017. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29018. var meshes = this._meshes;
  29019. var index = meshes.indexOf(mesh);
  29020. if (index === -1) {
  29021. return;
  29022. }
  29023. meshes.splice(index, 1);
  29024. mesh._geometry = null;
  29025. if (meshes.length === 0 && shouldDispose) {
  29026. this.dispose();
  29027. }
  29028. };
  29029. Geometry.prototype.applyToMesh = function (mesh) {
  29030. if (mesh._geometry === this) {
  29031. return;
  29032. }
  29033. var previousGeometry = mesh._geometry;
  29034. if (previousGeometry) {
  29035. previousGeometry.releaseForMesh(mesh);
  29036. }
  29037. var meshes = this._meshes;
  29038. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29039. mesh._geometry = this;
  29040. this._scene.pushGeometry(this);
  29041. meshes.push(mesh);
  29042. if (this.isReady()) {
  29043. this._applyToMesh(mesh);
  29044. }
  29045. else {
  29046. mesh._boundingInfo = this._boundingInfo;
  29047. }
  29048. };
  29049. Geometry.prototype.updateExtend = function (data, stride) {
  29050. if (data === void 0) { data = null; }
  29051. if (!data) {
  29052. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29053. }
  29054. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29055. };
  29056. Geometry.prototype._applyToMesh = function (mesh) {
  29057. var numOfMeshes = this._meshes.length;
  29058. // vertexBuffers
  29059. for (var kind in this._vertexBuffers) {
  29060. if (numOfMeshes === 1) {
  29061. this._vertexBuffers[kind].create();
  29062. }
  29063. var buffer = this._vertexBuffers[kind].getBuffer();
  29064. if (buffer)
  29065. buffer.references = numOfMeshes;
  29066. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29067. if (!this._extend) {
  29068. this.updateExtend(this._vertexBuffers[kind].getData());
  29069. }
  29070. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29071. mesh._createGlobalSubMesh(false);
  29072. //bounding info was just created again, world matrix should be applied again.
  29073. mesh._updateBoundingInfo();
  29074. }
  29075. }
  29076. // indexBuffer
  29077. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29078. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29079. }
  29080. if (this._indexBuffer) {
  29081. this._indexBuffer.references = numOfMeshes;
  29082. }
  29083. };
  29084. Geometry.prototype.notifyUpdate = function (kind) {
  29085. if (this.onGeometryUpdated) {
  29086. this.onGeometryUpdated(this, kind);
  29087. }
  29088. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29089. var mesh = _a[_i];
  29090. mesh._markSubMeshesAsAttributesDirty();
  29091. }
  29092. };
  29093. Geometry.prototype.load = function (scene, onLoaded) {
  29094. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29095. return;
  29096. }
  29097. if (this.isReady()) {
  29098. if (onLoaded) {
  29099. onLoaded();
  29100. }
  29101. return;
  29102. }
  29103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29104. this._queueLoad(scene, onLoaded);
  29105. };
  29106. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29107. var _this = this;
  29108. scene._addPendingData(this);
  29109. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29110. _this._delayLoadingFunction(JSON.parse(data), _this);
  29111. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29112. _this._delayInfo = [];
  29113. scene._removePendingData(_this);
  29114. var meshes = _this._meshes;
  29115. var numOfMeshes = meshes.length;
  29116. for (var index = 0; index < numOfMeshes; index++) {
  29117. _this._applyToMesh(meshes[index]);
  29118. }
  29119. if (onLoaded) {
  29120. onLoaded();
  29121. }
  29122. }, function () { }, scene.database);
  29123. };
  29124. /**
  29125. * Invert the geometry to move from a right handed system to a left handed one.
  29126. */
  29127. Geometry.prototype.toLeftHanded = function () {
  29128. // Flip faces
  29129. var tIndices = this.getIndices(false);
  29130. if (tIndices != null && tIndices.length > 0) {
  29131. for (var i = 0; i < tIndices.length; i += 3) {
  29132. var tTemp = tIndices[i + 0];
  29133. tIndices[i + 0] = tIndices[i + 2];
  29134. tIndices[i + 2] = tTemp;
  29135. }
  29136. this.setIndices(tIndices);
  29137. }
  29138. // Negate position.z
  29139. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29140. if (tPositions != null && tPositions.length > 0) {
  29141. for (var i = 0; i < tPositions.length; i += 3) {
  29142. tPositions[i + 2] = -tPositions[i + 2];
  29143. }
  29144. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29145. }
  29146. // Negate normal.z
  29147. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29148. if (tNormals != null && tNormals.length > 0) {
  29149. for (var i = 0; i < tNormals.length; i += 3) {
  29150. tNormals[i + 2] = -tNormals[i + 2];
  29151. }
  29152. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29153. }
  29154. };
  29155. // Cache
  29156. Geometry.prototype._resetPointsArrayCache = function () {
  29157. this._positions = null;
  29158. };
  29159. Geometry.prototype._generatePointsArray = function () {
  29160. if (this._positions)
  29161. return true;
  29162. this._positions = [];
  29163. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29164. if (!data) {
  29165. return false;
  29166. }
  29167. for (var index = 0; index < data.length; index += 3) {
  29168. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29169. }
  29170. return true;
  29171. };
  29172. Geometry.prototype.isDisposed = function () {
  29173. return this._isDisposed;
  29174. };
  29175. Geometry.prototype._disposeVertexArrayObjects = function () {
  29176. if (this._vertexArrayObjects) {
  29177. for (var kind in this._vertexArrayObjects) {
  29178. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29179. }
  29180. this._vertexArrayObjects = {};
  29181. }
  29182. };
  29183. Geometry.prototype.dispose = function () {
  29184. var meshes = this._meshes;
  29185. var numOfMeshes = meshes.length;
  29186. var index;
  29187. for (index = 0; index < numOfMeshes; index++) {
  29188. this.releaseForMesh(meshes[index]);
  29189. }
  29190. this._meshes = [];
  29191. this._disposeVertexArrayObjects();
  29192. for (var kind in this._vertexBuffers) {
  29193. this._vertexBuffers[kind].dispose();
  29194. }
  29195. this._vertexBuffers = {};
  29196. this._totalVertices = 0;
  29197. if (this._indexBuffer) {
  29198. this._engine._releaseBuffer(this._indexBuffer);
  29199. }
  29200. this._indexBuffer = null;
  29201. this._indices = [];
  29202. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29203. this.delayLoadingFile = null;
  29204. this._delayLoadingFunction = null;
  29205. this._delayInfo = [];
  29206. this._boundingInfo = null;
  29207. this._scene.removeGeometry(this);
  29208. this._isDisposed = true;
  29209. };
  29210. Geometry.prototype.copy = function (id) {
  29211. var vertexData = new BABYLON.VertexData();
  29212. vertexData.indices = [];
  29213. var indices = this.getIndices();
  29214. for (var index = 0; index < indices.length; index++) {
  29215. vertexData.indices.push(indices[index]);
  29216. }
  29217. var updatable = false;
  29218. var stopChecking = false;
  29219. var kind;
  29220. for (kind in this._vertexBuffers) {
  29221. // using slice() to make a copy of the array and not just reference it
  29222. var data = this.getVerticesData(kind);
  29223. if (data instanceof Float32Array) {
  29224. vertexData.set(new Float32Array(data), kind);
  29225. }
  29226. else {
  29227. vertexData.set(data.slice(0), kind);
  29228. }
  29229. if (!stopChecking) {
  29230. updatable = this.getVertexBuffer(kind).isUpdatable();
  29231. stopChecking = !updatable;
  29232. }
  29233. }
  29234. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29235. geometry.delayLoadState = this.delayLoadState;
  29236. geometry.delayLoadingFile = this.delayLoadingFile;
  29237. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29238. for (kind in this._delayInfo) {
  29239. geometry._delayInfo = geometry._delayInfo || [];
  29240. geometry._delayInfo.push(kind);
  29241. }
  29242. // Bounding info
  29243. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29244. return geometry;
  29245. };
  29246. Geometry.prototype.serialize = function () {
  29247. var serializationObject = {};
  29248. serializationObject.id = this.id;
  29249. serializationObject.updatable = this._updatable;
  29250. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29251. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29252. }
  29253. return serializationObject;
  29254. };
  29255. Geometry.prototype.toNumberArray = function (origin) {
  29256. if (Array.isArray(origin)) {
  29257. return origin;
  29258. }
  29259. else {
  29260. return Array.prototype.slice.call(origin);
  29261. }
  29262. };
  29263. Geometry.prototype.serializeVerticeData = function () {
  29264. var serializationObject = this.serialize();
  29265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29266. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29267. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29268. serializationObject.positions._updatable = true;
  29269. }
  29270. }
  29271. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29272. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29273. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29274. serializationObject.normals._updatable = true;
  29275. }
  29276. }
  29277. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29278. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29279. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29280. serializationObject.uvs._updatable = true;
  29281. }
  29282. }
  29283. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29284. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29285. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29286. serializationObject.uv2s._updatable = true;
  29287. }
  29288. }
  29289. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29290. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29291. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29292. serializationObject.uv3s._updatable = true;
  29293. }
  29294. }
  29295. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29296. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29297. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29298. serializationObject.uv4s._updatable = true;
  29299. }
  29300. }
  29301. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29302. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29303. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29304. serializationObject.uv5s._updatable = true;
  29305. }
  29306. }
  29307. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29308. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29309. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29310. serializationObject.uv6s._updatable = true;
  29311. }
  29312. }
  29313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29314. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29315. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29316. serializationObject.colors._updatable = true;
  29317. }
  29318. }
  29319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29320. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29321. serializationObject.matricesIndices._isExpanded = true;
  29322. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29323. serializationObject.matricesIndices._updatable = true;
  29324. }
  29325. }
  29326. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29327. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29328. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29329. serializationObject.matricesWeights._updatable = true;
  29330. }
  29331. }
  29332. serializationObject.indices = this.toNumberArray(this.getIndices());
  29333. return serializationObject;
  29334. };
  29335. // Statics
  29336. Geometry.ExtractFromMesh = function (mesh, id) {
  29337. var geometry = mesh._geometry;
  29338. if (!geometry) {
  29339. return null;
  29340. }
  29341. return geometry.copy(id);
  29342. };
  29343. /**
  29344. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29345. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29346. * Be aware Math.random() could cause collisions, but:
  29347. * "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"
  29348. */
  29349. Geometry.RandomId = function () {
  29350. return BABYLON.Tools.RandomId();
  29351. };
  29352. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29353. var scene = mesh.getScene();
  29354. // Geometry
  29355. var geometryId = parsedGeometry.geometryId;
  29356. if (geometryId) {
  29357. var geometry = scene.getGeometryByID(geometryId);
  29358. if (geometry) {
  29359. geometry.applyToMesh(mesh);
  29360. }
  29361. }
  29362. else if (parsedGeometry instanceof ArrayBuffer) {
  29363. var binaryInfo = mesh._binaryInfo;
  29364. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29365. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29366. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29367. }
  29368. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29369. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29370. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29371. }
  29372. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29373. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29374. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29375. }
  29376. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29377. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29378. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29379. }
  29380. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29381. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29382. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29383. }
  29384. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29385. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29386. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29387. }
  29388. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29389. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29390. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29391. }
  29392. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29393. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29394. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29395. }
  29396. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29397. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29398. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29399. }
  29400. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29401. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29402. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29403. }
  29404. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29405. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29406. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29407. }
  29408. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29409. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29410. mesh.setIndices(indicesData);
  29411. }
  29412. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29413. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29414. mesh.subMeshes = [];
  29415. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29416. var materialIndex = subMeshesData[(i * 5) + 0];
  29417. var verticesStart = subMeshesData[(i * 5) + 1];
  29418. var verticesCount = subMeshesData[(i * 5) + 2];
  29419. var indexStart = subMeshesData[(i * 5) + 3];
  29420. var indexCount = subMeshesData[(i * 5) + 4];
  29421. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29422. }
  29423. }
  29424. }
  29425. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29426. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29427. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29428. if (parsedGeometry.uvs) {
  29429. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29430. }
  29431. if (parsedGeometry.uvs2) {
  29432. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29433. }
  29434. if (parsedGeometry.uvs3) {
  29435. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29436. }
  29437. if (parsedGeometry.uvs4) {
  29438. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29439. }
  29440. if (parsedGeometry.uvs5) {
  29441. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29442. }
  29443. if (parsedGeometry.uvs6) {
  29444. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29445. }
  29446. if (parsedGeometry.colors) {
  29447. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29448. }
  29449. if (parsedGeometry.matricesIndices) {
  29450. if (!parsedGeometry.matricesIndices._isExpanded) {
  29451. var floatIndices = [];
  29452. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29453. var matricesIndex = parsedGeometry.matricesIndices[i];
  29454. floatIndices.push(matricesIndex & 0x000000FF);
  29455. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29456. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29457. floatIndices.push(matricesIndex >> 24);
  29458. }
  29459. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29460. }
  29461. else {
  29462. delete parsedGeometry.matricesIndices._isExpanded;
  29463. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29464. }
  29465. }
  29466. if (parsedGeometry.matricesIndicesExtra) {
  29467. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29468. var floatIndices = [];
  29469. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29470. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29471. floatIndices.push(matricesIndex & 0x000000FF);
  29472. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29473. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29474. floatIndices.push(matricesIndex >> 24);
  29475. }
  29476. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29477. }
  29478. else {
  29479. delete parsedGeometry.matricesIndices._isExpanded;
  29480. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29481. }
  29482. }
  29483. if (parsedGeometry.matricesWeights) {
  29484. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29485. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29486. }
  29487. if (parsedGeometry.matricesWeightsExtra) {
  29488. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29489. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29490. }
  29491. mesh.setIndices(parsedGeometry.indices);
  29492. }
  29493. // SubMeshes
  29494. if (parsedGeometry.subMeshes) {
  29495. mesh.subMeshes = [];
  29496. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29497. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29498. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29499. }
  29500. }
  29501. // Flat shading
  29502. if (mesh._shouldGenerateFlatShading) {
  29503. mesh.convertToFlatShadedMesh();
  29504. delete mesh._shouldGenerateFlatShading;
  29505. }
  29506. // Update
  29507. mesh.computeWorldMatrix(true);
  29508. // Octree
  29509. if (scene['_selectionOctree']) {
  29510. scene['_selectionOctree'].addMesh(mesh);
  29511. }
  29512. };
  29513. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29514. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29515. return;
  29516. }
  29517. var size = matricesWeights.length;
  29518. for (var i = 0; i < size; i += influencers) {
  29519. var weight = 0;
  29520. var biggerIndex = i;
  29521. var biggerWeight = 0;
  29522. for (var j = 0; j < influencers - 1; j++) {
  29523. weight += matricesWeights[i + j];
  29524. if (matricesWeights[i + j] > biggerWeight) {
  29525. biggerWeight = matricesWeights[i + j];
  29526. biggerIndex = i + j;
  29527. }
  29528. }
  29529. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29530. }
  29531. };
  29532. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29533. if (scene.getGeometryByID(parsedVertexData.id)) {
  29534. return null; // null since geometry could be something else than a box...
  29535. }
  29536. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29537. if (BABYLON.Tags) {
  29538. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29539. }
  29540. if (parsedVertexData.delayLoadingFile) {
  29541. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29542. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29543. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29544. geometry._delayInfo = [];
  29545. if (parsedVertexData.hasUVs) {
  29546. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29547. }
  29548. if (parsedVertexData.hasUVs2) {
  29549. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29550. }
  29551. if (parsedVertexData.hasUVs3) {
  29552. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29553. }
  29554. if (parsedVertexData.hasUVs4) {
  29555. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29556. }
  29557. if (parsedVertexData.hasUVs5) {
  29558. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29559. }
  29560. if (parsedVertexData.hasUVs6) {
  29561. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29562. }
  29563. if (parsedVertexData.hasColors) {
  29564. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29565. }
  29566. if (parsedVertexData.hasMatricesIndices) {
  29567. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29568. }
  29569. if (parsedVertexData.hasMatricesWeights) {
  29570. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29571. }
  29572. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29573. }
  29574. else {
  29575. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29576. }
  29577. scene.pushGeometry(geometry, true);
  29578. return geometry;
  29579. };
  29580. return Geometry;
  29581. }());
  29582. BABYLON.Geometry = Geometry;
  29583. /////// Primitives //////////////////////////////////////////////
  29584. (function (Geometry) {
  29585. var Primitives;
  29586. (function (Primitives) {
  29587. /// Abstract class
  29588. var _Primitive = (function (_super) {
  29589. __extends(_Primitive, _super);
  29590. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29591. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29592. _this._canBeRegenerated = _canBeRegenerated;
  29593. _this._beingRegenerated = true;
  29594. _this.regenerate();
  29595. _this._beingRegenerated = false;
  29596. return _this;
  29597. }
  29598. _Primitive.prototype.canBeRegenerated = function () {
  29599. return this._canBeRegenerated;
  29600. };
  29601. _Primitive.prototype.regenerate = function () {
  29602. if (!this._canBeRegenerated) {
  29603. return;
  29604. }
  29605. this._beingRegenerated = true;
  29606. this.setAllVerticesData(this._regenerateVertexData(), false);
  29607. this._beingRegenerated = false;
  29608. };
  29609. _Primitive.prototype.asNewGeometry = function (id) {
  29610. return _super.prototype.copy.call(this, id);
  29611. };
  29612. // overrides
  29613. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29614. if (!this._beingRegenerated) {
  29615. return;
  29616. }
  29617. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29618. };
  29619. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29620. if (!this._beingRegenerated) {
  29621. return;
  29622. }
  29623. _super.prototype.setVerticesData.call(this, kind, data, false);
  29624. };
  29625. // to override
  29626. // protected
  29627. _Primitive.prototype._regenerateVertexData = function () {
  29628. throw new Error("Abstract method");
  29629. };
  29630. _Primitive.prototype.copy = function (id) {
  29631. throw new Error("Must be overriden in sub-classes.");
  29632. };
  29633. _Primitive.prototype.serialize = function () {
  29634. var serializationObject = _super.prototype.serialize.call(this);
  29635. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29636. return serializationObject;
  29637. };
  29638. return _Primitive;
  29639. }(Geometry));
  29640. Primitives._Primitive = _Primitive;
  29641. var Ribbon = (function (_super) {
  29642. __extends(Ribbon, _super);
  29643. // Members
  29644. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29645. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29646. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29647. _this.pathArray = pathArray;
  29648. _this.closeArray = closeArray;
  29649. _this.closePath = closePath;
  29650. _this.offset = offset;
  29651. _this.side = side;
  29652. return _this;
  29653. }
  29654. Ribbon.prototype._regenerateVertexData = function () {
  29655. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29656. };
  29657. Ribbon.prototype.copy = function (id) {
  29658. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29659. };
  29660. return Ribbon;
  29661. }(_Primitive));
  29662. Primitives.Ribbon = Ribbon;
  29663. var Box = (function (_super) {
  29664. __extends(Box, _super);
  29665. // Members
  29666. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29667. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29668. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29669. _this.size = size;
  29670. _this.side = side;
  29671. return _this;
  29672. }
  29673. Box.prototype._regenerateVertexData = function () {
  29674. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29675. };
  29676. Box.prototype.copy = function (id) {
  29677. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29678. };
  29679. Box.prototype.serialize = function () {
  29680. var serializationObject = _super.prototype.serialize.call(this);
  29681. serializationObject.size = this.size;
  29682. return serializationObject;
  29683. };
  29684. Box.Parse = function (parsedBox, scene) {
  29685. if (scene.getGeometryByID(parsedBox.id)) {
  29686. return null; // null since geometry could be something else than a box...
  29687. }
  29688. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29689. if (BABYLON.Tags) {
  29690. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29691. }
  29692. scene.pushGeometry(box, true);
  29693. return box;
  29694. };
  29695. return Box;
  29696. }(_Primitive));
  29697. Primitives.Box = Box;
  29698. var Sphere = (function (_super) {
  29699. __extends(Sphere, _super);
  29700. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29701. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29702. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29703. _this.segments = segments;
  29704. _this.diameter = diameter;
  29705. _this.side = side;
  29706. return _this;
  29707. }
  29708. Sphere.prototype._regenerateVertexData = function () {
  29709. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29710. };
  29711. Sphere.prototype.copy = function (id) {
  29712. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29713. };
  29714. Sphere.prototype.serialize = function () {
  29715. var serializationObject = _super.prototype.serialize.call(this);
  29716. serializationObject.segments = this.segments;
  29717. serializationObject.diameter = this.diameter;
  29718. return serializationObject;
  29719. };
  29720. Sphere.Parse = function (parsedSphere, scene) {
  29721. if (scene.getGeometryByID(parsedSphere.id)) {
  29722. return null; // null since geometry could be something else than a sphere...
  29723. }
  29724. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29725. if (BABYLON.Tags) {
  29726. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29727. }
  29728. scene.pushGeometry(sphere, true);
  29729. return sphere;
  29730. };
  29731. return Sphere;
  29732. }(_Primitive));
  29733. Primitives.Sphere = Sphere;
  29734. var Disc = (function (_super) {
  29735. __extends(Disc, _super);
  29736. // Members
  29737. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29738. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29739. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29740. _this.radius = radius;
  29741. _this.tessellation = tessellation;
  29742. _this.side = side;
  29743. return _this;
  29744. }
  29745. Disc.prototype._regenerateVertexData = function () {
  29746. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29747. };
  29748. Disc.prototype.copy = function (id) {
  29749. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29750. };
  29751. return Disc;
  29752. }(_Primitive));
  29753. Primitives.Disc = Disc;
  29754. var Cylinder = (function (_super) {
  29755. __extends(Cylinder, _super);
  29756. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29757. if (subdivisions === void 0) { subdivisions = 1; }
  29758. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29759. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29760. _this.height = height;
  29761. _this.diameterTop = diameterTop;
  29762. _this.diameterBottom = diameterBottom;
  29763. _this.tessellation = tessellation;
  29764. _this.subdivisions = subdivisions;
  29765. _this.side = side;
  29766. return _this;
  29767. }
  29768. Cylinder.prototype._regenerateVertexData = function () {
  29769. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29770. };
  29771. Cylinder.prototype.copy = function (id) {
  29772. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29773. };
  29774. Cylinder.prototype.serialize = function () {
  29775. var serializationObject = _super.prototype.serialize.call(this);
  29776. serializationObject.height = this.height;
  29777. serializationObject.diameterTop = this.diameterTop;
  29778. serializationObject.diameterBottom = this.diameterBottom;
  29779. serializationObject.tessellation = this.tessellation;
  29780. return serializationObject;
  29781. };
  29782. Cylinder.Parse = function (parsedCylinder, scene) {
  29783. if (scene.getGeometryByID(parsedCylinder.id)) {
  29784. return null; // null since geometry could be something else than a cylinder...
  29785. }
  29786. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29787. if (BABYLON.Tags) {
  29788. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29789. }
  29790. scene.pushGeometry(cylinder, true);
  29791. return cylinder;
  29792. };
  29793. return Cylinder;
  29794. }(_Primitive));
  29795. Primitives.Cylinder = Cylinder;
  29796. var Torus = (function (_super) {
  29797. __extends(Torus, _super);
  29798. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29799. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29800. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29801. _this.diameter = diameter;
  29802. _this.thickness = thickness;
  29803. _this.tessellation = tessellation;
  29804. _this.side = side;
  29805. return _this;
  29806. }
  29807. Torus.prototype._regenerateVertexData = function () {
  29808. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29809. };
  29810. Torus.prototype.copy = function (id) {
  29811. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29812. };
  29813. Torus.prototype.serialize = function () {
  29814. var serializationObject = _super.prototype.serialize.call(this);
  29815. serializationObject.diameter = this.diameter;
  29816. serializationObject.thickness = this.thickness;
  29817. serializationObject.tessellation = this.tessellation;
  29818. return serializationObject;
  29819. };
  29820. Torus.Parse = function (parsedTorus, scene) {
  29821. if (scene.getGeometryByID(parsedTorus.id)) {
  29822. return null; // null since geometry could be something else than a torus...
  29823. }
  29824. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29825. if (BABYLON.Tags) {
  29826. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29827. }
  29828. scene.pushGeometry(torus, true);
  29829. return torus;
  29830. };
  29831. return Torus;
  29832. }(_Primitive));
  29833. Primitives.Torus = Torus;
  29834. var Ground = (function (_super) {
  29835. __extends(Ground, _super);
  29836. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29837. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29838. _this.width = width;
  29839. _this.height = height;
  29840. _this.subdivisions = subdivisions;
  29841. return _this;
  29842. }
  29843. Ground.prototype._regenerateVertexData = function () {
  29844. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29845. };
  29846. Ground.prototype.copy = function (id) {
  29847. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29848. };
  29849. Ground.prototype.serialize = function () {
  29850. var serializationObject = _super.prototype.serialize.call(this);
  29851. serializationObject.width = this.width;
  29852. serializationObject.height = this.height;
  29853. serializationObject.subdivisions = this.subdivisions;
  29854. return serializationObject;
  29855. };
  29856. Ground.Parse = function (parsedGround, scene) {
  29857. if (scene.getGeometryByID(parsedGround.id)) {
  29858. return null; // null since geometry could be something else than a ground...
  29859. }
  29860. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29861. if (BABYLON.Tags) {
  29862. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29863. }
  29864. scene.pushGeometry(ground, true);
  29865. return ground;
  29866. };
  29867. return Ground;
  29868. }(_Primitive));
  29869. Primitives.Ground = Ground;
  29870. var TiledGround = (function (_super) {
  29871. __extends(TiledGround, _super);
  29872. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29873. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29874. _this.xmin = xmin;
  29875. _this.zmin = zmin;
  29876. _this.xmax = xmax;
  29877. _this.zmax = zmax;
  29878. _this.subdivisions = subdivisions;
  29879. _this.precision = precision;
  29880. return _this;
  29881. }
  29882. TiledGround.prototype._regenerateVertexData = function () {
  29883. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29884. };
  29885. TiledGround.prototype.copy = function (id) {
  29886. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29887. };
  29888. return TiledGround;
  29889. }(_Primitive));
  29890. Primitives.TiledGround = TiledGround;
  29891. var Plane = (function (_super) {
  29892. __extends(Plane, _super);
  29893. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29894. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29895. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29896. _this.size = size;
  29897. _this.side = side;
  29898. return _this;
  29899. }
  29900. Plane.prototype._regenerateVertexData = function () {
  29901. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29902. };
  29903. Plane.prototype.copy = function (id) {
  29904. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29905. };
  29906. Plane.prototype.serialize = function () {
  29907. var serializationObject = _super.prototype.serialize.call(this);
  29908. serializationObject.size = this.size;
  29909. return serializationObject;
  29910. };
  29911. Plane.Parse = function (parsedPlane, scene) {
  29912. if (scene.getGeometryByID(parsedPlane.id)) {
  29913. return null; // null since geometry could be something else than a ground...
  29914. }
  29915. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29916. if (BABYLON.Tags) {
  29917. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29918. }
  29919. scene.pushGeometry(plane, true);
  29920. return plane;
  29921. };
  29922. return Plane;
  29923. }(_Primitive));
  29924. Primitives.Plane = Plane;
  29925. var TorusKnot = (function (_super) {
  29926. __extends(TorusKnot, _super);
  29927. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29928. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29929. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29930. _this.radius = radius;
  29931. _this.tube = tube;
  29932. _this.radialSegments = radialSegments;
  29933. _this.tubularSegments = tubularSegments;
  29934. _this.p = p;
  29935. _this.q = q;
  29936. _this.side = side;
  29937. return _this;
  29938. }
  29939. TorusKnot.prototype._regenerateVertexData = function () {
  29940. 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 });
  29941. };
  29942. TorusKnot.prototype.copy = function (id) {
  29943. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29944. };
  29945. TorusKnot.prototype.serialize = function () {
  29946. var serializationObject = _super.prototype.serialize.call(this);
  29947. serializationObject.radius = this.radius;
  29948. serializationObject.tube = this.tube;
  29949. serializationObject.radialSegments = this.radialSegments;
  29950. serializationObject.tubularSegments = this.tubularSegments;
  29951. serializationObject.p = this.p;
  29952. serializationObject.q = this.q;
  29953. return serializationObject;
  29954. };
  29955. ;
  29956. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29957. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29958. return null; // null since geometry could be something else than a ground...
  29959. }
  29960. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29961. if (BABYLON.Tags) {
  29962. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29963. }
  29964. scene.pushGeometry(torusKnot, true);
  29965. return torusKnot;
  29966. };
  29967. return TorusKnot;
  29968. }(_Primitive));
  29969. Primitives.TorusKnot = TorusKnot;
  29970. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29971. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29972. })(BABYLON || (BABYLON = {}));
  29973. //# sourceMappingURL=babylon.geometry.js.map
  29974. var BABYLON;
  29975. (function (BABYLON) {
  29976. var PostProcessManager = (function () {
  29977. function PostProcessManager(scene) {
  29978. this._vertexBuffers = {};
  29979. this._scene = scene;
  29980. }
  29981. PostProcessManager.prototype._prepareBuffers = function () {
  29982. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29983. return;
  29984. }
  29985. // VBO
  29986. var vertices = [];
  29987. vertices.push(1, 1);
  29988. vertices.push(-1, 1);
  29989. vertices.push(-1, -1);
  29990. vertices.push(1, -1);
  29991. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29992. this._buildIndexBuffer();
  29993. };
  29994. PostProcessManager.prototype._buildIndexBuffer = function () {
  29995. // Indices
  29996. var indices = [];
  29997. indices.push(0);
  29998. indices.push(1);
  29999. indices.push(2);
  30000. indices.push(0);
  30001. indices.push(2);
  30002. indices.push(3);
  30003. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30004. };
  30005. PostProcessManager.prototype._rebuild = function () {
  30006. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30007. return;
  30008. }
  30009. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30010. this._buildIndexBuffer();
  30011. };
  30012. // Methods
  30013. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30014. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30015. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30016. return false;
  30017. }
  30018. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30019. return true;
  30020. };
  30021. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30022. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30023. var engine = this._scene.getEngine();
  30024. for (var index = 0; index < postProcesses.length; index++) {
  30025. if (index < postProcesses.length - 1) {
  30026. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30027. }
  30028. else {
  30029. if (targetTexture) {
  30030. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30031. }
  30032. else {
  30033. engine.restoreDefaultFramebuffer();
  30034. }
  30035. }
  30036. var pp = postProcesses[index];
  30037. var effect = pp.apply();
  30038. if (effect) {
  30039. pp.onBeforeRenderObservable.notifyObservers(effect);
  30040. // VBOs
  30041. this._prepareBuffers();
  30042. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30043. // Draw order
  30044. engine.draw(true, 0, 6);
  30045. pp.onAfterRenderObservable.notifyObservers(effect);
  30046. }
  30047. }
  30048. // Restore depth buffer
  30049. engine.setDepthBuffer(true);
  30050. engine.setDepthWrite(true);
  30051. };
  30052. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  30053. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30054. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30055. return;
  30056. }
  30057. var engine = this._scene.getEngine();
  30058. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30059. if (index < len - 1) {
  30060. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30061. }
  30062. else {
  30063. if (targetTexture) {
  30064. engine.bindFramebuffer(targetTexture, faceIndex);
  30065. }
  30066. else {
  30067. engine.restoreDefaultFramebuffer();
  30068. }
  30069. }
  30070. if (doNotPresent) {
  30071. break;
  30072. }
  30073. var pp = postProcesses[index];
  30074. var effect = pp.apply();
  30075. if (effect) {
  30076. pp.onBeforeRenderObservable.notifyObservers(effect);
  30077. // VBOs
  30078. this._prepareBuffers();
  30079. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30080. // Draw order
  30081. engine.draw(true, 0, 6);
  30082. pp.onAfterRenderObservable.notifyObservers(effect);
  30083. }
  30084. }
  30085. // Restore states
  30086. engine.setDepthBuffer(true);
  30087. engine.setDepthWrite(true);
  30088. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30089. };
  30090. PostProcessManager.prototype.dispose = function () {
  30091. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30092. if (buffer) {
  30093. buffer.dispose();
  30094. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30095. }
  30096. if (this._indexBuffer) {
  30097. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30098. this._indexBuffer = null;
  30099. }
  30100. };
  30101. return PostProcessManager;
  30102. }());
  30103. BABYLON.PostProcessManager = PostProcessManager;
  30104. })(BABYLON || (BABYLON = {}));
  30105. //# sourceMappingURL=babylon.postProcessManager.js.map
  30106. var BABYLON;
  30107. (function (BABYLON) {
  30108. /**
  30109. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30110. */
  30111. var PerformanceMonitor = (function () {
  30112. /**
  30113. * constructor
  30114. * @param frameSampleSize The number of samples required to saturate the sliding window
  30115. */
  30116. function PerformanceMonitor(frameSampleSize) {
  30117. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30118. this._enabled = true;
  30119. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30120. }
  30121. /**
  30122. * Samples current frame
  30123. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30124. */
  30125. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30126. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30127. if (!this._enabled)
  30128. return;
  30129. if (this._lastFrameTimeMs != null) {
  30130. var dt = timeMs - this._lastFrameTimeMs;
  30131. this._rollingFrameTime.add(dt);
  30132. }
  30133. this._lastFrameTimeMs = timeMs;
  30134. };
  30135. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30136. /**
  30137. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30138. * @return Average frame time in milliseconds
  30139. */
  30140. get: function () {
  30141. return this._rollingFrameTime.average;
  30142. },
  30143. enumerable: true,
  30144. configurable: true
  30145. });
  30146. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30147. /**
  30148. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30149. * @return Frame time variance in milliseconds squared
  30150. */
  30151. get: function () {
  30152. return this._rollingFrameTime.variance;
  30153. },
  30154. enumerable: true,
  30155. configurable: true
  30156. });
  30157. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30158. /**
  30159. * Returns the frame time of the most recent frame
  30160. * @return Frame time in milliseconds
  30161. */
  30162. get: function () {
  30163. return this._rollingFrameTime.history(0);
  30164. },
  30165. enumerable: true,
  30166. configurable: true
  30167. });
  30168. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30169. /**
  30170. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30171. * @return Framerate in frames per second
  30172. */
  30173. get: function () {
  30174. return 1000.0 / this._rollingFrameTime.average;
  30175. },
  30176. enumerable: true,
  30177. configurable: true
  30178. });
  30179. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30180. /**
  30181. * Returns the average framerate in frames per second using the most recent frame time
  30182. * @return Framerate in frames per second
  30183. */
  30184. get: function () {
  30185. return 1000.0 / this._rollingFrameTime.history(0);
  30186. },
  30187. enumerable: true,
  30188. configurable: true
  30189. });
  30190. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30191. /**
  30192. * Returns true if enough samples have been taken to completely fill the sliding window
  30193. * @return true if saturated
  30194. */
  30195. get: function () {
  30196. return this._rollingFrameTime.isSaturated();
  30197. },
  30198. enumerable: true,
  30199. configurable: true
  30200. });
  30201. /**
  30202. * Enables contributions to the sliding window sample set
  30203. */
  30204. PerformanceMonitor.prototype.enable = function () {
  30205. this._enabled = true;
  30206. };
  30207. /**
  30208. * Disables contributions to the sliding window sample set
  30209. * Samples will not be interpolated over the disabled period
  30210. */
  30211. PerformanceMonitor.prototype.disable = function () {
  30212. this._enabled = false;
  30213. //clear last sample to avoid interpolating over the disabled period when next enabled
  30214. this._lastFrameTimeMs = null;
  30215. this._lastChangeTimeMs = null;
  30216. };
  30217. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30218. /**
  30219. * Returns true if sampling is enabled
  30220. * @return true if enabled
  30221. */
  30222. get: function () {
  30223. return this._enabled;
  30224. },
  30225. enumerable: true,
  30226. configurable: true
  30227. });
  30228. /**
  30229. * Resets performance monitor
  30230. */
  30231. PerformanceMonitor.prototype.reset = function () {
  30232. //clear last sample to avoid interpolating over the disabled period when next enabled
  30233. this._lastFrameTimeMs = null;
  30234. this._lastChangeTimeMs = null;
  30235. //wipe record
  30236. this._rollingFrameTime.reset();
  30237. };
  30238. return PerformanceMonitor;
  30239. }());
  30240. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30241. /**
  30242. * RollingAverage
  30243. *
  30244. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30245. */
  30246. var RollingAverage = (function () {
  30247. /**
  30248. * constructor
  30249. * @param length The number of samples required to saturate the sliding window
  30250. */
  30251. function RollingAverage(length) {
  30252. this._samples = new Array(length);
  30253. this.reset();
  30254. }
  30255. /**
  30256. * Adds a sample to the sample set
  30257. * @param v The sample value
  30258. */
  30259. RollingAverage.prototype.add = function (v) {
  30260. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30261. var delta;
  30262. //we need to check if we've already wrapped round
  30263. if (this.isSaturated()) {
  30264. //remove bottom of stack from mean
  30265. var bottomValue = this._samples[this._pos];
  30266. delta = bottomValue - this.average;
  30267. this.average -= delta / (this._sampleCount - 1);
  30268. this._m2 -= delta * (bottomValue - this.average);
  30269. }
  30270. else {
  30271. this._sampleCount++;
  30272. }
  30273. //add new value to mean
  30274. delta = v - this.average;
  30275. this.average += delta / (this._sampleCount);
  30276. this._m2 += delta * (v - this.average);
  30277. //set the new variance
  30278. this.variance = this._m2 / (this._sampleCount - 1);
  30279. this._samples[this._pos] = v;
  30280. this._pos++;
  30281. this._pos %= this._samples.length; //positive wrap around
  30282. };
  30283. /**
  30284. * Returns previously added values or null if outside of history or outside the sliding window domain
  30285. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30286. * @return Value previously recorded with add() or null if outside of range
  30287. */
  30288. RollingAverage.prototype.history = function (i) {
  30289. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30290. return null;
  30291. }
  30292. var i0 = this._wrapPosition(this._pos - 1.0);
  30293. return this._samples[this._wrapPosition(i0 - i)];
  30294. };
  30295. /**
  30296. * Returns true if enough samples have been taken to completely fill the sliding window
  30297. * @return true if sample-set saturated
  30298. */
  30299. RollingAverage.prototype.isSaturated = function () {
  30300. return this._sampleCount >= this._samples.length;
  30301. };
  30302. /**
  30303. * Resets the rolling average (equivalent to 0 samples taken so far)
  30304. */
  30305. RollingAverage.prototype.reset = function () {
  30306. this.average = 0;
  30307. this.variance = 0;
  30308. this._sampleCount = 0;
  30309. this._pos = 0;
  30310. this._m2 = 0;
  30311. };
  30312. /**
  30313. * Wraps a value around the sample range boundaries
  30314. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30315. * @return Wrapped position in sample range
  30316. */
  30317. RollingAverage.prototype._wrapPosition = function (i) {
  30318. var max = this._samples.length;
  30319. return ((i % max) + max) % max;
  30320. };
  30321. return RollingAverage;
  30322. }());
  30323. BABYLON.RollingAverage = RollingAverage;
  30324. })(BABYLON || (BABYLON = {}));
  30325. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30326. var BABYLON;
  30327. (function (BABYLON) {
  30328. var StandardMaterialDefines = (function (_super) {
  30329. __extends(StandardMaterialDefines, _super);
  30330. function StandardMaterialDefines() {
  30331. var _this = _super.call(this) || this;
  30332. _this.MAINUV1 = false;
  30333. _this.MAINUV2 = false;
  30334. _this.DIFFUSE = false;
  30335. _this.DIFFUSEDIRECTUV = 0;
  30336. _this.AMBIENT = false;
  30337. _this.AMBIENTDIRECTUV = 0;
  30338. _this.OPACITY = false;
  30339. _this.OPACITYDIRECTUV = 0;
  30340. _this.OPACITYRGB = false;
  30341. _this.REFLECTION = false;
  30342. _this.EMISSIVE = false;
  30343. _this.EMISSIVEDIRECTUV = 0;
  30344. _this.SPECULAR = false;
  30345. _this.SPECULARDIRECTUV = 0;
  30346. _this.BUMP = false;
  30347. _this.BUMPDIRECTUV = 0;
  30348. _this.PARALLAX = false;
  30349. _this.PARALLAXOCCLUSION = false;
  30350. _this.SPECULAROVERALPHA = false;
  30351. _this.CLIPPLANE = false;
  30352. _this.ALPHATEST = false;
  30353. _this.DEPTHPREPASS = false;
  30354. _this.ALPHAFROMDIFFUSE = false;
  30355. _this.POINTSIZE = false;
  30356. _this.FOG = false;
  30357. _this.SPECULARTERM = false;
  30358. _this.DIFFUSEFRESNEL = false;
  30359. _this.OPACITYFRESNEL = false;
  30360. _this.REFLECTIONFRESNEL = false;
  30361. _this.REFRACTIONFRESNEL = false;
  30362. _this.EMISSIVEFRESNEL = false;
  30363. _this.FRESNEL = false;
  30364. _this.NORMAL = false;
  30365. _this.UV1 = false;
  30366. _this.UV2 = false;
  30367. _this.VERTEXCOLOR = false;
  30368. _this.VERTEXALPHA = false;
  30369. _this.NUM_BONE_INFLUENCERS = 0;
  30370. _this.BonesPerMesh = 0;
  30371. _this.INSTANCES = false;
  30372. _this.GLOSSINESS = false;
  30373. _this.ROUGHNESS = false;
  30374. _this.EMISSIVEASILLUMINATION = false;
  30375. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30376. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30377. _this.LIGHTMAP = false;
  30378. _this.LIGHTMAPDIRECTUV = 0;
  30379. _this.USELIGHTMAPASSHADOWMAP = false;
  30380. _this.REFLECTIONMAP_3D = false;
  30381. _this.REFLECTIONMAP_SPHERICAL = false;
  30382. _this.REFLECTIONMAP_PLANAR = false;
  30383. _this.REFLECTIONMAP_CUBIC = false;
  30384. _this.REFLECTIONMAP_PROJECTION = false;
  30385. _this.REFLECTIONMAP_SKYBOX = false;
  30386. _this.REFLECTIONMAP_EXPLICIT = false;
  30387. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30388. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30389. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30390. _this.INVERTCUBICMAP = false;
  30391. _this.LOGARITHMICDEPTH = false;
  30392. _this.REFRACTION = false;
  30393. _this.REFRACTIONMAP_3D = false;
  30394. _this.REFLECTIONOVERALPHA = false;
  30395. _this.TWOSIDEDLIGHTING = false;
  30396. _this.SHADOWFLOAT = false;
  30397. _this.MORPHTARGETS = false;
  30398. _this.MORPHTARGETS_NORMAL = false;
  30399. _this.MORPHTARGETS_TANGENT = false;
  30400. _this.NUM_MORPH_INFLUENCERS = 0;
  30401. _this.USERIGHTHANDEDSYSTEM = false;
  30402. _this.IMAGEPROCESSING = false;
  30403. _this.VIGNETTE = false;
  30404. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30405. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30406. _this.TONEMAPPING = false;
  30407. _this.CONTRAST = false;
  30408. _this.COLORCURVES = false;
  30409. _this.COLORGRADING = false;
  30410. _this.SAMPLER3DGREENDEPTH = false;
  30411. _this.SAMPLER3DBGRMAP = false;
  30412. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30413. _this.EXPOSURE = false;
  30414. _this.rebuild();
  30415. return _this;
  30416. }
  30417. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30418. var modes = [
  30419. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30420. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30421. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30422. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30423. ];
  30424. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30425. var mode = modes_1[_i];
  30426. this[mode] = (mode === modeToEnable);
  30427. }
  30428. };
  30429. return StandardMaterialDefines;
  30430. }(BABYLON.MaterialDefines));
  30431. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30432. var StandardMaterial = (function (_super) {
  30433. __extends(StandardMaterial, _super);
  30434. function StandardMaterial(name, scene) {
  30435. var _this = _super.call(this, name, scene) || this;
  30436. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30437. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30438. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30439. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30440. _this.specularPower = 64;
  30441. _this._useAlphaFromDiffuseTexture = false;
  30442. _this._useEmissiveAsIllumination = false;
  30443. _this._linkEmissiveWithDiffuse = false;
  30444. _this._useSpecularOverAlpha = false;
  30445. _this._useReflectionOverAlpha = false;
  30446. _this._disableLighting = false;
  30447. _this._useParallax = false;
  30448. _this._useParallaxOcclusion = false;
  30449. _this.parallaxScaleBias = 0.05;
  30450. _this._roughness = 0;
  30451. _this.indexOfRefraction = 0.98;
  30452. _this.invertRefractionY = true;
  30453. _this._useLightmapAsShadowmap = false;
  30454. _this._useReflectionFresnelFromSpecular = false;
  30455. _this._useGlossinessFromSpecularMapAlpha = false;
  30456. _this._maxSimultaneousLights = 4;
  30457. /**
  30458. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30459. */
  30460. _this._invertNormalMapX = false;
  30461. /**
  30462. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30463. */
  30464. _this._invertNormalMapY = false;
  30465. /**
  30466. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30467. */
  30468. _this._twoSidedLighting = false;
  30469. _this._renderTargets = new BABYLON.SmartArray(16);
  30470. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30471. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30472. // Setup the default processing configuration to the scene.
  30473. _this._attachImageProcessingConfiguration(null);
  30474. _this.getRenderTargetTextures = function () {
  30475. _this._renderTargets.reset();
  30476. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30477. _this._renderTargets.push(_this._reflectionTexture);
  30478. }
  30479. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30480. _this._renderTargets.push(_this._refractionTexture);
  30481. }
  30482. return _this._renderTargets;
  30483. };
  30484. return _this;
  30485. }
  30486. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30487. /**
  30488. * Gets the image processing configuration used either in this material.
  30489. */
  30490. get: function () {
  30491. return this._imageProcessingConfiguration;
  30492. },
  30493. /**
  30494. * Sets the Default image processing configuration used either in the this material.
  30495. *
  30496. * If sets to null, the scene one is in use.
  30497. */
  30498. set: function (value) {
  30499. this._attachImageProcessingConfiguration(value);
  30500. // Ensure the effect will be rebuilt.
  30501. this._markAllSubMeshesAsTexturesDirty();
  30502. },
  30503. enumerable: true,
  30504. configurable: true
  30505. });
  30506. /**
  30507. * Attaches a new image processing configuration to the Standard Material.
  30508. * @param configuration
  30509. */
  30510. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30511. var _this = this;
  30512. if (configuration === this._imageProcessingConfiguration) {
  30513. return;
  30514. }
  30515. // Detaches observer.
  30516. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30517. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30518. }
  30519. // Pick the scene configuration if needed.
  30520. if (!configuration) {
  30521. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30522. }
  30523. else {
  30524. this._imageProcessingConfiguration = configuration;
  30525. }
  30526. // Attaches observer.
  30527. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30528. _this._markAllSubMeshesAsImageProcessingDirty();
  30529. });
  30530. };
  30531. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30532. /**
  30533. * Gets wether the color curves effect is enabled.
  30534. */
  30535. get: function () {
  30536. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30537. },
  30538. /**
  30539. * Sets wether the color curves effect is enabled.
  30540. */
  30541. set: function (value) {
  30542. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30548. /**
  30549. * Gets wether the color grading effect is enabled.
  30550. */
  30551. get: function () {
  30552. return this.imageProcessingConfiguration.colorGradingEnabled;
  30553. },
  30554. /**
  30555. * Gets wether the color grading effect is enabled.
  30556. */
  30557. set: function (value) {
  30558. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30559. },
  30560. enumerable: true,
  30561. configurable: true
  30562. });
  30563. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30564. /**
  30565. * Gets wether tonemapping is enabled or not.
  30566. */
  30567. get: function () {
  30568. return this._imageProcessingConfiguration.toneMappingEnabled;
  30569. },
  30570. /**
  30571. * Sets wether tonemapping is enabled or not
  30572. */
  30573. set: function (value) {
  30574. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30575. },
  30576. enumerable: true,
  30577. configurable: true
  30578. });
  30579. ;
  30580. ;
  30581. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30582. /**
  30583. * The camera exposure used on this material.
  30584. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30585. * This corresponds to a photographic exposure.
  30586. */
  30587. get: function () {
  30588. return this._imageProcessingConfiguration.exposure;
  30589. },
  30590. /**
  30591. * The camera exposure used on this material.
  30592. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30593. * This corresponds to a photographic exposure.
  30594. */
  30595. set: function (value) {
  30596. this._imageProcessingConfiguration.exposure = value;
  30597. },
  30598. enumerable: true,
  30599. configurable: true
  30600. });
  30601. ;
  30602. ;
  30603. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30604. /**
  30605. * Gets The camera contrast used on this material.
  30606. */
  30607. get: function () {
  30608. return this._imageProcessingConfiguration.contrast;
  30609. },
  30610. /**
  30611. * Sets The camera contrast used on this material.
  30612. */
  30613. set: function (value) {
  30614. this._imageProcessingConfiguration.contrast = value;
  30615. },
  30616. enumerable: true,
  30617. configurable: true
  30618. });
  30619. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30620. /**
  30621. * Gets the Color Grading 2D Lookup Texture.
  30622. */
  30623. get: function () {
  30624. return this._imageProcessingConfiguration.colorGradingTexture;
  30625. },
  30626. /**
  30627. * Sets the Color Grading 2D Lookup Texture.
  30628. */
  30629. set: function (value) {
  30630. this._imageProcessingConfiguration.colorGradingTexture = value;
  30631. },
  30632. enumerable: true,
  30633. configurable: true
  30634. });
  30635. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  30636. /**
  30637. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30638. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30639. * 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;
  30640. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30641. */
  30642. get: function () {
  30643. return this._imageProcessingConfiguration.colorCurves;
  30644. },
  30645. /**
  30646. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30647. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30648. * 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;
  30649. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30650. */
  30651. set: function (value) {
  30652. this._imageProcessingConfiguration.colorCurves = value;
  30653. },
  30654. enumerable: true,
  30655. configurable: true
  30656. });
  30657. StandardMaterial.prototype.getClassName = function () {
  30658. return "StandardMaterial";
  30659. };
  30660. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30661. get: function () {
  30662. return this._useLogarithmicDepth;
  30663. },
  30664. set: function (value) {
  30665. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30666. this._markAllSubMeshesAsMiscDirty();
  30667. },
  30668. enumerable: true,
  30669. configurable: true
  30670. });
  30671. StandardMaterial.prototype.needAlphaBlending = function () {
  30672. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  30673. };
  30674. StandardMaterial.prototype.needAlphaTesting = function () {
  30675. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  30676. };
  30677. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30678. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  30679. };
  30680. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30681. return this._diffuseTexture;
  30682. };
  30683. /**
  30684. * Child classes can use it to update shaders
  30685. */
  30686. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30687. if (this.isFrozen) {
  30688. if (this._wasPreviouslyReady && subMesh.effect) {
  30689. return true;
  30690. }
  30691. }
  30692. if (!subMesh._materialDefines) {
  30693. subMesh._materialDefines = new StandardMaterialDefines();
  30694. }
  30695. var scene = this.getScene();
  30696. var defines = subMesh._materialDefines;
  30697. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30698. if (defines._renderId === scene.getRenderId()) {
  30699. return true;
  30700. }
  30701. }
  30702. var engine = scene.getEngine();
  30703. // Lights
  30704. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30705. // Textures
  30706. if (defines._areTexturesDirty) {
  30707. defines._needUVs = false;
  30708. defines.MAINUV1 = false;
  30709. defines.MAINUV2 = false;
  30710. if (scene.texturesEnabled) {
  30711. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30712. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  30713. return false;
  30714. }
  30715. else {
  30716. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  30717. }
  30718. }
  30719. else {
  30720. defines.DIFFUSE = false;
  30721. }
  30722. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30723. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30724. return false;
  30725. }
  30726. else {
  30727. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30728. }
  30729. }
  30730. else {
  30731. defines.AMBIENT = false;
  30732. }
  30733. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30734. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30735. return false;
  30736. }
  30737. else {
  30738. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  30739. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30740. }
  30741. }
  30742. else {
  30743. defines.OPACITY = false;
  30744. }
  30745. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30746. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  30747. return false;
  30748. }
  30749. else {
  30750. defines._needNormals = true;
  30751. defines.REFLECTION = true;
  30752. defines.ROUGHNESS = (this._roughness > 0);
  30753. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30754. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30755. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30756. switch (this._reflectionTexture.coordinatesMode) {
  30757. case BABYLON.Texture.CUBIC_MODE:
  30758. case BABYLON.Texture.INVCUBIC_MODE:
  30759. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  30760. break;
  30761. case BABYLON.Texture.EXPLICIT_MODE:
  30762. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  30763. break;
  30764. case BABYLON.Texture.PLANAR_MODE:
  30765. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  30766. break;
  30767. case BABYLON.Texture.PROJECTION_MODE:
  30768. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  30769. break;
  30770. case BABYLON.Texture.SKYBOX_MODE:
  30771. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  30772. break;
  30773. case BABYLON.Texture.SPHERICAL_MODE:
  30774. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  30775. break;
  30776. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30777. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  30778. break;
  30779. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30780. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  30781. break;
  30782. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30783. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  30784. break;
  30785. }
  30786. }
  30787. }
  30788. else {
  30789. defines.REFLECTION = false;
  30790. }
  30791. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30792. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30793. return false;
  30794. }
  30795. else {
  30796. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30797. }
  30798. }
  30799. else {
  30800. defines.EMISSIVE = false;
  30801. }
  30802. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30803. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30804. return false;
  30805. }
  30806. else {
  30807. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30808. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30809. }
  30810. }
  30811. else {
  30812. defines.LIGHTMAP = false;
  30813. }
  30814. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30815. if (!this._specularTexture.isReadyOrNotBlocking()) {
  30816. return false;
  30817. }
  30818. else {
  30819. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  30820. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  30821. }
  30822. }
  30823. else {
  30824. defines.SPECULAR = false;
  30825. }
  30826. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30827. // Bump texure can not be not blocking.
  30828. if (!this._bumpTexture.isReady()) {
  30829. return false;
  30830. }
  30831. else {
  30832. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  30833. defines.PARALLAX = this._useParallax;
  30834. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  30835. }
  30836. }
  30837. else {
  30838. defines.BUMP = false;
  30839. }
  30840. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30841. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30842. return false;
  30843. }
  30844. else {
  30845. defines._needUVs = true;
  30846. defines.REFRACTION = true;
  30847. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30848. }
  30849. }
  30850. else {
  30851. defines.REFRACTION = false;
  30852. }
  30853. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  30854. }
  30855. else {
  30856. defines.DIFFUSE = false;
  30857. defines.AMBIENT = false;
  30858. defines.OPACITY = false;
  30859. defines.REFLECTION = false;
  30860. defines.EMISSIVE = false;
  30861. defines.LIGHTMAP = false;
  30862. defines.BUMP = false;
  30863. defines.REFRACTION = false;
  30864. }
  30865. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  30866. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  30867. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  30868. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  30869. }
  30870. if (defines._areImageProcessingDirty) {
  30871. if (!this._imageProcessingConfiguration.isReady()) {
  30872. return false;
  30873. }
  30874. this._imageProcessingConfiguration.prepareDefines(defines);
  30875. }
  30876. if (defines._areFresnelDirty) {
  30877. if (StandardMaterial.FresnelEnabled) {
  30878. // Fresnel
  30879. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  30880. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  30881. this._reflectionFresnelParameters) {
  30882. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  30883. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  30884. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  30885. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  30886. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  30887. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  30888. defines._needNormals = true;
  30889. defines.FRESNEL = true;
  30890. }
  30891. }
  30892. else {
  30893. defines.FRESNEL = false;
  30894. }
  30895. }
  30896. // Misc.
  30897. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30898. // Attribs
  30899. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  30900. // Values that need to be evaluated on every frame
  30901. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  30902. // Get correct effect
  30903. if (defines.isDirty) {
  30904. defines.markAsProcessed();
  30905. scene.resetCachedMaterial();
  30906. // Fallbacks
  30907. var fallbacks = new BABYLON.EffectFallbacks();
  30908. if (defines.REFLECTION) {
  30909. fallbacks.addFallback(0, "REFLECTION");
  30910. }
  30911. if (defines.SPECULAR) {
  30912. fallbacks.addFallback(0, "SPECULAR");
  30913. }
  30914. if (defines.BUMP) {
  30915. fallbacks.addFallback(0, "BUMP");
  30916. }
  30917. if (defines.PARALLAX) {
  30918. fallbacks.addFallback(1, "PARALLAX");
  30919. }
  30920. if (defines.PARALLAXOCCLUSION) {
  30921. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30922. }
  30923. if (defines.SPECULAROVERALPHA) {
  30924. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30925. }
  30926. if (defines.FOG) {
  30927. fallbacks.addFallback(1, "FOG");
  30928. }
  30929. if (defines.POINTSIZE) {
  30930. fallbacks.addFallback(0, "POINTSIZE");
  30931. }
  30932. if (defines.LOGARITHMICDEPTH) {
  30933. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30934. }
  30935. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30936. if (defines.SPECULARTERM) {
  30937. fallbacks.addFallback(0, "SPECULARTERM");
  30938. }
  30939. if (defines.DIFFUSEFRESNEL) {
  30940. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30941. }
  30942. if (defines.OPACITYFRESNEL) {
  30943. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30944. }
  30945. if (defines.REFLECTIONFRESNEL) {
  30946. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30947. }
  30948. if (defines.EMISSIVEFRESNEL) {
  30949. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30950. }
  30951. if (defines.FRESNEL) {
  30952. fallbacks.addFallback(4, "FRESNEL");
  30953. }
  30954. //Attributes
  30955. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30956. if (defines.NORMAL) {
  30957. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30958. }
  30959. if (defines.UV1) {
  30960. attribs.push(BABYLON.VertexBuffer.UVKind);
  30961. }
  30962. if (defines.UV2) {
  30963. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30964. }
  30965. if (defines.VERTEXCOLOR) {
  30966. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30967. }
  30968. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30969. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30970. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30971. var shaderName = "default";
  30972. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30973. "vFogInfos", "vFogColor", "pointSize",
  30974. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30975. "mBones",
  30976. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30977. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30978. "logarithmicDepthConstant", "vNormalReoderParams"
  30979. ];
  30980. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30981. var uniformBuffers = ["Material", "Scene"];
  30982. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30983. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30984. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30985. uniformsNames: uniforms,
  30986. uniformBuffersNames: uniformBuffers,
  30987. samplers: samplers,
  30988. defines: defines,
  30989. maxSimultaneousLights: this._maxSimultaneousLights
  30990. });
  30991. if (this.customShaderNameResolve) {
  30992. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  30993. }
  30994. var join = defines.toString();
  30995. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  30996. attributes: attribs,
  30997. uniformsNames: uniforms,
  30998. uniformBuffersNames: uniformBuffers,
  30999. samplers: samplers,
  31000. defines: join,
  31001. fallbacks: fallbacks,
  31002. onCompiled: this.onCompiled,
  31003. onError: this.onError,
  31004. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31005. }, engine), defines);
  31006. this.buildUniformLayout();
  31007. }
  31008. if (!subMesh.effect.isReady()) {
  31009. return false;
  31010. }
  31011. defines._renderId = scene.getRenderId();
  31012. this._wasPreviouslyReady = true;
  31013. return true;
  31014. };
  31015. StandardMaterial.prototype.buildUniformLayout = function () {
  31016. // Order is important !
  31017. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  31018. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  31019. this._uniformBuffer.addUniform("opacityParts", 4);
  31020. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  31021. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  31022. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  31023. this._uniformBuffer.addUniform("refractionRightColor", 4);
  31024. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  31025. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  31026. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  31027. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  31028. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31029. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31030. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31031. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31032. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  31033. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31034. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  31035. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31036. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31037. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31038. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31039. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31040. this._uniformBuffer.addUniform("specularMatrix", 16);
  31041. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31042. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  31043. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31044. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31045. this._uniformBuffer.addUniform("vSpecularColor", 4);
  31046. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31047. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  31048. this._uniformBuffer.addUniform("pointSize", 1);
  31049. this._uniformBuffer.create();
  31050. };
  31051. StandardMaterial.prototype.unbind = function () {
  31052. if (this._activeEffect) {
  31053. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31054. this._activeEffect.setTexture("reflection2DSampler", null);
  31055. }
  31056. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31057. this._activeEffect.setTexture("refraction2DSampler", null);
  31058. }
  31059. }
  31060. _super.prototype.unbind.call(this);
  31061. };
  31062. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31063. var scene = this.getScene();
  31064. var defines = subMesh._materialDefines;
  31065. if (!defines) {
  31066. return;
  31067. }
  31068. var effect = subMesh.effect;
  31069. this._activeEffect = effect;
  31070. // Matrices
  31071. this.bindOnlyWorldMatrix(world);
  31072. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  31073. // Bones
  31074. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  31075. if (mustRebind) {
  31076. this._uniformBuffer.bindToEffect(effect, "Material");
  31077. this.bindViewProjection(effect);
  31078. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31079. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  31080. // Fresnel
  31081. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  31082. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  31083. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  31084. }
  31085. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  31086. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  31087. }
  31088. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  31089. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  31090. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  31091. }
  31092. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  31093. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  31094. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  31095. }
  31096. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  31097. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  31098. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  31099. }
  31100. }
  31101. // Textures
  31102. if (scene.texturesEnabled) {
  31103. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31104. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  31105. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  31106. }
  31107. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31108. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  31109. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31110. }
  31111. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31112. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31113. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31114. }
  31115. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31116. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  31117. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  31118. }
  31119. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31120. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31121. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31122. }
  31123. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31124. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31125. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31126. }
  31127. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31128. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  31129. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  31130. }
  31131. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31132. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  31133. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31134. if (scene._mirroredCameraPosition) {
  31135. 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);
  31136. }
  31137. else {
  31138. 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);
  31139. }
  31140. }
  31141. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31142. var depth = 1.0;
  31143. if (!this._refractionTexture.isCube) {
  31144. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  31145. if (this._refractionTexture.depth) {
  31146. depth = this._refractionTexture.depth;
  31147. }
  31148. }
  31149. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  31150. }
  31151. }
  31152. // Point size
  31153. if (this.pointsCloud) {
  31154. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31155. }
  31156. if (defines.SPECULARTERM) {
  31157. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  31158. }
  31159. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  31160. // Diffuse
  31161. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  31162. }
  31163. // Textures
  31164. if (scene.texturesEnabled) {
  31165. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31166. effect.setTexture("diffuseSampler", this._diffuseTexture);
  31167. }
  31168. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31169. effect.setTexture("ambientSampler", this._ambientTexture);
  31170. }
  31171. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31172. effect.setTexture("opacitySampler", this._opacityTexture);
  31173. }
  31174. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31175. if (this._reflectionTexture.isCube) {
  31176. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  31177. }
  31178. else {
  31179. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  31180. }
  31181. }
  31182. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31183. effect.setTexture("emissiveSampler", this._emissiveTexture);
  31184. }
  31185. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31186. effect.setTexture("lightmapSampler", this._lightmapTexture);
  31187. }
  31188. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31189. effect.setTexture("specularSampler", this._specularTexture);
  31190. }
  31191. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31192. effect.setTexture("bumpSampler", this._bumpTexture);
  31193. }
  31194. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31195. var depth = 1.0;
  31196. if (this._refractionTexture.isCube) {
  31197. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  31198. }
  31199. else {
  31200. effect.setTexture("refraction2DSampler", this._refractionTexture);
  31201. }
  31202. }
  31203. }
  31204. // Clip plane
  31205. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  31206. // Colors
  31207. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  31208. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  31209. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31210. }
  31211. if (mustRebind || !this.isFrozen) {
  31212. // Lights
  31213. if (scene.lightsEnabled && !this._disableLighting) {
  31214. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  31215. }
  31216. // View
  31217. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  31218. this.bindView(effect);
  31219. }
  31220. // Fog
  31221. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  31222. // Morph targets
  31223. if (defines.NUM_MORPH_INFLUENCERS) {
  31224. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  31225. }
  31226. // Log. depth
  31227. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  31228. // image processing
  31229. this._imageProcessingConfiguration.bind(this._activeEffect);
  31230. }
  31231. this._uniformBuffer.update();
  31232. this._afterBind(mesh, this._activeEffect);
  31233. };
  31234. StandardMaterial.prototype.getAnimatables = function () {
  31235. var results = [];
  31236. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  31237. results.push(this._diffuseTexture);
  31238. }
  31239. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31240. results.push(this._ambientTexture);
  31241. }
  31242. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31243. results.push(this._opacityTexture);
  31244. }
  31245. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31246. results.push(this._reflectionTexture);
  31247. }
  31248. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31249. results.push(this._emissiveTexture);
  31250. }
  31251. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  31252. results.push(this._specularTexture);
  31253. }
  31254. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31255. results.push(this._bumpTexture);
  31256. }
  31257. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31258. results.push(this._lightmapTexture);
  31259. }
  31260. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31261. results.push(this._refractionTexture);
  31262. }
  31263. return results;
  31264. };
  31265. StandardMaterial.prototype.getActiveTextures = function () {
  31266. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31267. if (this._diffuseTexture) {
  31268. activeTextures.push(this._diffuseTexture);
  31269. }
  31270. if (this._ambientTexture) {
  31271. activeTextures.push(this._ambientTexture);
  31272. }
  31273. if (this._opacityTexture) {
  31274. activeTextures.push(this._opacityTexture);
  31275. }
  31276. if (this._reflectionTexture) {
  31277. activeTextures.push(this._reflectionTexture);
  31278. }
  31279. if (this._emissiveTexture) {
  31280. activeTextures.push(this._emissiveTexture);
  31281. }
  31282. if (this._specularTexture) {
  31283. activeTextures.push(this._specularTexture);
  31284. }
  31285. if (this._bumpTexture) {
  31286. activeTextures.push(this._bumpTexture);
  31287. }
  31288. if (this._lightmapTexture) {
  31289. activeTextures.push(this._lightmapTexture);
  31290. }
  31291. if (this._refractionTexture) {
  31292. activeTextures.push(this._refractionTexture);
  31293. }
  31294. return activeTextures;
  31295. };
  31296. StandardMaterial.prototype.hasTexture = function (texture) {
  31297. if (_super.prototype.hasTexture.call(this, texture)) {
  31298. return true;
  31299. }
  31300. if (this._diffuseTexture === texture) {
  31301. return true;
  31302. }
  31303. if (this._ambientTexture === texture) {
  31304. return true;
  31305. }
  31306. if (this._opacityTexture === texture) {
  31307. return true;
  31308. }
  31309. if (this._reflectionTexture === texture) {
  31310. return true;
  31311. }
  31312. if (this._emissiveTexture === texture) {
  31313. return true;
  31314. }
  31315. if (this._specularTexture === texture) {
  31316. return true;
  31317. }
  31318. if (this._bumpTexture === texture) {
  31319. return true;
  31320. }
  31321. if (this._lightmapTexture === texture) {
  31322. return true;
  31323. }
  31324. if (this._refractionTexture === texture) {
  31325. return true;
  31326. }
  31327. return false;
  31328. };
  31329. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31330. if (forceDisposeTextures) {
  31331. if (this._diffuseTexture) {
  31332. this._diffuseTexture.dispose();
  31333. }
  31334. if (this._ambientTexture) {
  31335. this._ambientTexture.dispose();
  31336. }
  31337. if (this._opacityTexture) {
  31338. this._opacityTexture.dispose();
  31339. }
  31340. if (this._reflectionTexture) {
  31341. this._reflectionTexture.dispose();
  31342. }
  31343. if (this._emissiveTexture) {
  31344. this._emissiveTexture.dispose();
  31345. }
  31346. if (this._specularTexture) {
  31347. this._specularTexture.dispose();
  31348. }
  31349. if (this._bumpTexture) {
  31350. this._bumpTexture.dispose();
  31351. }
  31352. if (this._lightmapTexture) {
  31353. this._lightmapTexture.dispose();
  31354. }
  31355. if (this._refractionTexture) {
  31356. this._refractionTexture.dispose();
  31357. }
  31358. }
  31359. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31360. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31361. }
  31362. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31363. };
  31364. StandardMaterial.prototype.clone = function (name) {
  31365. var _this = this;
  31366. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31367. result.name = name;
  31368. result.id = name;
  31369. return result;
  31370. };
  31371. StandardMaterial.prototype.serialize = function () {
  31372. return BABYLON.SerializationHelper.Serialize(this);
  31373. };
  31374. // Statics
  31375. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31376. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31377. };
  31378. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31379. get: function () {
  31380. return StandardMaterial._DiffuseTextureEnabled;
  31381. },
  31382. set: function (value) {
  31383. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31384. return;
  31385. }
  31386. StandardMaterial._DiffuseTextureEnabled = value;
  31387. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31388. },
  31389. enumerable: true,
  31390. configurable: true
  31391. });
  31392. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31393. get: function () {
  31394. return StandardMaterial._AmbientTextureEnabled;
  31395. },
  31396. set: function (value) {
  31397. if (StandardMaterial._AmbientTextureEnabled === value) {
  31398. return;
  31399. }
  31400. StandardMaterial._AmbientTextureEnabled = value;
  31401. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31402. },
  31403. enumerable: true,
  31404. configurable: true
  31405. });
  31406. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31407. get: function () {
  31408. return StandardMaterial._OpacityTextureEnabled;
  31409. },
  31410. set: function (value) {
  31411. if (StandardMaterial._OpacityTextureEnabled === value) {
  31412. return;
  31413. }
  31414. StandardMaterial._OpacityTextureEnabled = value;
  31415. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31416. },
  31417. enumerable: true,
  31418. configurable: true
  31419. });
  31420. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31421. get: function () {
  31422. return StandardMaterial._ReflectionTextureEnabled;
  31423. },
  31424. set: function (value) {
  31425. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31426. return;
  31427. }
  31428. StandardMaterial._ReflectionTextureEnabled = value;
  31429. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31430. },
  31431. enumerable: true,
  31432. configurable: true
  31433. });
  31434. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31435. get: function () {
  31436. return StandardMaterial._EmissiveTextureEnabled;
  31437. },
  31438. set: function (value) {
  31439. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31440. return;
  31441. }
  31442. StandardMaterial._EmissiveTextureEnabled = value;
  31443. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31444. },
  31445. enumerable: true,
  31446. configurable: true
  31447. });
  31448. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31449. get: function () {
  31450. return StandardMaterial._SpecularTextureEnabled;
  31451. },
  31452. set: function (value) {
  31453. if (StandardMaterial._SpecularTextureEnabled === value) {
  31454. return;
  31455. }
  31456. StandardMaterial._SpecularTextureEnabled = value;
  31457. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31458. },
  31459. enumerable: true,
  31460. configurable: true
  31461. });
  31462. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31463. get: function () {
  31464. return StandardMaterial._BumpTextureEnabled;
  31465. },
  31466. set: function (value) {
  31467. if (StandardMaterial._BumpTextureEnabled === value) {
  31468. return;
  31469. }
  31470. StandardMaterial._BumpTextureEnabled = value;
  31471. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31472. },
  31473. enumerable: true,
  31474. configurable: true
  31475. });
  31476. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31477. get: function () {
  31478. return StandardMaterial._LightmapTextureEnabled;
  31479. },
  31480. set: function (value) {
  31481. if (StandardMaterial._LightmapTextureEnabled === value) {
  31482. return;
  31483. }
  31484. StandardMaterial._LightmapTextureEnabled = value;
  31485. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31486. },
  31487. enumerable: true,
  31488. configurable: true
  31489. });
  31490. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31491. get: function () {
  31492. return StandardMaterial._RefractionTextureEnabled;
  31493. },
  31494. set: function (value) {
  31495. if (StandardMaterial._RefractionTextureEnabled === value) {
  31496. return;
  31497. }
  31498. StandardMaterial._RefractionTextureEnabled = value;
  31499. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31500. },
  31501. enumerable: true,
  31502. configurable: true
  31503. });
  31504. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31505. get: function () {
  31506. return StandardMaterial._ColorGradingTextureEnabled;
  31507. },
  31508. set: function (value) {
  31509. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31510. return;
  31511. }
  31512. StandardMaterial._ColorGradingTextureEnabled = value;
  31513. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31514. },
  31515. enumerable: true,
  31516. configurable: true
  31517. });
  31518. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31519. get: function () {
  31520. return StandardMaterial._FresnelEnabled;
  31521. },
  31522. set: function (value) {
  31523. if (StandardMaterial._FresnelEnabled === value) {
  31524. return;
  31525. }
  31526. StandardMaterial._FresnelEnabled = value;
  31527. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31528. },
  31529. enumerable: true,
  31530. configurable: true
  31531. });
  31532. // Flags used to enable or disable a type of texture for all Standard Materials
  31533. StandardMaterial._DiffuseTextureEnabled = true;
  31534. StandardMaterial._AmbientTextureEnabled = true;
  31535. StandardMaterial._OpacityTextureEnabled = true;
  31536. StandardMaterial._ReflectionTextureEnabled = true;
  31537. StandardMaterial._EmissiveTextureEnabled = true;
  31538. StandardMaterial._SpecularTextureEnabled = true;
  31539. StandardMaterial._BumpTextureEnabled = true;
  31540. StandardMaterial._LightmapTextureEnabled = true;
  31541. StandardMaterial._RefractionTextureEnabled = true;
  31542. StandardMaterial._ColorGradingTextureEnabled = true;
  31543. StandardMaterial._FresnelEnabled = true;
  31544. __decorate([
  31545. BABYLON.serializeAsTexture("diffuseTexture")
  31546. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31547. __decorate([
  31548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31549. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31550. __decorate([
  31551. BABYLON.serializeAsTexture("ambientTexture")
  31552. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31553. __decorate([
  31554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31555. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31556. __decorate([
  31557. BABYLON.serializeAsTexture("opacityTexture")
  31558. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31559. __decorate([
  31560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31561. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31562. __decorate([
  31563. BABYLON.serializeAsTexture("reflectionTexture")
  31564. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31565. __decorate([
  31566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31567. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31568. __decorate([
  31569. BABYLON.serializeAsTexture("emissiveTexture")
  31570. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31571. __decorate([
  31572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31573. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31574. __decorate([
  31575. BABYLON.serializeAsTexture("specularTexture")
  31576. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31577. __decorate([
  31578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31579. ], StandardMaterial.prototype, "specularTexture", void 0);
  31580. __decorate([
  31581. BABYLON.serializeAsTexture("bumpTexture")
  31582. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31583. __decorate([
  31584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31585. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31586. __decorate([
  31587. BABYLON.serializeAsTexture("lightmapTexture")
  31588. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31589. __decorate([
  31590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31591. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31592. __decorate([
  31593. BABYLON.serializeAsTexture("refractionTexture")
  31594. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31595. __decorate([
  31596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31597. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31598. __decorate([
  31599. BABYLON.serializeAsColor3("ambient")
  31600. ], StandardMaterial.prototype, "ambientColor", void 0);
  31601. __decorate([
  31602. BABYLON.serializeAsColor3("diffuse")
  31603. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31604. __decorate([
  31605. BABYLON.serializeAsColor3("specular")
  31606. ], StandardMaterial.prototype, "specularColor", void 0);
  31607. __decorate([
  31608. BABYLON.serializeAsColor3("emissive")
  31609. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31610. __decorate([
  31611. BABYLON.serialize()
  31612. ], StandardMaterial.prototype, "specularPower", void 0);
  31613. __decorate([
  31614. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31615. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31616. __decorate([
  31617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31618. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31619. __decorate([
  31620. BABYLON.serialize("useEmissiveAsIllumination")
  31621. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31622. __decorate([
  31623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31624. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31625. __decorate([
  31626. BABYLON.serialize("linkEmissiveWithDiffuse")
  31627. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31628. __decorate([
  31629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31630. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31631. __decorate([
  31632. BABYLON.serialize("useSpecularOverAlpha")
  31633. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31634. __decorate([
  31635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31636. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31637. __decorate([
  31638. BABYLON.serialize("useReflectionOverAlpha")
  31639. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31640. __decorate([
  31641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31642. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31643. __decorate([
  31644. BABYLON.serialize("disableLighting")
  31645. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31646. __decorate([
  31647. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31648. ], StandardMaterial.prototype, "disableLighting", void 0);
  31649. __decorate([
  31650. BABYLON.serialize("useParallax")
  31651. ], StandardMaterial.prototype, "_useParallax", void 0);
  31652. __decorate([
  31653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31654. ], StandardMaterial.prototype, "useParallax", void 0);
  31655. __decorate([
  31656. BABYLON.serialize("useParallaxOcclusion")
  31657. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31658. __decorate([
  31659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31660. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31661. __decorate([
  31662. BABYLON.serialize()
  31663. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31664. __decorate([
  31665. BABYLON.serialize("roughness")
  31666. ], StandardMaterial.prototype, "_roughness", void 0);
  31667. __decorate([
  31668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31669. ], StandardMaterial.prototype, "roughness", void 0);
  31670. __decorate([
  31671. BABYLON.serialize()
  31672. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31673. __decorate([
  31674. BABYLON.serialize()
  31675. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31676. __decorate([
  31677. BABYLON.serialize("useLightmapAsShadowmap")
  31678. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31679. __decorate([
  31680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31681. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31682. __decorate([
  31683. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31684. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31685. __decorate([
  31686. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31687. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31688. __decorate([
  31689. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31690. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31691. __decorate([
  31692. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31693. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31694. __decorate([
  31695. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31696. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31697. __decorate([
  31698. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31699. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31700. __decorate([
  31701. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31702. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31703. __decorate([
  31704. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31705. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31706. __decorate([
  31707. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31708. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31709. __decorate([
  31710. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31711. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31712. __decorate([
  31713. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31714. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31715. __decorate([
  31716. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31717. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31718. __decorate([
  31719. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31720. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31721. __decorate([
  31722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31723. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31724. __decorate([
  31725. BABYLON.serialize("maxSimultaneousLights")
  31726. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31727. __decorate([
  31728. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31729. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31730. __decorate([
  31731. BABYLON.serialize("invertNormalMapX")
  31732. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31733. __decorate([
  31734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31735. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  31736. __decorate([
  31737. BABYLON.serialize("invertNormalMapY")
  31738. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  31739. __decorate([
  31740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31741. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  31742. __decorate([
  31743. BABYLON.serialize("twoSidedLighting")
  31744. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31745. __decorate([
  31746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31747. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31748. __decorate([
  31749. BABYLON.serialize()
  31750. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31751. return StandardMaterial;
  31752. }(BABYLON.PushMaterial));
  31753. BABYLON.StandardMaterial = StandardMaterial;
  31754. })(BABYLON || (BABYLON = {}));
  31755. //# sourceMappingURL=babylon.standardMaterial.js.map
  31756. var BABYLON;
  31757. (function (BABYLON) {
  31758. var PBRMaterialDefines = (function (_super) {
  31759. __extends(PBRMaterialDefines, _super);
  31760. function PBRMaterialDefines() {
  31761. var _this = _super.call(this) || this;
  31762. _this.PBR = true;
  31763. _this.MAINUV1 = false;
  31764. _this.MAINUV2 = false;
  31765. _this.UV1 = false;
  31766. _this.UV2 = false;
  31767. _this.ALBEDO = false;
  31768. _this.ALBEDODIRECTUV = 0;
  31769. _this.VERTEXCOLOR = false;
  31770. _this.AMBIENT = false;
  31771. _this.AMBIENTDIRECTUV = 0;
  31772. _this.AMBIENTINGRAYSCALE = false;
  31773. _this.OPACITY = false;
  31774. _this.VERTEXALPHA = false;
  31775. _this.OPACITYDIRECTUV = 0;
  31776. _this.OPACITYRGB = false;
  31777. _this.ALPHATEST = false;
  31778. _this.DEPTHPREPASS = false;
  31779. _this.ALPHABLEND = false;
  31780. _this.ALPHAFROMALBEDO = false;
  31781. _this.ALPHATESTVALUE = 0.5;
  31782. _this.SPECULAROVERALPHA = false;
  31783. _this.RADIANCEOVERALPHA = false;
  31784. _this.ALPHAFRESNEL = false;
  31785. _this.PREMULTIPLYALPHA = false;
  31786. _this.EMISSIVE = false;
  31787. _this.EMISSIVEDIRECTUV = 0;
  31788. _this.REFLECTIVITY = false;
  31789. _this.REFLECTIVITYDIRECTUV = 0;
  31790. _this.SPECULARTERM = false;
  31791. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  31792. _this.MICROSURFACEAUTOMATIC = false;
  31793. _this.LODBASEDMICROSFURACE = false;
  31794. _this.MICROSURFACEMAP = false;
  31795. _this.MICROSURFACEMAPDIRECTUV = 0;
  31796. _this.METALLICWORKFLOW = false;
  31797. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  31798. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  31799. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  31800. _this.AOSTOREINMETALMAPRED = false;
  31801. _this.ENVIRONMENTBRDF = false;
  31802. _this.NORMAL = false;
  31803. _this.TANGENT = false;
  31804. _this.BUMP = false;
  31805. _this.BUMPDIRECTUV = 0;
  31806. _this.PARALLAX = false;
  31807. _this.PARALLAXOCCLUSION = false;
  31808. _this.NORMALXYSCALE = true;
  31809. _this.LIGHTMAP = false;
  31810. _this.LIGHTMAPDIRECTUV = 0;
  31811. _this.USELIGHTMAPASSHADOWMAP = false;
  31812. _this.REFLECTION = false;
  31813. _this.REFLECTIONMAP_3D = false;
  31814. _this.REFLECTIONMAP_SPHERICAL = false;
  31815. _this.REFLECTIONMAP_PLANAR = false;
  31816. _this.REFLECTIONMAP_CUBIC = false;
  31817. _this.REFLECTIONMAP_PROJECTION = false;
  31818. _this.REFLECTIONMAP_SKYBOX = false;
  31819. _this.REFLECTIONMAP_EXPLICIT = false;
  31820. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31821. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31822. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31823. _this.INVERTCUBICMAP = false;
  31824. _this.USESPHERICALFROMREFLECTIONMAP = false;
  31825. _this.USESPHERICALINFRAGMENT = false;
  31826. _this.REFLECTIONMAP_OPPOSITEZ = false;
  31827. _this.LODINREFLECTIONALPHA = false;
  31828. _this.GAMMAREFLECTION = false;
  31829. _this.REFRACTION = false;
  31830. _this.REFRACTIONMAP_3D = false;
  31831. _this.REFRACTIONMAP_OPPOSITEZ = false;
  31832. _this.LODINREFRACTIONALPHA = false;
  31833. _this.GAMMAREFRACTION = false;
  31834. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  31835. _this.INSTANCES = false;
  31836. _this.NUM_BONE_INFLUENCERS = 0;
  31837. _this.BonesPerMesh = 0;
  31838. _this.MORPHTARGETS = false;
  31839. _this.MORPHTARGETS_NORMAL = false;
  31840. _this.MORPHTARGETS_TANGENT = false;
  31841. _this.NUM_MORPH_INFLUENCERS = 0;
  31842. _this.IMAGEPROCESSING = false;
  31843. _this.VIGNETTE = false;
  31844. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  31845. _this.VIGNETTEBLENDMODEOPAQUE = false;
  31846. _this.TONEMAPPING = false;
  31847. _this.CONTRAST = false;
  31848. _this.COLORCURVES = false;
  31849. _this.COLORGRADING = false;
  31850. _this.SAMPLER3DGREENDEPTH = false;
  31851. _this.SAMPLER3DBGRMAP = false;
  31852. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  31853. _this.EXPOSURE = false;
  31854. _this.USEPHYSICALLIGHTFALLOFF = false;
  31855. _this.TWOSIDEDLIGHTING = false;
  31856. _this.SHADOWFLOAT = false;
  31857. _this.USERIGHTHANDEDSYSTEM = false;
  31858. _this.CLIPPLANE = false;
  31859. _this.POINTSIZE = false;
  31860. _this.FOG = false;
  31861. _this.LOGARITHMICDEPTH = false;
  31862. _this.FORCENORMALFORWARD = false;
  31863. _this.rebuild();
  31864. return _this;
  31865. }
  31866. PBRMaterialDefines.prototype.reset = function () {
  31867. _super.prototype.reset.call(this);
  31868. this.ALPHATESTVALUE = 0.5;
  31869. this.PBR = true;
  31870. };
  31871. return PBRMaterialDefines;
  31872. }(BABYLON.MaterialDefines));
  31873. /**
  31874. * The Physically based material base class of BJS.
  31875. *
  31876. * This offers the main features of a standard PBR material.
  31877. * For more information, please refer to the documentation :
  31878. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31879. */
  31880. var PBRBaseMaterial = (function (_super) {
  31881. __extends(PBRBaseMaterial, _super);
  31882. /**
  31883. * Instantiates a new PBRMaterial instance.
  31884. *
  31885. * @param name The material name
  31886. * @param scene The scene the material will be use in.
  31887. */
  31888. function PBRBaseMaterial(name, scene) {
  31889. var _this = _super.call(this, name, scene) || this;
  31890. /**
  31891. * Intensity of the direct lights e.g. the four lights available in your scene.
  31892. * This impacts both the direct diffuse and specular highlights.
  31893. */
  31894. _this._directIntensity = 1.0;
  31895. /**
  31896. * Intensity of the emissive part of the material.
  31897. * This helps controlling the emissive effect without modifying the emissive color.
  31898. */
  31899. _this._emissiveIntensity = 1.0;
  31900. /**
  31901. * Intensity of the environment e.g. how much the environment will light the object
  31902. * either through harmonics for rough material or through the refelction for shiny ones.
  31903. */
  31904. _this._environmentIntensity = 1.0;
  31905. /**
  31906. * This is a special control allowing the reduction of the specular highlights coming from the
  31907. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31908. */
  31909. _this._specularIntensity = 1.0;
  31910. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  31911. /**
  31912. * Debug Control allowing disabling the bump map on this material.
  31913. */
  31914. _this._disableBumpMap = false;
  31915. /**
  31916. * AKA Occlusion Texture Intensity in other nomenclature.
  31917. */
  31918. _this._ambientTextureStrength = 1.0;
  31919. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  31920. /**
  31921. * AKA Diffuse Color in other nomenclature.
  31922. */
  31923. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  31924. /**
  31925. * AKA Specular Color in other nomenclature.
  31926. */
  31927. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31928. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  31929. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  31930. /**
  31931. * AKA Glossiness in other nomenclature.
  31932. */
  31933. _this._microSurface = 0.9;
  31934. /**
  31935. * source material index of refraction (IOR)' / 'destination material IOR.
  31936. */
  31937. _this._indexOfRefraction = 0.66;
  31938. /**
  31939. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31940. */
  31941. _this._invertRefractionY = false;
  31942. /**
  31943. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31944. * Materials half opaque for instance using refraction could benefit from this control.
  31945. */
  31946. _this._linkRefractionWithTransparency = false;
  31947. _this._useLightmapAsShadowmap = false;
  31948. /**
  31949. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31950. */
  31951. _this._useAlphaFromAlbedoTexture = false;
  31952. /**
  31953. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31954. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31955. */
  31956. _this._useSpecularOverAlpha = true;
  31957. /**
  31958. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31959. */
  31960. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  31961. /**
  31962. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31963. */
  31964. _this._useRoughnessFromMetallicTextureAlpha = true;
  31965. /**
  31966. * Specifies if the metallic texture contains the roughness information in its green channel.
  31967. */
  31968. _this._useRoughnessFromMetallicTextureGreen = false;
  31969. /**
  31970. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31971. */
  31972. _this._useMetallnessFromMetallicTextureBlue = false;
  31973. /**
  31974. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31975. */
  31976. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  31977. /**
  31978. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31979. */
  31980. _this._useAmbientInGrayScale = false;
  31981. /**
  31982. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31983. * The material will try to infer what glossiness each pixel should be.
  31984. */
  31985. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  31986. /**
  31987. * BJS is using an harcoded light falloff based on a manually sets up range.
  31988. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31989. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31990. */
  31991. _this._usePhysicalLightFalloff = true;
  31992. /**
  31993. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31994. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31995. */
  31996. _this._useRadianceOverAlpha = true;
  31997. /**
  31998. * Allows using the bump map in parallax mode.
  31999. */
  32000. _this._useParallax = false;
  32001. /**
  32002. * Allows using the bump map in parallax occlusion mode.
  32003. */
  32004. _this._useParallaxOcclusion = false;
  32005. /**
  32006. * Controls the scale bias of the parallax mode.
  32007. */
  32008. _this._parallaxScaleBias = 0.05;
  32009. /**
  32010. * If sets to true, disables all the lights affecting the material.
  32011. */
  32012. _this._disableLighting = false;
  32013. /**
  32014. * Number of Simultaneous lights allowed on the material.
  32015. */
  32016. _this._maxSimultaneousLights = 4;
  32017. /**
  32018. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  32019. */
  32020. _this._invertNormalMapX = false;
  32021. /**
  32022. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  32023. */
  32024. _this._invertNormalMapY = false;
  32025. /**
  32026. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32027. */
  32028. _this._twoSidedLighting = false;
  32029. /**
  32030. * Defines the alpha limits in alpha test mode.
  32031. */
  32032. _this._alphaCutOff = 0.4;
  32033. /**
  32034. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32035. */
  32036. _this._forceAlphaTest = false;
  32037. /**
  32038. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32039. * in your scene composition.
  32040. */
  32041. _this._preMultiplyAlpha = false;
  32042. /**
  32043. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32044. * And/Or occlude the blended part.
  32045. */
  32046. _this._useAlphaFresnel = false;
  32047. /**
  32048. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  32049. * from cos thetav and roughness:
  32050. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  32051. */
  32052. _this._environmentBRDFTexture = null;
  32053. /**
  32054. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32055. */
  32056. _this._forceIrradianceInFragment = false;
  32057. /**
  32058. * Force normal to face away from face.
  32059. * (Temporary internal fix to remove before 3.1)
  32060. */
  32061. _this._forceNormalForward = false;
  32062. _this._renderTargets = new BABYLON.SmartArray(16);
  32063. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32064. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32065. _this._tempColor = new BABYLON.Color3();
  32066. // Setup the default processing configuration to the scene.
  32067. _this._attachImageProcessingConfiguration(null);
  32068. _this.getRenderTargetTextures = function () {
  32069. _this._renderTargets.reset();
  32070. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32071. _this._renderTargets.push(_this._reflectionTexture);
  32072. }
  32073. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32074. _this._renderTargets.push(_this._refractionTexture);
  32075. }
  32076. return _this._renderTargets;
  32077. };
  32078. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32079. return _this;
  32080. }
  32081. /**
  32082. * Attaches a new image processing configuration to the PBR Material.
  32083. * @param configuration
  32084. */
  32085. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32086. var _this = this;
  32087. if (configuration === this._imageProcessingConfiguration) {
  32088. return;
  32089. }
  32090. // Detaches observer.
  32091. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32092. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32093. }
  32094. // Pick the scene configuration if needed.
  32095. if (!configuration) {
  32096. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32097. }
  32098. else {
  32099. this._imageProcessingConfiguration = configuration;
  32100. }
  32101. // Attaches observer.
  32102. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32103. _this._markAllSubMeshesAsImageProcessingDirty();
  32104. });
  32105. };
  32106. PBRBaseMaterial.prototype.getClassName = function () {
  32107. return "PBRBaseMaterial";
  32108. };
  32109. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  32110. get: function () {
  32111. return this._useLogarithmicDepth;
  32112. },
  32113. set: function (value) {
  32114. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32115. },
  32116. enumerable: true,
  32117. configurable: true
  32118. });
  32119. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  32120. if (this._linkRefractionWithTransparency) {
  32121. return false;
  32122. }
  32123. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  32124. };
  32125. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  32126. if (this._forceAlphaTest) {
  32127. return true;
  32128. }
  32129. if (this._linkRefractionWithTransparency) {
  32130. return false;
  32131. }
  32132. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  32133. };
  32134. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32135. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  32136. };
  32137. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  32138. return this._albedoTexture;
  32139. };
  32140. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32141. if (this.isFrozen) {
  32142. if (this._wasPreviouslyReady) {
  32143. return true;
  32144. }
  32145. }
  32146. if (!subMesh._materialDefines) {
  32147. subMesh._materialDefines = new PBRMaterialDefines();
  32148. }
  32149. var scene = this.getScene();
  32150. var defines = subMesh._materialDefines;
  32151. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32152. if (defines._renderId === scene.getRenderId()) {
  32153. return true;
  32154. }
  32155. }
  32156. var engine = scene.getEngine();
  32157. // Lights
  32158. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32159. defines._needNormals = true;
  32160. // Textures
  32161. if (defines._areTexturesDirty) {
  32162. defines._needUVs = false;
  32163. if (scene.texturesEnabled) {
  32164. if (scene.getEngine().getCaps().textureLOD) {
  32165. defines.LODBASEDMICROSFURACE = true;
  32166. }
  32167. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32168. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  32169. return false;
  32170. }
  32171. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  32172. }
  32173. else {
  32174. defines.ALBEDO = false;
  32175. }
  32176. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32177. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32178. return false;
  32179. }
  32180. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32181. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  32182. }
  32183. else {
  32184. defines.AMBIENT = false;
  32185. }
  32186. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32187. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32188. return false;
  32189. }
  32190. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32191. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32192. }
  32193. else {
  32194. defines.OPACITY = false;
  32195. }
  32196. var reflectionTexture = this._getReflectionTexture();
  32197. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32198. if (!reflectionTexture.isReadyOrNotBlocking()) {
  32199. return false;
  32200. }
  32201. defines.REFLECTION = true;
  32202. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  32203. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  32204. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32205. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  32206. defines.INVERTCUBICMAP = true;
  32207. }
  32208. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  32209. switch (reflectionTexture.coordinatesMode) {
  32210. case BABYLON.Texture.CUBIC_MODE:
  32211. case BABYLON.Texture.INVCUBIC_MODE:
  32212. defines.REFLECTIONMAP_CUBIC = true;
  32213. break;
  32214. case BABYLON.Texture.EXPLICIT_MODE:
  32215. defines.REFLECTIONMAP_EXPLICIT = true;
  32216. break;
  32217. case BABYLON.Texture.PLANAR_MODE:
  32218. defines.REFLECTIONMAP_PLANAR = true;
  32219. break;
  32220. case BABYLON.Texture.PROJECTION_MODE:
  32221. defines.REFLECTIONMAP_PROJECTION = true;
  32222. break;
  32223. case BABYLON.Texture.SKYBOX_MODE:
  32224. defines.REFLECTIONMAP_SKYBOX = true;
  32225. break;
  32226. case BABYLON.Texture.SPHERICAL_MODE:
  32227. defines.REFLECTIONMAP_SPHERICAL = true;
  32228. break;
  32229. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32230. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  32231. break;
  32232. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32233. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  32234. break;
  32235. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32236. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  32237. break;
  32238. }
  32239. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  32240. if (reflectionTexture.sphericalPolynomial) {
  32241. defines.USESPHERICALFROMREFLECTIONMAP = true;
  32242. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  32243. defines.USESPHERICALINFRAGMENT = true;
  32244. }
  32245. }
  32246. }
  32247. }
  32248. else {
  32249. defines.REFLECTION = false;
  32250. defines.REFLECTIONMAP_3D = false;
  32251. defines.REFLECTIONMAP_SPHERICAL = false;
  32252. defines.REFLECTIONMAP_PLANAR = false;
  32253. defines.REFLECTIONMAP_CUBIC = false;
  32254. defines.REFLECTIONMAP_PROJECTION = false;
  32255. defines.REFLECTIONMAP_SKYBOX = false;
  32256. defines.REFLECTIONMAP_EXPLICIT = false;
  32257. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32258. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32259. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32260. defines.INVERTCUBICMAP = false;
  32261. defines.USESPHERICALFROMREFLECTIONMAP = false;
  32262. defines.USESPHERICALINFRAGMENT = false;
  32263. defines.REFLECTIONMAP_OPPOSITEZ = false;
  32264. defines.LODINREFLECTIONALPHA = false;
  32265. defines.GAMMAREFLECTION = false;
  32266. }
  32267. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32268. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32269. return false;
  32270. }
  32271. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32272. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32273. }
  32274. else {
  32275. defines.LIGHTMAP = false;
  32276. }
  32277. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32278. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32279. return false;
  32280. }
  32281. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32282. }
  32283. else {
  32284. defines.EMISSIVE = false;
  32285. }
  32286. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32287. if (this._metallicTexture) {
  32288. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  32289. return false;
  32290. }
  32291. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  32292. defines.METALLICWORKFLOW = true;
  32293. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  32294. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  32295. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  32296. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  32297. }
  32298. else if (this._reflectivityTexture) {
  32299. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  32300. return false;
  32301. }
  32302. defines.METALLICWORKFLOW = false;
  32303. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  32304. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  32305. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  32306. }
  32307. else {
  32308. defines.METALLICWORKFLOW = false;
  32309. defines.REFLECTIVITY = false;
  32310. }
  32311. if (this._microSurfaceTexture) {
  32312. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  32313. return false;
  32314. }
  32315. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  32316. }
  32317. else {
  32318. defines.MICROSURFACEMAP = false;
  32319. }
  32320. }
  32321. else {
  32322. defines.REFLECTIVITY = false;
  32323. defines.MICROSURFACEMAP = false;
  32324. }
  32325. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32326. // Bump texure can not be none blocking.
  32327. if (!this._bumpTexture.isReady()) {
  32328. return false;
  32329. }
  32330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32331. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32332. defines.PARALLAX = true;
  32333. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  32334. }
  32335. else {
  32336. defines.PARALLAX = false;
  32337. }
  32338. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  32339. }
  32340. else {
  32341. defines.BUMP = false;
  32342. }
  32343. var refractionTexture = this._getRefractionTexture();
  32344. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32345. if (!refractionTexture.isReadyOrNotBlocking()) {
  32346. return false;
  32347. }
  32348. defines.REFRACTION = true;
  32349. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32350. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32351. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32352. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32353. if (this._linkRefractionWithTransparency) {
  32354. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32355. }
  32356. }
  32357. else {
  32358. defines.REFRACTION = false;
  32359. }
  32360. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32361. // This is blocking.
  32362. if (!this._environmentBRDFTexture.isReady()) {
  32363. return false;
  32364. }
  32365. defines.ENVIRONMENTBRDF = true;
  32366. }
  32367. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32368. defines.ALPHAFROMALBEDO = true;
  32369. }
  32370. }
  32371. if (this._useSpecularOverAlpha) {
  32372. defines.SPECULAROVERALPHA = true;
  32373. }
  32374. if (this._usePhysicalLightFalloff) {
  32375. defines.USEPHYSICALLIGHTFALLOFF = true;
  32376. }
  32377. if (this._useRadianceOverAlpha) {
  32378. defines.RADIANCEOVERALPHA = true;
  32379. }
  32380. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32381. defines.METALLICWORKFLOW = true;
  32382. }
  32383. if (!this.backFaceCulling && this._twoSidedLighting) {
  32384. defines.TWOSIDEDLIGHTING = true;
  32385. }
  32386. defines.ALPHATESTVALUE = this._alphaCutOff;
  32387. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32388. defines.ALPHABLEND = this.needAlphaBlending();
  32389. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32390. }
  32391. if (defines._areImageProcessingDirty) {
  32392. if (!this._imageProcessingConfiguration.isReady()) {
  32393. return false;
  32394. }
  32395. this._imageProcessingConfiguration.prepareDefines(defines);
  32396. }
  32397. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32398. // Misc.
  32399. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32400. // Values that need to be evaluated on every frame
  32401. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32402. // Attribs
  32403. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32404. if (mesh) {
  32405. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32406. mesh.createNormals(true);
  32407. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32408. }
  32409. }
  32410. }
  32411. // Get correct effect
  32412. if (defines.isDirty) {
  32413. defines.markAsProcessed();
  32414. scene.resetCachedMaterial();
  32415. // Fallbacks
  32416. var fallbacks = new BABYLON.EffectFallbacks();
  32417. if (defines.ENVIRONMENTBRDF) {
  32418. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32419. }
  32420. if (defines.REFLECTION) {
  32421. fallbacks.addFallback(0, "REFLECTION");
  32422. }
  32423. if (defines.REFRACTION) {
  32424. fallbacks.addFallback(0, "REFRACTION");
  32425. }
  32426. if (defines.REFLECTIVITY) {
  32427. fallbacks.addFallback(0, "REFLECTIVITY");
  32428. }
  32429. if (defines.BUMP) {
  32430. fallbacks.addFallback(0, "BUMP");
  32431. }
  32432. if (defines.PARALLAX) {
  32433. fallbacks.addFallback(1, "PARALLAX");
  32434. }
  32435. if (defines.PARALLAXOCCLUSION) {
  32436. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32437. }
  32438. if (defines.SPECULAROVERALPHA) {
  32439. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32440. }
  32441. if (defines.FOG) {
  32442. fallbacks.addFallback(1, "FOG");
  32443. }
  32444. if (defines.POINTSIZE) {
  32445. fallbacks.addFallback(0, "POINTSIZE");
  32446. }
  32447. if (defines.LOGARITHMICDEPTH) {
  32448. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32449. }
  32450. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32451. if (defines.SPECULARTERM) {
  32452. fallbacks.addFallback(0, "SPECULARTERM");
  32453. }
  32454. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32455. fallbacks.addCPUSkinningFallback(0, mesh);
  32456. }
  32457. //Attributes
  32458. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32459. if (defines.NORMAL) {
  32460. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32461. }
  32462. if (defines.TANGENT) {
  32463. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32464. }
  32465. if (defines.UV1) {
  32466. attribs.push(BABYLON.VertexBuffer.UVKind);
  32467. }
  32468. if (defines.UV2) {
  32469. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32470. }
  32471. if (defines.VERTEXCOLOR) {
  32472. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32473. }
  32474. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32475. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32476. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32477. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32478. "vFogInfos", "vFogColor", "pointSize",
  32479. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32480. "mBones",
  32481. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32482. "vLightingIntensity",
  32483. "logarithmicDepthConstant",
  32484. "vSphericalX", "vSphericalY", "vSphericalZ",
  32485. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32486. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32487. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32488. "vNormalReoderParams"
  32489. ];
  32490. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32491. "bumpSampler", "lightmapSampler", "opacitySampler",
  32492. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32493. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32494. "microSurfaceSampler", "environmentBrdfSampler"];
  32495. var uniformBuffers = ["Material", "Scene"];
  32496. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32497. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32498. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32499. uniformsNames: uniforms,
  32500. uniformBuffersNames: uniformBuffers,
  32501. samplers: samplers,
  32502. defines: defines,
  32503. maxSimultaneousLights: this._maxSimultaneousLights
  32504. });
  32505. var onCompiled = function (effect) {
  32506. if (this.onCompiled) {
  32507. this.onCompiled(effect);
  32508. }
  32509. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32510. }.bind(this);
  32511. var join = defines.toString();
  32512. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32513. attributes: attribs,
  32514. uniformsNames: uniforms,
  32515. uniformBuffersNames: uniformBuffers,
  32516. samplers: samplers,
  32517. defines: join,
  32518. fallbacks: fallbacks,
  32519. onCompiled: onCompiled,
  32520. onError: this.onError,
  32521. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32522. }, engine), defines);
  32523. this.buildUniformLayout();
  32524. }
  32525. if (!subMesh.effect.isReady()) {
  32526. return false;
  32527. }
  32528. defines._renderId = scene.getRenderId();
  32529. this._wasPreviouslyReady = true;
  32530. return true;
  32531. };
  32532. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32533. // Order is important !
  32534. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32535. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32536. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32537. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32538. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32539. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32540. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32541. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32542. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32543. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32544. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32545. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32546. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32547. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32548. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32549. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32550. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32551. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32552. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  32553. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32554. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32555. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32556. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32557. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32558. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32559. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32560. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32561. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32562. this._uniformBuffer.addUniform("pointSize", 1);
  32563. this._uniformBuffer.create();
  32564. };
  32565. PBRBaseMaterial.prototype.unbind = function () {
  32566. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32567. this._uniformBuffer.setTexture("reflectionSampler", null);
  32568. }
  32569. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32570. this._uniformBuffer.setTexture("refractionSampler", null);
  32571. }
  32572. _super.prototype.unbind.call(this);
  32573. };
  32574. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32575. this._activeEffect.setMatrix("world", world);
  32576. };
  32577. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32578. var scene = this.getScene();
  32579. var defines = subMesh._materialDefines;
  32580. if (!defines) {
  32581. return;
  32582. }
  32583. var effect = subMesh.effect;
  32584. this._activeEffect = effect;
  32585. // Matrices
  32586. this.bindOnlyWorldMatrix(world);
  32587. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32588. // Bones
  32589. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32590. if (mustRebind) {
  32591. this._uniformBuffer.bindToEffect(effect, "Material");
  32592. this.bindViewProjection(effect);
  32593. var reflectionTexture = this._getReflectionTexture();
  32594. var refractionTexture = this._getRefractionTexture();
  32595. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32596. // Texture uniforms
  32597. if (scene.texturesEnabled) {
  32598. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32599. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32600. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32601. }
  32602. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32603. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32604. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32605. }
  32606. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32607. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32608. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32609. }
  32610. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32611. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32612. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32613. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32614. var polynomials = reflectionTexture.sphericalPolynomial;
  32615. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32616. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32617. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32618. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32619. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32620. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32621. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32622. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32623. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32624. }
  32625. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32626. }
  32627. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32628. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32629. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32630. }
  32631. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32632. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32633. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32634. }
  32635. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32636. if (this._metallicTexture) {
  32637. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32638. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32639. }
  32640. else if (this._reflectivityTexture) {
  32641. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32642. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32643. }
  32644. if (this._microSurfaceTexture) {
  32645. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32646. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32647. }
  32648. }
  32649. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32650. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32651. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32652. if (scene._mirroredCameraPosition) {
  32653. 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);
  32654. }
  32655. else {
  32656. 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);
  32657. }
  32658. }
  32659. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32660. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32661. var depth = 1.0;
  32662. if (!refractionTexture.isCube) {
  32663. if (refractionTexture.depth) {
  32664. depth = refractionTexture.depth;
  32665. }
  32666. }
  32667. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32668. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32669. }
  32670. }
  32671. // Point size
  32672. if (this.pointsCloud) {
  32673. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32674. }
  32675. // Colors
  32676. if (defines.METALLICWORKFLOW) {
  32677. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  32678. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  32679. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  32680. }
  32681. else {
  32682. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  32683. }
  32684. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  32685. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  32686. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  32687. // Misc
  32688. this._lightingInfos.x = this._directIntensity;
  32689. this._lightingInfos.y = this._emissiveIntensity;
  32690. this._lightingInfos.z = this._environmentIntensity;
  32691. this._lightingInfos.w = this._specularIntensity;
  32692. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  32693. }
  32694. // Textures
  32695. if (scene.texturesEnabled) {
  32696. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32697. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  32698. }
  32699. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32700. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  32701. }
  32702. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32703. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  32704. }
  32705. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32706. if (defines.LODBASEDMICROSFURACE) {
  32707. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  32708. }
  32709. else {
  32710. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  32711. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  32712. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  32713. }
  32714. }
  32715. if (defines.ENVIRONMENTBRDF) {
  32716. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  32717. }
  32718. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32719. if (defines.LODBASEDMICROSFURACE) {
  32720. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  32721. }
  32722. else {
  32723. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  32724. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  32725. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  32726. }
  32727. }
  32728. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32729. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  32730. }
  32731. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32732. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  32733. }
  32734. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32735. if (this._metallicTexture) {
  32736. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  32737. }
  32738. else if (this._reflectivityTexture) {
  32739. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  32740. }
  32741. if (this._microSurfaceTexture) {
  32742. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  32743. }
  32744. }
  32745. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32746. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  32747. }
  32748. }
  32749. // Clip plane
  32750. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  32751. // Colors
  32752. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  32753. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  32754. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  32755. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32756. }
  32757. if (mustRebind || !this.isFrozen) {
  32758. // Lights
  32759. if (scene.lightsEnabled && !this._disableLighting) {
  32760. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  32761. }
  32762. // View
  32763. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  32764. this.bindView(effect);
  32765. }
  32766. // Fog
  32767. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  32768. // Morph targets
  32769. if (defines.NUM_MORPH_INFLUENCERS) {
  32770. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  32771. }
  32772. // image processing
  32773. this._imageProcessingConfiguration.bind(this._activeEffect);
  32774. // Log. depth
  32775. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  32776. }
  32777. this._uniformBuffer.update();
  32778. this._afterBind(mesh);
  32779. scene = null;
  32780. };
  32781. PBRBaseMaterial.prototype.getAnimatables = function () {
  32782. var results = [];
  32783. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  32784. results.push(this._albedoTexture);
  32785. }
  32786. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32787. results.push(this._ambientTexture);
  32788. }
  32789. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32790. results.push(this._opacityTexture);
  32791. }
  32792. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32793. results.push(this._reflectionTexture);
  32794. }
  32795. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32796. results.push(this._emissiveTexture);
  32797. }
  32798. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  32799. results.push(this._metallicTexture);
  32800. }
  32801. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  32802. results.push(this._reflectivityTexture);
  32803. }
  32804. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32805. results.push(this._bumpTexture);
  32806. }
  32807. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32808. results.push(this._lightmapTexture);
  32809. }
  32810. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32811. results.push(this._refractionTexture);
  32812. }
  32813. return results;
  32814. };
  32815. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  32816. if (this._reflectionTexture) {
  32817. return this._reflectionTexture;
  32818. }
  32819. return this.getScene().environmentTexture;
  32820. };
  32821. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  32822. if (this._refractionTexture) {
  32823. return this._refractionTexture;
  32824. }
  32825. if (this._linkRefractionWithTransparency) {
  32826. return this.getScene().environmentTexture;
  32827. }
  32828. return null;
  32829. };
  32830. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32831. if (forceDisposeTextures) {
  32832. if (this._albedoTexture) {
  32833. this._albedoTexture.dispose();
  32834. }
  32835. if (this._ambientTexture) {
  32836. this._ambientTexture.dispose();
  32837. }
  32838. if (this._opacityTexture) {
  32839. this._opacityTexture.dispose();
  32840. }
  32841. if (this._reflectionTexture) {
  32842. this._reflectionTexture.dispose();
  32843. }
  32844. if (this._environmentBRDFTexture) {
  32845. this._environmentBRDFTexture.dispose();
  32846. }
  32847. if (this._emissiveTexture) {
  32848. this._emissiveTexture.dispose();
  32849. }
  32850. if (this._metallicTexture) {
  32851. this._metallicTexture.dispose();
  32852. }
  32853. if (this._reflectivityTexture) {
  32854. this._reflectivityTexture.dispose();
  32855. }
  32856. if (this._bumpTexture) {
  32857. this._bumpTexture.dispose();
  32858. }
  32859. if (this._lightmapTexture) {
  32860. this._lightmapTexture.dispose();
  32861. }
  32862. if (this._refractionTexture) {
  32863. this._refractionTexture.dispose();
  32864. }
  32865. }
  32866. this._renderTargets.dispose();
  32867. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32868. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32869. }
  32870. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32871. };
  32872. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  32873. __decorate([
  32874. BABYLON.serializeAsImageProcessingConfiguration()
  32875. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  32876. __decorate([
  32877. BABYLON.serialize()
  32878. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  32879. return PBRBaseMaterial;
  32880. }(BABYLON.PushMaterial));
  32881. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  32882. })(BABYLON || (BABYLON = {}));
  32883. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  32884. var BABYLON;
  32885. (function (BABYLON) {
  32886. var Internals;
  32887. (function (Internals) {
  32888. /**
  32889. * The Physically based simple base material of BJS.
  32890. *
  32891. * This enables better naming and convention enforcements on top of the pbrMaterial.
  32892. * It is used as the base class for both the specGloss and metalRough conventions.
  32893. */
  32894. var PBRBaseSimpleMaterial = (function (_super) {
  32895. __extends(PBRBaseSimpleMaterial, _super);
  32896. /**
  32897. * Instantiates a new PBRMaterial instance.
  32898. *
  32899. * @param name The material name
  32900. * @param scene The scene the material will be use in.
  32901. */
  32902. function PBRBaseSimpleMaterial(name, scene) {
  32903. var _this = _super.call(this, name, scene) || this;
  32904. /**
  32905. * Number of Simultaneous lights allowed on the material.
  32906. */
  32907. _this.maxSimultaneousLights = 4;
  32908. /**
  32909. * If sets to true, disables all the lights affecting the material.
  32910. */
  32911. _this.disableLighting = false;
  32912. /**
  32913. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32914. */
  32915. _this.invertNormalMapX = false;
  32916. /**
  32917. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32918. */
  32919. _this.invertNormalMapY = false;
  32920. /**
  32921. * Emissivie color used to self-illuminate the model.
  32922. */
  32923. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32924. /**
  32925. * Occlusion Channel Strenght.
  32926. */
  32927. _this.occlusionStrength = 1.0;
  32928. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32929. _this._useAmbientInGrayScale = true;
  32930. return _this;
  32931. }
  32932. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  32933. /**
  32934. * Gets the current transparency mode.
  32935. */
  32936. get: function () {
  32937. return this._transparencyMode;
  32938. },
  32939. /**
  32940. * Sets the transparency mode of the material.
  32941. */
  32942. set: function (value) {
  32943. if (this._transparencyMode === value) {
  32944. return;
  32945. }
  32946. this._transparencyMode = value;
  32947. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  32948. this._forceAlphaTest = true;
  32949. }
  32950. else {
  32951. this._forceAlphaTest = false;
  32952. }
  32953. this._markAllSubMeshesAsTexturesDirty();
  32954. },
  32955. enumerable: true,
  32956. configurable: true
  32957. });
  32958. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  32959. /**
  32960. * Gets the current double sided mode.
  32961. */
  32962. get: function () {
  32963. return this._twoSidedLighting;
  32964. },
  32965. /**
  32966. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32967. */
  32968. set: function (value) {
  32969. if (this._twoSidedLighting === value) {
  32970. return;
  32971. }
  32972. this._twoSidedLighting = value;
  32973. this.backFaceCulling = !value;
  32974. this._markAllSubMeshesAsTexturesDirty();
  32975. },
  32976. enumerable: true,
  32977. configurable: true
  32978. });
  32979. /**
  32980. * Specifies wether or not the alpha value of the albedo texture should be used.
  32981. */
  32982. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32983. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32984. };
  32985. /**
  32986. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  32987. */
  32988. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  32989. if (this._linkRefractionWithTransparency) {
  32990. return false;
  32991. }
  32992. return (this.alpha < 1.0) ||
  32993. (this._shouldUseAlphaFromAlbedoTexture() &&
  32994. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  32995. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  32996. };
  32997. /**
  32998. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  32999. */
  33000. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  33001. if (this._linkRefractionWithTransparency) {
  33002. return false;
  33003. }
  33004. return this._shouldUseAlphaFromAlbedoTexture() &&
  33005. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  33006. };
  33007. /**
  33008. * Return the active textures of the material.
  33009. */
  33010. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  33011. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33012. if (this.environmentTexture) {
  33013. activeTextures.push(this.environmentTexture);
  33014. }
  33015. if (this.normalTexture) {
  33016. activeTextures.push(this.normalTexture);
  33017. }
  33018. if (this.emissiveTexture) {
  33019. activeTextures.push(this.emissiveTexture);
  33020. }
  33021. if (this.occlusionTexture) {
  33022. activeTextures.push(this.occlusionTexture);
  33023. }
  33024. return activeTextures;
  33025. };
  33026. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  33027. return "PBRBaseSimpleMaterial";
  33028. };
  33029. __decorate([
  33030. BABYLON.serialize(),
  33031. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33032. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  33033. __decorate([
  33034. BABYLON.serialize(),
  33035. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33036. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  33037. __decorate([
  33038. BABYLON.serializeAsTexture(),
  33039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  33040. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  33041. __decorate([
  33042. BABYLON.serialize(),
  33043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33044. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  33045. __decorate([
  33046. BABYLON.serialize(),
  33047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33048. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  33049. __decorate([
  33050. BABYLON.serializeAsTexture(),
  33051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  33052. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  33053. __decorate([
  33054. BABYLON.serializeAsColor3("emissive"),
  33055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33056. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  33057. __decorate([
  33058. BABYLON.serializeAsTexture(),
  33059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33060. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  33061. __decorate([
  33062. BABYLON.serialize(),
  33063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  33064. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  33065. __decorate([
  33066. BABYLON.serializeAsTexture(),
  33067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  33068. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  33069. __decorate([
  33070. BABYLON.serialize(),
  33071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  33072. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  33073. __decorate([
  33074. BABYLON.serialize()
  33075. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  33076. __decorate([
  33077. BABYLON.serialize()
  33078. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  33079. return PBRBaseSimpleMaterial;
  33080. }(BABYLON.PBRBaseMaterial));
  33081. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  33082. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33083. })(BABYLON || (BABYLON = {}));
  33084. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  33085. var BABYLON;
  33086. (function (BABYLON) {
  33087. /**
  33088. * The Physically based material of BJS.
  33089. *
  33090. * This offers the main features of a standard PBR material.
  33091. * For more information, please refer to the documentation :
  33092. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33093. */
  33094. var PBRMaterial = (function (_super) {
  33095. __extends(PBRMaterial, _super);
  33096. /**
  33097. * Instantiates a new PBRMaterial instance.
  33098. *
  33099. * @param name The material name
  33100. * @param scene The scene the material will be use in.
  33101. */
  33102. function PBRMaterial(name, scene) {
  33103. var _this = _super.call(this, name, scene) || this;
  33104. /**
  33105. * Intensity of the direct lights e.g. the four lights available in your scene.
  33106. * This impacts both the direct diffuse and specular highlights.
  33107. */
  33108. _this.directIntensity = 1.0;
  33109. /**
  33110. * Intensity of the emissive part of the material.
  33111. * This helps controlling the emissive effect without modifying the emissive color.
  33112. */
  33113. _this.emissiveIntensity = 1.0;
  33114. /**
  33115. * Intensity of the environment e.g. how much the environment will light the object
  33116. * either through harmonics for rough material or through the refelction for shiny ones.
  33117. */
  33118. _this.environmentIntensity = 1.0;
  33119. /**
  33120. * This is a special control allowing the reduction of the specular highlights coming from the
  33121. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33122. */
  33123. _this.specularIntensity = 1.0;
  33124. /**
  33125. * Debug Control allowing disabling the bump map on this material.
  33126. */
  33127. _this.disableBumpMap = false;
  33128. /**
  33129. * AKA Occlusion Texture Intensity in other nomenclature.
  33130. */
  33131. _this.ambientTextureStrength = 1.0;
  33132. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33133. /**
  33134. * AKA Diffuse Color in other nomenclature.
  33135. */
  33136. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  33137. /**
  33138. * AKA Specular Color in other nomenclature.
  33139. */
  33140. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33141. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  33142. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33143. /**
  33144. * AKA Glossiness in other nomenclature.
  33145. */
  33146. _this.microSurface = 1.0;
  33147. /**
  33148. * source material index of refraction (IOR)' / 'destination material IOR.
  33149. */
  33150. _this.indexOfRefraction = 0.66;
  33151. /**
  33152. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33153. */
  33154. _this.invertRefractionY = false;
  33155. /**
  33156. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33157. * Materials half opaque for instance using refraction could benefit from this control.
  33158. */
  33159. _this.linkRefractionWithTransparency = false;
  33160. _this.useLightmapAsShadowmap = false;
  33161. /**
  33162. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33163. */
  33164. _this.useAlphaFromAlbedoTexture = false;
  33165. /**
  33166. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33167. */
  33168. _this.forceAlphaTest = false;
  33169. /**
  33170. * Defines the alpha limits in alpha test mode.
  33171. */
  33172. _this.alphaCutOff = 0.4;
  33173. /**
  33174. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33175. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33176. */
  33177. _this.useSpecularOverAlpha = true;
  33178. /**
  33179. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33180. */
  33181. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  33182. /**
  33183. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33184. */
  33185. _this.useRoughnessFromMetallicTextureAlpha = true;
  33186. /**
  33187. * Specifies if the metallic texture contains the roughness information in its green channel.
  33188. */
  33189. _this.useRoughnessFromMetallicTextureGreen = false;
  33190. /**
  33191. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33192. */
  33193. _this.useMetallnessFromMetallicTextureBlue = false;
  33194. /**
  33195. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33196. */
  33197. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  33198. /**
  33199. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33200. */
  33201. _this.useAmbientInGrayScale = false;
  33202. /**
  33203. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33204. * The material will try to infer what glossiness each pixel should be.
  33205. */
  33206. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  33207. /**
  33208. * BJS is using an harcoded light falloff based on a manually sets up range.
  33209. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33210. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33211. */
  33212. _this.usePhysicalLightFalloff = true;
  33213. /**
  33214. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33215. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33216. */
  33217. _this.useRadianceOverAlpha = true;
  33218. /**
  33219. * Allows using the bump map in parallax mode.
  33220. */
  33221. _this.useParallax = false;
  33222. /**
  33223. * Allows using the bump map in parallax occlusion mode.
  33224. */
  33225. _this.useParallaxOcclusion = false;
  33226. /**
  33227. * Controls the scale bias of the parallax mode.
  33228. */
  33229. _this.parallaxScaleBias = 0.05;
  33230. /**
  33231. * If sets to true, disables all the lights affecting the material.
  33232. */
  33233. _this.disableLighting = false;
  33234. /**
  33235. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33236. */
  33237. _this.forceIrradianceInFragment = false;
  33238. /**
  33239. * Number of Simultaneous lights allowed on the material.
  33240. */
  33241. _this.maxSimultaneousLights = 4;
  33242. /**
  33243. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33244. */
  33245. _this.invertNormalMapX = false;
  33246. /**
  33247. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33248. */
  33249. _this.invertNormalMapY = false;
  33250. /**
  33251. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33252. */
  33253. _this.twoSidedLighting = false;
  33254. /**
  33255. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33256. * in your scene composition.
  33257. */
  33258. _this.preMultiplyAlpha = false;
  33259. /**
  33260. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33261. * And/Or occlude the blended part.
  33262. */
  33263. _this.useAlphaFresnel = false;
  33264. /**
  33265. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33266. * And/Or occlude the blended part.
  33267. */
  33268. _this.environmentBRDFTexture = null;
  33269. /**
  33270. * Force normal to face away from face.
  33271. * (Temporary internal fix to remove before 3.1)
  33272. */
  33273. _this.forceNormalForward = false;
  33274. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33275. return _this;
  33276. }
  33277. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  33278. /**
  33279. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  33280. */
  33281. get: function () {
  33282. return this._PBRMATERIAL_OPAQUE;
  33283. },
  33284. enumerable: true,
  33285. configurable: true
  33286. });
  33287. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  33288. /**
  33289. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  33290. */
  33291. get: function () {
  33292. return this._PBRMATERIAL_ALPHATEST;
  33293. },
  33294. enumerable: true,
  33295. configurable: true
  33296. });
  33297. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  33298. /**
  33299. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33300. */
  33301. get: function () {
  33302. return this._PBRMATERIAL_ALPHABLEND;
  33303. },
  33304. enumerable: true,
  33305. configurable: true
  33306. });
  33307. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  33308. /**
  33309. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33310. * They are also discarded below the alpha cutoff threshold to improve performances.
  33311. */
  33312. get: function () {
  33313. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  33314. },
  33315. enumerable: true,
  33316. configurable: true
  33317. });
  33318. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  33319. /**
  33320. * Gets the image processing configuration used either in this material.
  33321. */
  33322. get: function () {
  33323. return this._imageProcessingConfiguration;
  33324. },
  33325. /**
  33326. * Sets the Default image processing configuration used either in the this material.
  33327. *
  33328. * If sets to null, the scene one is in use.
  33329. */
  33330. set: function (value) {
  33331. this._attachImageProcessingConfiguration(value);
  33332. // Ensure the effect will be rebuilt.
  33333. this._markAllSubMeshesAsTexturesDirty();
  33334. },
  33335. enumerable: true,
  33336. configurable: true
  33337. });
  33338. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  33339. /**
  33340. * Gets wether the color curves effect is enabled.
  33341. */
  33342. get: function () {
  33343. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33344. },
  33345. /**
  33346. * Sets wether the color curves effect is enabled.
  33347. */
  33348. set: function (value) {
  33349. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33350. },
  33351. enumerable: true,
  33352. configurable: true
  33353. });
  33354. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33355. /**
  33356. * Gets wether the color grading effect is enabled.
  33357. */
  33358. get: function () {
  33359. return this.imageProcessingConfiguration.colorGradingEnabled;
  33360. },
  33361. /**
  33362. * Gets wether the color grading effect is enabled.
  33363. */
  33364. set: function (value) {
  33365. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33366. },
  33367. enumerable: true,
  33368. configurable: true
  33369. });
  33370. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33371. /**
  33372. * Gets wether tonemapping is enabled or not.
  33373. */
  33374. get: function () {
  33375. return this._imageProcessingConfiguration.toneMappingEnabled;
  33376. },
  33377. /**
  33378. * Sets wether tonemapping is enabled or not
  33379. */
  33380. set: function (value) {
  33381. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33382. },
  33383. enumerable: true,
  33384. configurable: true
  33385. });
  33386. ;
  33387. ;
  33388. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33389. /**
  33390. * The camera exposure used on this material.
  33391. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33392. * This corresponds to a photographic exposure.
  33393. */
  33394. get: function () {
  33395. return this._imageProcessingConfiguration.exposure;
  33396. },
  33397. /**
  33398. * The camera exposure used on this material.
  33399. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33400. * This corresponds to a photographic exposure.
  33401. */
  33402. set: function (value) {
  33403. this._imageProcessingConfiguration.exposure = value;
  33404. },
  33405. enumerable: true,
  33406. configurable: true
  33407. });
  33408. ;
  33409. ;
  33410. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33411. /**
  33412. * Gets The camera contrast used on this material.
  33413. */
  33414. get: function () {
  33415. return this._imageProcessingConfiguration.contrast;
  33416. },
  33417. /**
  33418. * Sets The camera contrast used on this material.
  33419. */
  33420. set: function (value) {
  33421. this._imageProcessingConfiguration.contrast = value;
  33422. },
  33423. enumerable: true,
  33424. configurable: true
  33425. });
  33426. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33427. /**
  33428. * Gets the Color Grading 2D Lookup Texture.
  33429. */
  33430. get: function () {
  33431. return this._imageProcessingConfiguration.colorGradingTexture;
  33432. },
  33433. /**
  33434. * Sets the Color Grading 2D Lookup Texture.
  33435. */
  33436. set: function (value) {
  33437. this._imageProcessingConfiguration.colorGradingTexture = value;
  33438. },
  33439. enumerable: true,
  33440. configurable: true
  33441. });
  33442. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33443. /**
  33444. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33445. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33446. * 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;
  33447. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33448. */
  33449. get: function () {
  33450. return this._imageProcessingConfiguration.colorCurves;
  33451. },
  33452. /**
  33453. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33454. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33455. * 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;
  33456. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33457. */
  33458. set: function (value) {
  33459. this._imageProcessingConfiguration.colorCurves = value;
  33460. },
  33461. enumerable: true,
  33462. configurable: true
  33463. });
  33464. PBRMaterial.prototype.getClassName = function () {
  33465. return "PBRMaterial";
  33466. };
  33467. PBRMaterial.prototype.getActiveTextures = function () {
  33468. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33469. if (this._albedoTexture) {
  33470. activeTextures.push(this._albedoTexture);
  33471. }
  33472. if (this._ambientTexture) {
  33473. activeTextures.push(this._ambientTexture);
  33474. }
  33475. if (this._opacityTexture) {
  33476. activeTextures.push(this._opacityTexture);
  33477. }
  33478. if (this._reflectionTexture) {
  33479. activeTextures.push(this._reflectionTexture);
  33480. }
  33481. if (this._emissiveTexture) {
  33482. activeTextures.push(this._emissiveTexture);
  33483. }
  33484. if (this._reflectivityTexture) {
  33485. activeTextures.push(this._reflectivityTexture);
  33486. }
  33487. if (this._metallicTexture) {
  33488. activeTextures.push(this._metallicTexture);
  33489. }
  33490. if (this._microSurfaceTexture) {
  33491. activeTextures.push(this._microSurfaceTexture);
  33492. }
  33493. if (this._bumpTexture) {
  33494. activeTextures.push(this._bumpTexture);
  33495. }
  33496. if (this._lightmapTexture) {
  33497. activeTextures.push(this._lightmapTexture);
  33498. }
  33499. if (this._refractionTexture) {
  33500. activeTextures.push(this._refractionTexture);
  33501. }
  33502. return activeTextures;
  33503. };
  33504. PBRMaterial.prototype.hasTexture = function (texture) {
  33505. if (_super.prototype.hasTexture.call(this, texture)) {
  33506. return true;
  33507. }
  33508. if (this._albedoTexture === texture) {
  33509. return true;
  33510. }
  33511. if (this._ambientTexture === texture) {
  33512. return true;
  33513. }
  33514. if (this._opacityTexture === texture) {
  33515. return true;
  33516. }
  33517. if (this._reflectionTexture === texture) {
  33518. return true;
  33519. }
  33520. if (this._reflectivityTexture === texture) {
  33521. return true;
  33522. }
  33523. if (this._metallicTexture === texture) {
  33524. return true;
  33525. }
  33526. if (this._microSurfaceTexture === texture) {
  33527. return true;
  33528. }
  33529. if (this._bumpTexture === texture) {
  33530. return true;
  33531. }
  33532. if (this._lightmapTexture === texture) {
  33533. return true;
  33534. }
  33535. if (this._refractionTexture === texture) {
  33536. return true;
  33537. }
  33538. return false;
  33539. };
  33540. PBRMaterial.prototype.clone = function (name) {
  33541. var _this = this;
  33542. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33543. };
  33544. PBRMaterial.prototype.serialize = function () {
  33545. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33546. serializationObject.customType = "BABYLON.PBRMaterial";
  33547. return serializationObject;
  33548. };
  33549. // Statics
  33550. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33551. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33552. };
  33553. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33554. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33555. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33556. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33557. __decorate([
  33558. BABYLON.serialize(),
  33559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33560. ], PBRMaterial.prototype, "directIntensity", void 0);
  33561. __decorate([
  33562. BABYLON.serialize(),
  33563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33564. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33565. __decorate([
  33566. BABYLON.serialize(),
  33567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33568. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33569. __decorate([
  33570. BABYLON.serialize(),
  33571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33572. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33573. __decorate([
  33574. BABYLON.serialize(),
  33575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33576. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33577. __decorate([
  33578. BABYLON.serializeAsTexture(),
  33579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33580. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33581. __decorate([
  33582. BABYLON.serializeAsTexture(),
  33583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33584. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33585. __decorate([
  33586. BABYLON.serialize(),
  33587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33588. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33589. __decorate([
  33590. BABYLON.serializeAsTexture(),
  33591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33592. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33593. __decorate([
  33594. BABYLON.serializeAsTexture(),
  33595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33596. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33597. __decorate([
  33598. BABYLON.serializeAsTexture(),
  33599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33600. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33601. __decorate([
  33602. BABYLON.serializeAsTexture(),
  33603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33604. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33605. __decorate([
  33606. BABYLON.serializeAsTexture(),
  33607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33608. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33609. __decorate([
  33610. BABYLON.serialize(),
  33611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33612. ], PBRMaterial.prototype, "metallic", void 0);
  33613. __decorate([
  33614. BABYLON.serialize(),
  33615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33616. ], PBRMaterial.prototype, "roughness", void 0);
  33617. __decorate([
  33618. BABYLON.serializeAsTexture(),
  33619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33620. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33621. __decorate([
  33622. BABYLON.serializeAsTexture(),
  33623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33624. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33625. __decorate([
  33626. BABYLON.serializeAsTexture(),
  33627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33628. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33629. __decorate([
  33630. BABYLON.serializeAsTexture(),
  33631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33632. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33633. __decorate([
  33634. BABYLON.serializeAsColor3("ambient"),
  33635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33636. ], PBRMaterial.prototype, "ambientColor", void 0);
  33637. __decorate([
  33638. BABYLON.serializeAsColor3("albedo"),
  33639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33640. ], PBRMaterial.prototype, "albedoColor", void 0);
  33641. __decorate([
  33642. BABYLON.serializeAsColor3("reflectivity"),
  33643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33644. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33645. __decorate([
  33646. BABYLON.serializeAsColor3("reflection"),
  33647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33648. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33649. __decorate([
  33650. BABYLON.serializeAsColor3("emissive"),
  33651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33652. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33653. __decorate([
  33654. BABYLON.serialize(),
  33655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33656. ], PBRMaterial.prototype, "microSurface", void 0);
  33657. __decorate([
  33658. BABYLON.serialize(),
  33659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33660. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33661. __decorate([
  33662. BABYLON.serialize(),
  33663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33664. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33665. __decorate([
  33666. BABYLON.serialize(),
  33667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33668. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33669. __decorate([
  33670. BABYLON.serialize(),
  33671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33672. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33673. __decorate([
  33674. BABYLON.serialize(),
  33675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33676. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  33677. __decorate([
  33678. BABYLON.serialize(),
  33679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33680. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  33681. __decorate([
  33682. BABYLON.serialize(),
  33683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33684. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  33685. __decorate([
  33686. BABYLON.serialize(),
  33687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33688. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  33689. __decorate([
  33690. BABYLON.serialize(),
  33691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33692. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  33693. __decorate([
  33694. BABYLON.serialize(),
  33695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33696. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  33697. __decorate([
  33698. BABYLON.serialize(),
  33699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33700. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  33701. __decorate([
  33702. BABYLON.serialize(),
  33703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33704. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  33705. __decorate([
  33706. BABYLON.serialize(),
  33707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33708. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  33709. __decorate([
  33710. BABYLON.serialize(),
  33711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33712. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  33713. __decorate([
  33714. BABYLON.serialize(),
  33715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33716. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  33717. __decorate([
  33718. BABYLON.serialize(),
  33719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33720. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  33721. __decorate([
  33722. BABYLON.serialize(),
  33723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33724. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  33725. __decorate([
  33726. BABYLON.serialize(),
  33727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33728. ], PBRMaterial.prototype, "useParallax", void 0);
  33729. __decorate([
  33730. BABYLON.serialize(),
  33731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33732. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  33733. __decorate([
  33734. BABYLON.serialize(),
  33735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33736. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  33737. __decorate([
  33738. BABYLON.serialize(),
  33739. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33740. ], PBRMaterial.prototype, "disableLighting", void 0);
  33741. __decorate([
  33742. BABYLON.serialize(),
  33743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33744. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  33745. __decorate([
  33746. BABYLON.serialize(),
  33747. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33748. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  33749. __decorate([
  33750. BABYLON.serialize(),
  33751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33752. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  33753. __decorate([
  33754. BABYLON.serialize(),
  33755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33756. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  33757. __decorate([
  33758. BABYLON.serialize(),
  33759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33760. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  33761. __decorate([
  33762. BABYLON.serialize(),
  33763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33764. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  33765. __decorate([
  33766. BABYLON.serialize(),
  33767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33768. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  33769. __decorate([
  33770. BABYLON.serializeAsTexture(),
  33771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33772. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  33773. __decorate([
  33774. BABYLON.serialize(),
  33775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33776. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  33777. return PBRMaterial;
  33778. }(BABYLON.PBRBaseMaterial));
  33779. BABYLON.PBRMaterial = PBRMaterial;
  33780. })(BABYLON || (BABYLON = {}));
  33781. //# sourceMappingURL=babylon.pbrMaterial.js.map
  33782. var BABYLON;
  33783. (function (BABYLON) {
  33784. /**
  33785. * The PBR material of BJS following the metal roughness convention.
  33786. *
  33787. * This fits to the PBR convention in the GLTF definition:
  33788. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  33789. */
  33790. var PBRMetallicRoughnessMaterial = (function (_super) {
  33791. __extends(PBRMetallicRoughnessMaterial, _super);
  33792. /**
  33793. * Instantiates a new PBRMetalRoughnessMaterial instance.
  33794. *
  33795. * @param name The material name
  33796. * @param scene The scene the material will be use in.
  33797. */
  33798. function PBRMetallicRoughnessMaterial(name, scene) {
  33799. var _this = _super.call(this, name, scene) || this;
  33800. _this._useRoughnessFromMetallicTextureAlpha = false;
  33801. _this._useRoughnessFromMetallicTextureGreen = true;
  33802. _this._useMetallnessFromMetallicTextureBlue = true;
  33803. return _this;
  33804. }
  33805. /**
  33806. * Return the currrent class name of the material.
  33807. */
  33808. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  33809. return "PBRMetallicRoughnessMaterial";
  33810. };
  33811. /**
  33812. * Return the active textures of the material.
  33813. */
  33814. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  33815. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33816. if (this.baseTexture) {
  33817. activeTextures.push(this.baseTexture);
  33818. }
  33819. if (this.metallicRoughnessTexture) {
  33820. activeTextures.push(this.metallicRoughnessTexture);
  33821. }
  33822. return activeTextures;
  33823. };
  33824. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  33825. if (_super.prototype.hasTexture.call(this, texture)) {
  33826. return true;
  33827. }
  33828. if (this.baseTexture === texture) {
  33829. return true;
  33830. }
  33831. if (this.metallicRoughnessTexture === texture) {
  33832. return true;
  33833. }
  33834. return false;
  33835. };
  33836. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  33837. var _this = this;
  33838. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  33839. };
  33840. /**
  33841. * Serialize the material to a parsable JSON object.
  33842. */
  33843. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  33844. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33845. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  33846. return serializationObject;
  33847. };
  33848. /**
  33849. * Parses a JSON object correponding to the serialize function.
  33850. */
  33851. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  33852. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  33853. };
  33854. __decorate([
  33855. BABYLON.serializeAsColor3(),
  33856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33857. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  33858. __decorate([
  33859. BABYLON.serializeAsTexture(),
  33860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33861. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  33862. __decorate([
  33863. BABYLON.serialize(),
  33864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33865. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  33866. __decorate([
  33867. BABYLON.serialize(),
  33868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33869. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  33870. __decorate([
  33871. BABYLON.serializeAsTexture(),
  33872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  33873. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  33874. return PBRMetallicRoughnessMaterial;
  33875. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33876. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  33877. })(BABYLON || (BABYLON = {}));
  33878. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  33879. var BABYLON;
  33880. (function (BABYLON) {
  33881. /**
  33882. * The PBR material of BJS following the specular glossiness convention.
  33883. *
  33884. * This fits to the PBR convention in the GLTF definition:
  33885. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  33886. */
  33887. var PBRSpecularGlossinessMaterial = (function (_super) {
  33888. __extends(PBRSpecularGlossinessMaterial, _super);
  33889. /**
  33890. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  33891. *
  33892. * @param name The material name
  33893. * @param scene The scene the material will be use in.
  33894. */
  33895. function PBRSpecularGlossinessMaterial(name, scene) {
  33896. var _this = _super.call(this, name, scene) || this;
  33897. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  33898. return _this;
  33899. }
  33900. /**
  33901. * Return the currrent class name of the material.
  33902. */
  33903. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  33904. return "PBRSpecularGlossinessMaterial";
  33905. };
  33906. /**
  33907. * Return the active textures of the material.
  33908. */
  33909. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  33910. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33911. if (this.diffuseTexture) {
  33912. activeTextures.push(this.diffuseTexture);
  33913. }
  33914. if (this.specularGlossinessTexture) {
  33915. activeTextures.push(this.specularGlossinessTexture);
  33916. }
  33917. return activeTextures;
  33918. };
  33919. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  33920. if (_super.prototype.hasTexture.call(this, texture)) {
  33921. return true;
  33922. }
  33923. if (this.diffuseTexture === texture) {
  33924. return true;
  33925. }
  33926. if (this.specularGlossinessTexture === texture) {
  33927. return true;
  33928. }
  33929. return false;
  33930. };
  33931. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  33932. var _this = this;
  33933. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  33934. };
  33935. /**
  33936. * Serialize the material to a parsable JSON object.
  33937. */
  33938. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  33939. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33940. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  33941. return serializationObject;
  33942. };
  33943. /**
  33944. * Parses a JSON object correponding to the serialize function.
  33945. */
  33946. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  33947. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  33948. };
  33949. __decorate([
  33950. BABYLON.serializeAsColor3("diffuse"),
  33951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33952. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  33953. __decorate([
  33954. BABYLON.serializeAsTexture(),
  33955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33956. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  33957. __decorate([
  33958. BABYLON.serializeAsColor3("specular"),
  33959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  33960. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  33961. __decorate([
  33962. BABYLON.serialize(),
  33963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  33964. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  33965. __decorate([
  33966. BABYLON.serializeAsTexture(),
  33967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  33968. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  33969. return PBRSpecularGlossinessMaterial;
  33970. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33971. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  33972. })(BABYLON || (BABYLON = {}));
  33973. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  33974. var BABYLON;
  33975. (function (BABYLON) {
  33976. BABYLON.CameraInputTypes = {};
  33977. var CameraInputsManager = (function () {
  33978. function CameraInputsManager(camera) {
  33979. this.attached = {};
  33980. this.camera = camera;
  33981. this.checkInputs = function () { };
  33982. }
  33983. CameraInputsManager.prototype.add = function (input) {
  33984. var type = input.getSimpleName();
  33985. if (this.attached[type]) {
  33986. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  33987. return;
  33988. }
  33989. this.attached[type] = input;
  33990. input.camera = this.camera;
  33991. //for checkInputs, we are dynamically creating a function
  33992. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  33993. if (input.checkInputs) {
  33994. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33995. }
  33996. if (this.attachedElement) {
  33997. input.attachControl(this.attachedElement);
  33998. }
  33999. };
  34000. CameraInputsManager.prototype.remove = function (inputToRemove) {
  34001. for (var cam in this.attached) {
  34002. var input = this.attached[cam];
  34003. if (input === inputToRemove) {
  34004. input.detachControl(this.attachedElement);
  34005. input.camera = null;
  34006. delete this.attached[cam];
  34007. this.rebuildInputCheck();
  34008. }
  34009. }
  34010. };
  34011. CameraInputsManager.prototype.removeByType = function (inputType) {
  34012. for (var cam in this.attached) {
  34013. var input = this.attached[cam];
  34014. if (input.getClassName() === inputType) {
  34015. input.detachControl(this.attachedElement);
  34016. input.camera = null;
  34017. delete this.attached[cam];
  34018. this.rebuildInputCheck();
  34019. }
  34020. }
  34021. };
  34022. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  34023. var current = this.checkInputs;
  34024. return function () {
  34025. current();
  34026. fn();
  34027. };
  34028. };
  34029. CameraInputsManager.prototype.attachInput = function (input) {
  34030. input.attachControl(this.attachedElement, this.noPreventDefault);
  34031. };
  34032. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  34033. if (this.attachedElement) {
  34034. return;
  34035. }
  34036. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  34037. this.attachedElement = element;
  34038. this.noPreventDefault = noPreventDefault;
  34039. for (var cam in this.attached) {
  34040. var input = this.attached[cam];
  34041. this.attached[cam].attachControl(element, noPreventDefault);
  34042. }
  34043. };
  34044. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  34045. if (disconnect === void 0) { disconnect = false; }
  34046. if (this.attachedElement !== element) {
  34047. return;
  34048. }
  34049. for (var cam in this.attached) {
  34050. var input = this.attached[cam];
  34051. this.attached[cam].detachControl(element);
  34052. if (disconnect) {
  34053. this.attached[cam].camera = null;
  34054. }
  34055. }
  34056. this.attachedElement = null;
  34057. };
  34058. CameraInputsManager.prototype.rebuildInputCheck = function () {
  34059. this.checkInputs = function () { };
  34060. for (var cam in this.attached) {
  34061. var input = this.attached[cam];
  34062. if (input.checkInputs) {
  34063. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34064. }
  34065. }
  34066. };
  34067. CameraInputsManager.prototype.clear = function () {
  34068. if (this.attachedElement) {
  34069. this.detachElement(this.attachedElement, true);
  34070. }
  34071. this.attached = {};
  34072. this.attachedElement = null;
  34073. this.checkInputs = function () { };
  34074. };
  34075. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  34076. var inputs = {};
  34077. for (var cam in this.attached) {
  34078. var input = this.attached[cam];
  34079. var res = BABYLON.SerializationHelper.Serialize(input);
  34080. inputs[input.getClassName()] = res;
  34081. }
  34082. serializedCamera.inputsmgr = inputs;
  34083. };
  34084. CameraInputsManager.prototype.parse = function (parsedCamera) {
  34085. var parsedInputs = parsedCamera.inputsmgr;
  34086. if (parsedInputs) {
  34087. this.clear();
  34088. for (var n in parsedInputs) {
  34089. var construct = BABYLON.CameraInputTypes[n];
  34090. if (construct) {
  34091. var parsedinput = parsedInputs[n];
  34092. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  34093. this.add(input);
  34094. }
  34095. }
  34096. }
  34097. else {
  34098. //2016-03-08 this part is for managing backward compatibility
  34099. for (var n in this.attached) {
  34100. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  34101. if (construct) {
  34102. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  34103. this.remove(this.attached[n]);
  34104. this.add(input);
  34105. }
  34106. }
  34107. }
  34108. };
  34109. return CameraInputsManager;
  34110. }());
  34111. BABYLON.CameraInputsManager = CameraInputsManager;
  34112. })(BABYLON || (BABYLON = {}));
  34113. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  34114. var BABYLON;
  34115. (function (BABYLON) {
  34116. var FreeCameraMouseInput = (function () {
  34117. function FreeCameraMouseInput(touchEnabled) {
  34118. if (touchEnabled === void 0) { touchEnabled = true; }
  34119. this.touchEnabled = touchEnabled;
  34120. this.buttons = [0, 1, 2];
  34121. this.angularSensibility = 2000.0;
  34122. }
  34123. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  34124. var _this = this;
  34125. var engine = this.camera.getEngine();
  34126. if (!this._pointerInput) {
  34127. this._pointerInput = function (p, s) {
  34128. var evt = p.event;
  34129. if (!_this.touchEnabled && evt.pointerType === "touch") {
  34130. return;
  34131. }
  34132. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34133. return;
  34134. }
  34135. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34136. try {
  34137. evt.srcElement.setPointerCapture(evt.pointerId);
  34138. }
  34139. catch (e) {
  34140. //Nothing to do with the error. Execution will continue.
  34141. }
  34142. _this.previousPosition = {
  34143. x: evt.clientX,
  34144. y: evt.clientY
  34145. };
  34146. if (!noPreventDefault) {
  34147. evt.preventDefault();
  34148. element.focus();
  34149. }
  34150. }
  34151. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34152. try {
  34153. evt.srcElement.releasePointerCapture(evt.pointerId);
  34154. }
  34155. catch (e) {
  34156. //Nothing to do with the error.
  34157. }
  34158. _this.previousPosition = null;
  34159. if (!noPreventDefault) {
  34160. evt.preventDefault();
  34161. }
  34162. }
  34163. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34164. if (!_this.previousPosition || engine.isPointerLock) {
  34165. return;
  34166. }
  34167. var offsetX = evt.clientX - _this.previousPosition.x;
  34168. var offsetY = evt.clientY - _this.previousPosition.y;
  34169. if (_this.camera.getScene().useRightHandedSystem) {
  34170. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34171. }
  34172. else {
  34173. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34174. }
  34175. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34176. _this.previousPosition = {
  34177. x: evt.clientX,
  34178. y: evt.clientY
  34179. };
  34180. if (!noPreventDefault) {
  34181. evt.preventDefault();
  34182. }
  34183. }
  34184. };
  34185. }
  34186. this._onMouseMove = function (evt) {
  34187. if (!engine.isPointerLock) {
  34188. return;
  34189. }
  34190. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34191. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34192. if (_this.camera.getScene().useRightHandedSystem) {
  34193. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34194. }
  34195. else {
  34196. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34197. }
  34198. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34199. _this.previousPosition = null;
  34200. if (!noPreventDefault) {
  34201. evt.preventDefault();
  34202. }
  34203. };
  34204. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34205. element.addEventListener("mousemove", this._onMouseMove, false);
  34206. };
  34207. FreeCameraMouseInput.prototype.detachControl = function (element) {
  34208. if (this._observer && element) {
  34209. this.camera.getScene().onPointerObservable.remove(this._observer);
  34210. element.removeEventListener("mousemove", this._onMouseMove);
  34211. this._observer = null;
  34212. this._onMouseMove = null;
  34213. this.previousPosition = null;
  34214. }
  34215. };
  34216. FreeCameraMouseInput.prototype.getClassName = function () {
  34217. return "FreeCameraMouseInput";
  34218. };
  34219. FreeCameraMouseInput.prototype.getSimpleName = function () {
  34220. return "mouse";
  34221. };
  34222. __decorate([
  34223. BABYLON.serialize()
  34224. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  34225. __decorate([
  34226. BABYLON.serialize()
  34227. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  34228. return FreeCameraMouseInput;
  34229. }());
  34230. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  34231. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  34232. })(BABYLON || (BABYLON = {}));
  34233. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  34234. var BABYLON;
  34235. (function (BABYLON) {
  34236. var FreeCameraKeyboardMoveInput = (function () {
  34237. function FreeCameraKeyboardMoveInput() {
  34238. this._keys = [];
  34239. this.keysUp = [38];
  34240. this.keysDown = [40];
  34241. this.keysLeft = [37];
  34242. this.keysRight = [39];
  34243. }
  34244. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34245. var _this = this;
  34246. if (this._onCanvasBlurObserver) {
  34247. return;
  34248. }
  34249. this._scene = this.camera.getScene();
  34250. this._engine = this._scene.getEngine();
  34251. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  34252. _this._keys = [];
  34253. });
  34254. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  34255. var evt = info.event;
  34256. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  34257. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34258. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34259. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34260. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34261. var index = _this._keys.indexOf(evt.keyCode);
  34262. if (index === -1) {
  34263. _this._keys.push(evt.keyCode);
  34264. }
  34265. if (!noPreventDefault) {
  34266. evt.preventDefault();
  34267. }
  34268. }
  34269. }
  34270. else {
  34271. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34272. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34273. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34274. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34275. var index = _this._keys.indexOf(evt.keyCode);
  34276. if (index >= 0) {
  34277. _this._keys.splice(index, 1);
  34278. }
  34279. if (!noPreventDefault) {
  34280. evt.preventDefault();
  34281. }
  34282. }
  34283. }
  34284. });
  34285. };
  34286. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34287. if (this._scene) {
  34288. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  34289. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  34290. this._onKeyboardObserver = null;
  34291. this._onCanvasBlurObserver = null;
  34292. }
  34293. this._keys = [];
  34294. };
  34295. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34296. if (this._onKeyboardObserver) {
  34297. var camera = this.camera;
  34298. // Keyboard
  34299. for (var index = 0; index < this._keys.length; index++) {
  34300. var keyCode = this._keys[index];
  34301. var speed = camera._computeLocalCameraSpeed();
  34302. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34303. camera._localDirection.copyFromFloats(-speed, 0, 0);
  34304. }
  34305. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34306. camera._localDirection.copyFromFloats(0, 0, speed);
  34307. }
  34308. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34309. camera._localDirection.copyFromFloats(speed, 0, 0);
  34310. }
  34311. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34312. camera._localDirection.copyFromFloats(0, 0, -speed);
  34313. }
  34314. if (camera.getScene().useRightHandedSystem) {
  34315. camera._localDirection.z *= -1;
  34316. }
  34317. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  34318. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  34319. camera.cameraDirection.addInPlace(camera._transformedDirection);
  34320. }
  34321. }
  34322. };
  34323. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  34324. return "FreeCameraKeyboardMoveInput";
  34325. };
  34326. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  34327. this._keys = [];
  34328. };
  34329. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34330. return "keyboard";
  34331. };
  34332. __decorate([
  34333. BABYLON.serialize()
  34334. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34335. __decorate([
  34336. BABYLON.serialize()
  34337. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34338. __decorate([
  34339. BABYLON.serialize()
  34340. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34341. __decorate([
  34342. BABYLON.serialize()
  34343. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34344. return FreeCameraKeyboardMoveInput;
  34345. }());
  34346. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  34347. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  34348. })(BABYLON || (BABYLON = {}));
  34349. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34350. var BABYLON;
  34351. (function (BABYLON) {
  34352. var FreeCameraInputsManager = (function (_super) {
  34353. __extends(FreeCameraInputsManager, _super);
  34354. function FreeCameraInputsManager(camera) {
  34355. return _super.call(this, camera) || this;
  34356. }
  34357. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34358. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34359. return this;
  34360. };
  34361. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34362. if (touchEnabled === void 0) { touchEnabled = true; }
  34363. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34364. return this;
  34365. };
  34366. FreeCameraInputsManager.prototype.addGamepad = function () {
  34367. this.add(new BABYLON.FreeCameraGamepadInput());
  34368. return this;
  34369. };
  34370. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34371. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34372. return this;
  34373. };
  34374. FreeCameraInputsManager.prototype.addTouch = function () {
  34375. this.add(new BABYLON.FreeCameraTouchInput());
  34376. return this;
  34377. };
  34378. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34379. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34380. return this;
  34381. };
  34382. return FreeCameraInputsManager;
  34383. }(BABYLON.CameraInputsManager));
  34384. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34385. })(BABYLON || (BABYLON = {}));
  34386. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34387. /// <reference path="babylon.camera.ts" />
  34388. var BABYLON;
  34389. (function (BABYLON) {
  34390. var TargetCamera = (function (_super) {
  34391. __extends(TargetCamera, _super);
  34392. function TargetCamera(name, position, scene) {
  34393. var _this = _super.call(this, name, position, scene) || this;
  34394. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34395. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34396. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34397. _this.speed = 2.0;
  34398. _this.noRotationConstraint = false;
  34399. _this.lockedTarget = null;
  34400. _this._currentTarget = BABYLON.Vector3.Zero();
  34401. _this._viewMatrix = BABYLON.Matrix.Zero();
  34402. _this._camMatrix = BABYLON.Matrix.Zero();
  34403. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34404. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34405. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34406. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34407. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34408. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34409. _this._tempMatrix = BABYLON.Matrix.Zero();
  34410. return _this;
  34411. }
  34412. TargetCamera.prototype.getFrontPosition = function (distance) {
  34413. var direction = this.getTarget().subtract(this.position);
  34414. direction.normalize();
  34415. direction.scaleInPlace(distance);
  34416. return this.globalPosition.add(direction);
  34417. };
  34418. TargetCamera.prototype._getLockedTargetPosition = function () {
  34419. if (!this.lockedTarget) {
  34420. return null;
  34421. }
  34422. if (this.lockedTarget.absolutePosition) {
  34423. this.lockedTarget.computeWorldMatrix();
  34424. }
  34425. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34426. };
  34427. TargetCamera.prototype.storeState = function () {
  34428. this._storedPosition = this.position.clone();
  34429. this._storedRotation = this.rotation.clone();
  34430. if (this.rotationQuaternion) {
  34431. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  34432. }
  34433. return _super.prototype.storeState.call(this);
  34434. };
  34435. /**
  34436. * Restored camera state. You must call storeState() first
  34437. */
  34438. TargetCamera.prototype._restoreStateValues = function () {
  34439. if (!_super.prototype._restoreStateValues.call(this)) {
  34440. return false;
  34441. }
  34442. this.position = this._storedPosition.clone();
  34443. this.rotation = this._storedRotation.clone();
  34444. if (this.rotationQuaternion) {
  34445. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  34446. }
  34447. this.cameraDirection.copyFromFloats(0, 0, 0);
  34448. this.cameraRotation.copyFromFloats(0, 0);
  34449. return true;
  34450. };
  34451. // Cache
  34452. TargetCamera.prototype._initCache = function () {
  34453. _super.prototype._initCache.call(this);
  34454. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34455. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34456. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34457. };
  34458. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34459. if (!ignoreParentClass) {
  34460. _super.prototype._updateCache.call(this);
  34461. }
  34462. var lockedTargetPosition = this._getLockedTargetPosition();
  34463. if (!lockedTargetPosition) {
  34464. this._cache.lockedTarget = null;
  34465. }
  34466. else {
  34467. if (!this._cache.lockedTarget) {
  34468. this._cache.lockedTarget = lockedTargetPosition.clone();
  34469. }
  34470. else {
  34471. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34472. }
  34473. }
  34474. this._cache.rotation.copyFrom(this.rotation);
  34475. if (this.rotationQuaternion)
  34476. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34477. };
  34478. // Synchronized
  34479. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34480. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34481. return false;
  34482. }
  34483. var lockedTargetPosition = this._getLockedTargetPosition();
  34484. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34485. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34486. };
  34487. // Methods
  34488. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34489. var engine = this.getEngine();
  34490. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34491. };
  34492. // Target
  34493. TargetCamera.prototype.setTarget = function (target) {
  34494. this.upVector.normalize();
  34495. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34496. this._camMatrix.invert();
  34497. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34498. var vDir = target.subtract(this.position);
  34499. if (vDir.x >= 0.0) {
  34500. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34501. }
  34502. else {
  34503. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34504. }
  34505. this.rotation.z = 0;
  34506. if (isNaN(this.rotation.x)) {
  34507. this.rotation.x = 0;
  34508. }
  34509. if (isNaN(this.rotation.y)) {
  34510. this.rotation.y = 0;
  34511. }
  34512. if (isNaN(this.rotation.z)) {
  34513. this.rotation.z = 0;
  34514. }
  34515. if (this.rotationQuaternion) {
  34516. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34517. }
  34518. };
  34519. /**
  34520. * Return the current target position of the camera. This value is expressed in local space.
  34521. */
  34522. TargetCamera.prototype.getTarget = function () {
  34523. return this._currentTarget;
  34524. };
  34525. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34526. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34527. };
  34528. TargetCamera.prototype._updatePosition = function () {
  34529. if (this.parent) {
  34530. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34531. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34532. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34533. return;
  34534. }
  34535. this.position.addInPlace(this.cameraDirection);
  34536. };
  34537. TargetCamera.prototype._checkInputs = function () {
  34538. var needToMove = this._decideIfNeedsToMove();
  34539. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34540. // Move
  34541. if (needToMove) {
  34542. this._updatePosition();
  34543. }
  34544. // Rotate
  34545. if (needToRotate) {
  34546. this.rotation.x += this.cameraRotation.x;
  34547. this.rotation.y += this.cameraRotation.y;
  34548. //rotate, if quaternion is set and rotation was used
  34549. if (this.rotationQuaternion) {
  34550. var len = this.rotation.lengthSquared();
  34551. if (len) {
  34552. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34553. }
  34554. }
  34555. if (!this.noRotationConstraint) {
  34556. var limit = (Math.PI / 2) * 0.95;
  34557. if (this.rotation.x > limit)
  34558. this.rotation.x = limit;
  34559. if (this.rotation.x < -limit)
  34560. this.rotation.x = -limit;
  34561. }
  34562. }
  34563. // Inertia
  34564. if (needToMove) {
  34565. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34566. this.cameraDirection.x = 0;
  34567. }
  34568. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34569. this.cameraDirection.y = 0;
  34570. }
  34571. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34572. this.cameraDirection.z = 0;
  34573. }
  34574. this.cameraDirection.scaleInPlace(this.inertia);
  34575. }
  34576. if (needToRotate) {
  34577. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34578. this.cameraRotation.x = 0;
  34579. }
  34580. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34581. this.cameraRotation.y = 0;
  34582. }
  34583. this.cameraRotation.scaleInPlace(this.inertia);
  34584. }
  34585. _super.prototype._checkInputs.call(this);
  34586. };
  34587. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34588. if (this.rotationQuaternion) {
  34589. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34590. //update the up vector!
  34591. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34592. }
  34593. else {
  34594. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34595. }
  34596. };
  34597. TargetCamera.prototype._getViewMatrix = function () {
  34598. if (!this.lockedTarget) {
  34599. // Compute
  34600. this._updateCameraRotationMatrix();
  34601. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34602. // Computing target and final matrix
  34603. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34604. }
  34605. else {
  34606. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34607. }
  34608. if (this.getScene().useRightHandedSystem) {
  34609. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34610. }
  34611. else {
  34612. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34613. }
  34614. return this._viewMatrix;
  34615. };
  34616. /**
  34617. * @override
  34618. * Override Camera.createRigCamera
  34619. */
  34620. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34621. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34622. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34623. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34624. if (!this.rotationQuaternion) {
  34625. this.rotationQuaternion = new BABYLON.Quaternion();
  34626. }
  34627. rigCamera._cameraRigParams = {};
  34628. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34629. }
  34630. return rigCamera;
  34631. }
  34632. return null;
  34633. };
  34634. /**
  34635. * @override
  34636. * Override Camera._updateRigCameras
  34637. */
  34638. TargetCamera.prototype._updateRigCameras = function () {
  34639. var camLeft = this._rigCameras[0];
  34640. var camRight = this._rigCameras[1];
  34641. switch (this.cameraRigMode) {
  34642. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34643. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34644. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34645. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34646. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34647. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34648. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34649. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34650. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34651. camLeft.setTarget(this.getTarget());
  34652. camRight.setTarget(this.getTarget());
  34653. break;
  34654. case BABYLON.Camera.RIG_MODE_VR:
  34655. if (camLeft.rotationQuaternion) {
  34656. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34657. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34658. }
  34659. else {
  34660. camLeft.rotation.copyFrom(this.rotation);
  34661. camRight.rotation.copyFrom(this.rotation);
  34662. }
  34663. camLeft.position.copyFrom(this.position);
  34664. camRight.position.copyFrom(this.position);
  34665. break;
  34666. }
  34667. _super.prototype._updateRigCameras.call(this);
  34668. };
  34669. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  34670. if (!this._rigCamTransformMatrix) {
  34671. this._rigCamTransformMatrix = new BABYLON.Matrix();
  34672. }
  34673. var target = this.getTarget();
  34674. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  34675. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  34676. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  34677. };
  34678. TargetCamera.prototype.getClassName = function () {
  34679. return "TargetCamera";
  34680. };
  34681. __decorate([
  34682. BABYLON.serializeAsVector3()
  34683. ], TargetCamera.prototype, "rotation", void 0);
  34684. __decorate([
  34685. BABYLON.serialize()
  34686. ], TargetCamera.prototype, "speed", void 0);
  34687. __decorate([
  34688. BABYLON.serializeAsMeshReference("lockedTargetId")
  34689. ], TargetCamera.prototype, "lockedTarget", void 0);
  34690. return TargetCamera;
  34691. }(BABYLON.Camera));
  34692. BABYLON.TargetCamera = TargetCamera;
  34693. })(BABYLON || (BABYLON = {}));
  34694. //# sourceMappingURL=babylon.targetCamera.js.map
  34695. var BABYLON;
  34696. (function (BABYLON) {
  34697. var FreeCamera = (function (_super) {
  34698. __extends(FreeCamera, _super);
  34699. function FreeCamera(name, position, scene) {
  34700. var _this = _super.call(this, name, position, scene) || this;
  34701. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  34702. _this.checkCollisions = false;
  34703. _this.applyGravity = false;
  34704. _this._needMoveForGravity = false;
  34705. _this._oldPosition = BABYLON.Vector3.Zero();
  34706. _this._diffPosition = BABYLON.Vector3.Zero();
  34707. _this._newPosition = BABYLON.Vector3.Zero();
  34708. // Collisions
  34709. _this._collisionMask = -1;
  34710. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34711. if (collidedMesh === void 0) { collidedMesh = null; }
  34712. //TODO move this to the collision coordinator!
  34713. if (_this.getScene().workerCollisions)
  34714. newPosition.multiplyInPlace(_this._collider.radius);
  34715. var updatePosition = function (newPos) {
  34716. _this._newPosition.copyFrom(newPos);
  34717. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  34718. var oldPosition = _this.position.clone();
  34719. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  34720. _this.position.addInPlace(_this._diffPosition);
  34721. if (_this.onCollide && collidedMesh) {
  34722. _this.onCollide(collidedMesh);
  34723. }
  34724. }
  34725. };
  34726. updatePosition(newPosition);
  34727. };
  34728. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  34729. _this.inputs.addKeyboard().addMouse();
  34730. return _this;
  34731. }
  34732. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  34733. //-- begin properties for backward compatibility for inputs
  34734. get: function () {
  34735. var mouse = this.inputs.attached["mouse"];
  34736. if (mouse)
  34737. return mouse.angularSensibility;
  34738. },
  34739. set: function (value) {
  34740. var mouse = this.inputs.attached["mouse"];
  34741. if (mouse)
  34742. mouse.angularSensibility = value;
  34743. },
  34744. enumerable: true,
  34745. configurable: true
  34746. });
  34747. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  34748. get: function () {
  34749. var keyboard = this.inputs.attached["keyboard"];
  34750. if (keyboard)
  34751. return keyboard.keysUp;
  34752. },
  34753. set: function (value) {
  34754. var keyboard = this.inputs.attached["keyboard"];
  34755. if (keyboard)
  34756. keyboard.keysUp = value;
  34757. },
  34758. enumerable: true,
  34759. configurable: true
  34760. });
  34761. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  34762. get: function () {
  34763. var keyboard = this.inputs.attached["keyboard"];
  34764. if (keyboard)
  34765. return keyboard.keysDown;
  34766. },
  34767. set: function (value) {
  34768. var keyboard = this.inputs.attached["keyboard"];
  34769. if (keyboard)
  34770. keyboard.keysDown = value;
  34771. },
  34772. enumerable: true,
  34773. configurable: true
  34774. });
  34775. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  34776. get: function () {
  34777. var keyboard = this.inputs.attached["keyboard"];
  34778. if (keyboard)
  34779. return keyboard.keysLeft;
  34780. },
  34781. set: function (value) {
  34782. var keyboard = this.inputs.attached["keyboard"];
  34783. if (keyboard)
  34784. keyboard.keysLeft = value;
  34785. },
  34786. enumerable: true,
  34787. configurable: true
  34788. });
  34789. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  34790. get: function () {
  34791. var keyboard = this.inputs.attached["keyboard"];
  34792. if (keyboard)
  34793. return keyboard.keysRight;
  34794. },
  34795. set: function (value) {
  34796. var keyboard = this.inputs.attached["keyboard"];
  34797. if (keyboard)
  34798. keyboard.keysRight = value;
  34799. },
  34800. enumerable: true,
  34801. configurable: true
  34802. });
  34803. // Controls
  34804. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34805. this.inputs.attachElement(element, noPreventDefault);
  34806. };
  34807. FreeCamera.prototype.detachControl = function (element) {
  34808. this.inputs.detachElement(element);
  34809. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34810. this.cameraRotation = new BABYLON.Vector2(0, 0);
  34811. };
  34812. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  34813. get: function () {
  34814. return this._collisionMask;
  34815. },
  34816. set: function (mask) {
  34817. this._collisionMask = !isNaN(mask) ? mask : -1;
  34818. },
  34819. enumerable: true,
  34820. configurable: true
  34821. });
  34822. FreeCamera.prototype._collideWithWorld = function (displacement) {
  34823. var globalPosition;
  34824. if (this.parent) {
  34825. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  34826. }
  34827. else {
  34828. globalPosition = this.position;
  34829. }
  34830. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  34831. if (!this._collider) {
  34832. this._collider = new BABYLON.Collider();
  34833. }
  34834. this._collider.radius = this.ellipsoid;
  34835. this._collider.collisionMask = this._collisionMask;
  34836. //no need for clone, as long as gravity is not on.
  34837. var actualDisplacement = displacement;
  34838. //add gravity to the direction to prevent the dual-collision checking
  34839. if (this.applyGravity) {
  34840. //this prevents mending with cameraDirection, a global variable of the free camera class.
  34841. actualDisplacement = displacement.add(this.getScene().gravity);
  34842. }
  34843. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34844. };
  34845. FreeCamera.prototype._checkInputs = function () {
  34846. if (!this._localDirection) {
  34847. this._localDirection = BABYLON.Vector3.Zero();
  34848. this._transformedDirection = BABYLON.Vector3.Zero();
  34849. }
  34850. this.inputs.checkInputs();
  34851. _super.prototype._checkInputs.call(this);
  34852. };
  34853. FreeCamera.prototype._decideIfNeedsToMove = function () {
  34854. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34855. };
  34856. FreeCamera.prototype._updatePosition = function () {
  34857. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  34858. this._collideWithWorld(this.cameraDirection);
  34859. }
  34860. else {
  34861. _super.prototype._updatePosition.call(this);
  34862. }
  34863. };
  34864. FreeCamera.prototype.dispose = function () {
  34865. this.inputs.clear();
  34866. _super.prototype.dispose.call(this);
  34867. };
  34868. FreeCamera.prototype.getClassName = function () {
  34869. return "FreeCamera";
  34870. };
  34871. __decorate([
  34872. BABYLON.serializeAsVector3()
  34873. ], FreeCamera.prototype, "ellipsoid", void 0);
  34874. __decorate([
  34875. BABYLON.serialize()
  34876. ], FreeCamera.prototype, "checkCollisions", void 0);
  34877. __decorate([
  34878. BABYLON.serialize()
  34879. ], FreeCamera.prototype, "applyGravity", void 0);
  34880. return FreeCamera;
  34881. }(BABYLON.TargetCamera));
  34882. BABYLON.FreeCamera = FreeCamera;
  34883. })(BABYLON || (BABYLON = {}));
  34884. //# sourceMappingURL=babylon.freeCamera.js.map
  34885. var BABYLON;
  34886. (function (BABYLON) {
  34887. var ArcRotateCameraKeyboardMoveInput = (function () {
  34888. function ArcRotateCameraKeyboardMoveInput() {
  34889. this._keys = [];
  34890. this.keysUp = [38];
  34891. this.keysDown = [40];
  34892. this.keysLeft = [37];
  34893. this.keysRight = [39];
  34894. this.keysReset = [111];
  34895. this.panningSensibility = 50.0;
  34896. }
  34897. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34898. var _this = this;
  34899. if (this._onCanvasBlurObserver) {
  34900. return;
  34901. }
  34902. this._scene = this.camera.getScene();
  34903. this._engine = this._scene.getEngine();
  34904. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  34905. _this._keys = [];
  34906. });
  34907. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  34908. var evt = info.event;
  34909. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  34910. _this._ctrlPressed = evt.ctrlKey;
  34911. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34912. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34913. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34914. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  34915. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  34916. var index = _this._keys.indexOf(evt.keyCode);
  34917. if (index === -1) {
  34918. _this._keys.push(evt.keyCode);
  34919. }
  34920. if (evt.preventDefault) {
  34921. if (!noPreventDefault) {
  34922. evt.preventDefault();
  34923. }
  34924. }
  34925. }
  34926. }
  34927. else {
  34928. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34929. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34930. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34931. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  34932. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  34933. var index = _this._keys.indexOf(evt.keyCode);
  34934. if (index >= 0) {
  34935. _this._keys.splice(index, 1);
  34936. }
  34937. if (evt.preventDefault) {
  34938. if (!noPreventDefault) {
  34939. evt.preventDefault();
  34940. }
  34941. }
  34942. }
  34943. }
  34944. });
  34945. };
  34946. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34947. if (this._scene) {
  34948. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  34949. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  34950. this._onKeyboardObserver = null;
  34951. this._onCanvasBlurObserver = null;
  34952. }
  34953. this._keys = [];
  34954. };
  34955. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34956. if (this._onKeyboardObserver) {
  34957. var camera = this.camera;
  34958. for (var index = 0; index < this._keys.length; index++) {
  34959. var keyCode = this._keys[index];
  34960. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34961. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34962. camera.inertialPanningX -= 1 / this.panningSensibility;
  34963. }
  34964. else {
  34965. camera.inertialAlphaOffset -= 0.01;
  34966. }
  34967. }
  34968. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34969. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34970. camera.inertialPanningY += 1 / this.panningSensibility;
  34971. }
  34972. else {
  34973. camera.inertialBetaOffset -= 0.01;
  34974. }
  34975. }
  34976. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34977. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34978. camera.inertialPanningX += 1 / this.panningSensibility;
  34979. }
  34980. else {
  34981. camera.inertialAlphaOffset += 0.01;
  34982. }
  34983. }
  34984. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34985. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34986. camera.inertialPanningY -= 1 / this.panningSensibility;
  34987. }
  34988. else {
  34989. camera.inertialBetaOffset += 0.01;
  34990. }
  34991. }
  34992. else if (this.keysReset.indexOf(keyCode) !== -1) {
  34993. camera.restoreState();
  34994. }
  34995. }
  34996. }
  34997. };
  34998. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  34999. return "ArcRotateCameraKeyboardMoveInput";
  35000. };
  35001. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  35002. return "keyboard";
  35003. };
  35004. __decorate([
  35005. BABYLON.serialize()
  35006. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  35007. __decorate([
  35008. BABYLON.serialize()
  35009. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  35010. __decorate([
  35011. BABYLON.serialize()
  35012. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  35013. __decorate([
  35014. BABYLON.serialize()
  35015. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  35016. __decorate([
  35017. BABYLON.serialize()
  35018. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  35019. __decorate([
  35020. BABYLON.serialize()
  35021. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  35022. return ArcRotateCameraKeyboardMoveInput;
  35023. }());
  35024. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  35025. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  35026. })(BABYLON || (BABYLON = {}));
  35027. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  35028. var BABYLON;
  35029. (function (BABYLON) {
  35030. var ArcRotateCameraMouseWheelInput = (function () {
  35031. function ArcRotateCameraMouseWheelInput() {
  35032. this.wheelPrecision = 3.0;
  35033. }
  35034. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  35035. var _this = this;
  35036. this._wheel = function (p, s) {
  35037. //sanity check - this should be a PointerWheel event.
  35038. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  35039. return;
  35040. var event = p.event;
  35041. var delta = 0;
  35042. if (event.wheelDelta) {
  35043. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  35044. }
  35045. else if (event.detail) {
  35046. delta = -event.detail / _this.wheelPrecision;
  35047. }
  35048. if (delta)
  35049. _this.camera.inertialRadiusOffset += delta;
  35050. if (event.preventDefault) {
  35051. if (!noPreventDefault) {
  35052. event.preventDefault();
  35053. }
  35054. }
  35055. };
  35056. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  35057. };
  35058. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  35059. if (this._observer && element) {
  35060. this.camera.getScene().onPointerObservable.remove(this._observer);
  35061. this._observer = null;
  35062. this._wheel = null;
  35063. }
  35064. };
  35065. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  35066. return "ArcRotateCameraMouseWheelInput";
  35067. };
  35068. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  35069. return "mousewheel";
  35070. };
  35071. __decorate([
  35072. BABYLON.serialize()
  35073. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  35074. return ArcRotateCameraMouseWheelInput;
  35075. }());
  35076. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  35077. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  35078. })(BABYLON || (BABYLON = {}));
  35079. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  35080. var BABYLON;
  35081. (function (BABYLON) {
  35082. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  35083. var ArcRotateCameraPointersInput = (function () {
  35084. function ArcRotateCameraPointersInput() {
  35085. this.buttons = [0, 1, 2];
  35086. this.angularSensibilityX = 1000.0;
  35087. this.angularSensibilityY = 1000.0;
  35088. this.pinchPrecision = 6.0;
  35089. this.panningSensibility = 50.0;
  35090. this.multiTouchPanning = true;
  35091. this._isPanClick = false;
  35092. this.pinchInwards = true;
  35093. }
  35094. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  35095. var _this = this;
  35096. var engine = this.camera.getEngine();
  35097. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  35098. var pointA, pointB;
  35099. var previousPinchSquaredDistance = 0;
  35100. var previousPinchDistance = 0;
  35101. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false };
  35102. this._pointerInput = function (p, s) {
  35103. var evt = p.event;
  35104. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35105. return;
  35106. }
  35107. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35108. try {
  35109. evt.srcElement.setPointerCapture(evt.pointerId);
  35110. }
  35111. catch (e) {
  35112. //Nothing to do with the error. Execution will continue.
  35113. }
  35114. // Manage panning with pan button click
  35115. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  35116. // manage pointers
  35117. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  35118. if (pointA === undefined) {
  35119. pointA = cacheSoloPointer;
  35120. }
  35121. else if (pointB === undefined) {
  35122. pointB = cacheSoloPointer;
  35123. }
  35124. if (!noPreventDefault) {
  35125. evt.preventDefault();
  35126. element.focus();
  35127. }
  35128. }
  35129. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  35130. _this.camera.restoreState();
  35131. }
  35132. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35133. try {
  35134. evt.srcElement.releasePointerCapture(evt.pointerId);
  35135. }
  35136. catch (e) {
  35137. //Nothing to do with the error.
  35138. }
  35139. cacheSoloPointer = null;
  35140. previousPinchSquaredDistance = 0;
  35141. previousPinchDistance = 0;
  35142. previousMultiTouchPanPosition.isPaning = false;
  35143. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  35144. //but emptying completly pointers collection is required to fix a bug on iPhone :
  35145. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  35146. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  35147. pointA = pointB = undefined;
  35148. if (!noPreventDefault) {
  35149. evt.preventDefault();
  35150. }
  35151. }
  35152. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35153. if (!noPreventDefault) {
  35154. evt.preventDefault();
  35155. }
  35156. // One button down
  35157. if (pointA && pointB === undefined) {
  35158. if (_this.panningSensibility !== 0 &&
  35159. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  35160. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  35161. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  35162. }
  35163. else {
  35164. var offsetX = evt.clientX - cacheSoloPointer.x;
  35165. var offsetY = evt.clientY - cacheSoloPointer.y;
  35166. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35167. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35168. }
  35169. cacheSoloPointer.x = evt.clientX;
  35170. cacheSoloPointer.y = evt.clientY;
  35171. }
  35172. else if (pointA && pointB) {
  35173. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  35174. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  35175. ed.x = evt.clientX;
  35176. ed.y = evt.clientY;
  35177. var direction = _this.pinchInwards ? 1 : -1;
  35178. var distX = pointA.x - pointB.x;
  35179. var distY = pointA.y - pointB.y;
  35180. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  35181. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  35182. if (previousPinchSquaredDistance === 0) {
  35183. previousPinchSquaredDistance = pinchSquaredDistance;
  35184. previousPinchDistance = pinchDistance;
  35185. return;
  35186. }
  35187. if (Math.abs(pinchDistance - previousPinchDistance) > _this.camera.pinchToPanMaxDistance) {
  35188. _this.camera
  35189. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  35190. (_this.pinchPrecision *
  35191. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  35192. direction);
  35193. previousMultiTouchPanPosition.isPaning = false;
  35194. }
  35195. else {
  35196. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  35197. if (!previousMultiTouchPanPosition.isPaning) {
  35198. previousMultiTouchPanPosition.isPaning = true;
  35199. previousMultiTouchPanPosition.x = ed.x;
  35200. previousMultiTouchPanPosition.y = ed.y;
  35201. return;
  35202. }
  35203. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / _this.panningSensibility;
  35204. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / _this.panningSensibility;
  35205. }
  35206. }
  35207. if (cacheSoloPointer.pointerId === evt.pointerId) {
  35208. previousMultiTouchPanPosition.x = ed.x;
  35209. previousMultiTouchPanPosition.y = ed.y;
  35210. }
  35211. previousPinchSquaredDistance = pinchSquaredDistance;
  35212. previousPinchDistance = pinchDistance;
  35213. }
  35214. }
  35215. };
  35216. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  35217. this._onContextMenu = function (evt) {
  35218. evt.preventDefault();
  35219. };
  35220. if (!this.camera._useCtrlForPanning) {
  35221. element.addEventListener("contextmenu", this._onContextMenu, false);
  35222. }
  35223. this._onLostFocus = function () {
  35224. //this._keys = [];
  35225. pointA = pointB = undefined;
  35226. previousPinchSquaredDistance = 0;
  35227. previousPinchDistance = 0;
  35228. previousMultiTouchPanPosition.isPaning = false;
  35229. cacheSoloPointer = null;
  35230. };
  35231. this._onMouseMove = function (evt) {
  35232. if (!engine.isPointerLock) {
  35233. return;
  35234. }
  35235. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  35236. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  35237. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35238. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35239. if (!noPreventDefault) {
  35240. evt.preventDefault();
  35241. }
  35242. };
  35243. this._onGestureStart = function (e) {
  35244. if (window.MSGesture === undefined) {
  35245. return;
  35246. }
  35247. if (!_this._MSGestureHandler) {
  35248. _this._MSGestureHandler = new MSGesture();
  35249. _this._MSGestureHandler.target = element;
  35250. }
  35251. _this._MSGestureHandler.addPointer(e.pointerId);
  35252. };
  35253. this._onGesture = function (e) {
  35254. _this.camera.radius *= e.scale;
  35255. if (e.preventDefault) {
  35256. if (!noPreventDefault) {
  35257. e.stopPropagation();
  35258. e.preventDefault();
  35259. }
  35260. }
  35261. };
  35262. element.addEventListener("mousemove", this._onMouseMove, false);
  35263. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  35264. element.addEventListener("MSGestureChange", this._onGesture, false);
  35265. BABYLON.Tools.RegisterTopRootEvents([
  35266. { name: "blur", handler: this._onLostFocus }
  35267. ]);
  35268. };
  35269. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  35270. BABYLON.Tools.UnregisterTopRootEvents([
  35271. { name: "blur", handler: this._onLostFocus }
  35272. ]);
  35273. if (element && this._observer) {
  35274. this.camera.getScene().onPointerObservable.remove(this._observer);
  35275. this._observer = null;
  35276. element.removeEventListener("contextmenu", this._onContextMenu);
  35277. element.removeEventListener("mousemove", this._onMouseMove);
  35278. element.removeEventListener("MSPointerDown", this._onGestureStart);
  35279. element.removeEventListener("MSGestureChange", this._onGesture);
  35280. this._isPanClick = false;
  35281. this.pinchInwards = true;
  35282. this._onMouseMove = null;
  35283. this._onGestureStart = null;
  35284. this._onGesture = null;
  35285. this._MSGestureHandler = null;
  35286. this._onLostFocus = null;
  35287. this._onContextMenu = null;
  35288. }
  35289. };
  35290. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  35291. return "ArcRotateCameraPointersInput";
  35292. };
  35293. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  35294. return "pointers";
  35295. };
  35296. __decorate([
  35297. BABYLON.serialize()
  35298. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  35299. __decorate([
  35300. BABYLON.serialize()
  35301. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  35302. __decorate([
  35303. BABYLON.serialize()
  35304. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  35305. __decorate([
  35306. BABYLON.serialize()
  35307. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  35308. __decorate([
  35309. BABYLON.serialize()
  35310. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  35311. __decorate([
  35312. BABYLON.serialize()
  35313. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  35314. return ArcRotateCameraPointersInput;
  35315. }());
  35316. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  35317. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  35318. })(BABYLON || (BABYLON = {}));
  35319. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  35320. /// <reference path="babylon.targetCamera.ts" />
  35321. /// <reference path="..\Tools\babylon.tools.ts" />
  35322. var BABYLON;
  35323. (function (BABYLON) {
  35324. var ArcRotateCamera = (function (_super) {
  35325. __extends(ArcRotateCamera, _super);
  35326. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  35327. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  35328. _this.inertialAlphaOffset = 0;
  35329. _this.inertialBetaOffset = 0;
  35330. _this.inertialRadiusOffset = 0;
  35331. _this.lowerAlphaLimit = null;
  35332. _this.upperAlphaLimit = null;
  35333. _this.lowerBetaLimit = 0.01;
  35334. _this.upperBetaLimit = Math.PI;
  35335. _this.lowerRadiusLimit = null;
  35336. _this.upperRadiusLimit = null;
  35337. _this.inertialPanningX = 0;
  35338. _this.inertialPanningY = 0;
  35339. _this.pinchToPanMaxDistance = 2;
  35340. _this.panningDistanceLimit = null;
  35341. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  35342. _this.panningInertia = 0.9;
  35343. //-- end properties for backward compatibility for inputs
  35344. _this.zoomOnFactor = 1;
  35345. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  35346. _this.allowUpsideDown = true;
  35347. _this._viewMatrix = new BABYLON.Matrix();
  35348. // Panning
  35349. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  35350. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  35351. _this.checkCollisions = false;
  35352. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35353. _this._previousPosition = BABYLON.Vector3.Zero();
  35354. _this._collisionVelocity = BABYLON.Vector3.Zero();
  35355. _this._newPosition = BABYLON.Vector3.Zero();
  35356. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  35357. if (collidedMesh === void 0) { collidedMesh = null; }
  35358. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  35359. newPosition.multiplyInPlace(_this._collider.radius);
  35360. }
  35361. if (!collidedMesh) {
  35362. _this._previousPosition.copyFrom(_this.position);
  35363. }
  35364. else {
  35365. _this.setPosition(newPosition);
  35366. if (_this.onCollide) {
  35367. _this.onCollide(collidedMesh);
  35368. }
  35369. }
  35370. // Recompute because of constraints
  35371. var cosa = Math.cos(_this.alpha);
  35372. var sina = Math.sin(_this.alpha);
  35373. var cosb = Math.cos(_this.beta);
  35374. var sinb = Math.sin(_this.beta);
  35375. if (sinb === 0) {
  35376. sinb = 0.0001;
  35377. }
  35378. var target = _this._getTargetPosition();
  35379. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  35380. _this.position.copyFrom(_this._newPosition);
  35381. var up = _this.upVector;
  35382. if (_this.allowUpsideDown && _this.beta < 0) {
  35383. up = up.clone();
  35384. up = up.negate();
  35385. }
  35386. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  35387. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  35388. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  35389. _this._collisionTriggered = false;
  35390. };
  35391. _this._target = BABYLON.Vector3.Zero();
  35392. if (target) {
  35393. _this.setTarget(target);
  35394. }
  35395. _this.alpha = alpha;
  35396. _this.beta = beta;
  35397. _this.radius = radius;
  35398. _this.getViewMatrix();
  35399. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  35400. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  35401. return _this;
  35402. }
  35403. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  35404. get: function () {
  35405. return this._target;
  35406. },
  35407. set: function (value) {
  35408. this.setTarget(value);
  35409. },
  35410. enumerable: true,
  35411. configurable: true
  35412. });
  35413. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  35414. //-- begin properties for backward compatibility for inputs
  35415. get: function () {
  35416. var pointers = this.inputs.attached["pointers"];
  35417. if (pointers)
  35418. return pointers.angularSensibilityX;
  35419. },
  35420. set: function (value) {
  35421. var pointers = this.inputs.attached["pointers"];
  35422. if (pointers) {
  35423. pointers.angularSensibilityX = value;
  35424. }
  35425. },
  35426. enumerable: true,
  35427. configurable: true
  35428. });
  35429. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35430. get: function () {
  35431. var pointers = this.inputs.attached["pointers"];
  35432. if (pointers)
  35433. return pointers.angularSensibilityY;
  35434. },
  35435. set: function (value) {
  35436. var pointers = this.inputs.attached["pointers"];
  35437. if (pointers) {
  35438. pointers.angularSensibilityY = value;
  35439. }
  35440. },
  35441. enumerable: true,
  35442. configurable: true
  35443. });
  35444. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35445. get: function () {
  35446. var pointers = this.inputs.attached["pointers"];
  35447. if (pointers)
  35448. return pointers.pinchPrecision;
  35449. },
  35450. set: function (value) {
  35451. var pointers = this.inputs.attached["pointers"];
  35452. if (pointers) {
  35453. pointers.pinchPrecision = value;
  35454. }
  35455. },
  35456. enumerable: true,
  35457. configurable: true
  35458. });
  35459. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35460. get: function () {
  35461. var pointers = this.inputs.attached["pointers"];
  35462. if (pointers)
  35463. return pointers.panningSensibility;
  35464. },
  35465. set: function (value) {
  35466. var pointers = this.inputs.attached["pointers"];
  35467. if (pointers) {
  35468. pointers.panningSensibility = value;
  35469. }
  35470. },
  35471. enumerable: true,
  35472. configurable: true
  35473. });
  35474. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35475. get: function () {
  35476. var keyboard = this.inputs.attached["keyboard"];
  35477. if (keyboard)
  35478. return keyboard.keysUp;
  35479. },
  35480. set: function (value) {
  35481. var keyboard = this.inputs.attached["keyboard"];
  35482. if (keyboard)
  35483. keyboard.keysUp = value;
  35484. },
  35485. enumerable: true,
  35486. configurable: true
  35487. });
  35488. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35489. get: function () {
  35490. var keyboard = this.inputs.attached["keyboard"];
  35491. if (keyboard)
  35492. return keyboard.keysDown;
  35493. },
  35494. set: function (value) {
  35495. var keyboard = this.inputs.attached["keyboard"];
  35496. if (keyboard)
  35497. keyboard.keysDown = value;
  35498. },
  35499. enumerable: true,
  35500. configurable: true
  35501. });
  35502. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35503. get: function () {
  35504. var keyboard = this.inputs.attached["keyboard"];
  35505. if (keyboard)
  35506. return keyboard.keysLeft;
  35507. },
  35508. set: function (value) {
  35509. var keyboard = this.inputs.attached["keyboard"];
  35510. if (keyboard)
  35511. keyboard.keysLeft = value;
  35512. },
  35513. enumerable: true,
  35514. configurable: true
  35515. });
  35516. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35517. get: function () {
  35518. var keyboard = this.inputs.attached["keyboard"];
  35519. if (keyboard)
  35520. return keyboard.keysRight;
  35521. },
  35522. set: function (value) {
  35523. var keyboard = this.inputs.attached["keyboard"];
  35524. if (keyboard)
  35525. keyboard.keysRight = value;
  35526. },
  35527. enumerable: true,
  35528. configurable: true
  35529. });
  35530. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35531. get: function () {
  35532. var mousewheel = this.inputs.attached["mousewheel"];
  35533. if (mousewheel)
  35534. return mousewheel.wheelPrecision;
  35535. },
  35536. set: function (value) {
  35537. var mousewheel = this.inputs.attached["mousewheel"];
  35538. if (mousewheel)
  35539. mousewheel.wheelPrecision = value;
  35540. },
  35541. enumerable: true,
  35542. configurable: true
  35543. });
  35544. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35545. get: function () {
  35546. return this._bouncingBehavior;
  35547. },
  35548. enumerable: true,
  35549. configurable: true
  35550. });
  35551. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35552. get: function () {
  35553. return this._bouncingBehavior != null;
  35554. },
  35555. set: function (value) {
  35556. if (value === this.useBouncingBehavior) {
  35557. return;
  35558. }
  35559. if (value) {
  35560. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35561. this.addBehavior(this._bouncingBehavior);
  35562. }
  35563. else {
  35564. this.removeBehavior(this._bouncingBehavior);
  35565. this._bouncingBehavior = null;
  35566. }
  35567. },
  35568. enumerable: true,
  35569. configurable: true
  35570. });
  35571. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35572. get: function () {
  35573. return this._framingBehavior;
  35574. },
  35575. enumerable: true,
  35576. configurable: true
  35577. });
  35578. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35579. get: function () {
  35580. return this._framingBehavior != null;
  35581. },
  35582. set: function (value) {
  35583. if (value === this.useFramingBehavior) {
  35584. return;
  35585. }
  35586. if (value) {
  35587. this._framingBehavior = new BABYLON.FramingBehavior();
  35588. this.addBehavior(this._framingBehavior);
  35589. }
  35590. else {
  35591. this.removeBehavior(this._framingBehavior);
  35592. this._framingBehavior = null;
  35593. }
  35594. },
  35595. enumerable: true,
  35596. configurable: true
  35597. });
  35598. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  35599. get: function () {
  35600. return this._autoRotationBehavior;
  35601. },
  35602. enumerable: true,
  35603. configurable: true
  35604. });
  35605. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  35606. get: function () {
  35607. return this._autoRotationBehavior != null;
  35608. },
  35609. set: function (value) {
  35610. if (value === this.useAutoRotationBehavior) {
  35611. return;
  35612. }
  35613. if (value) {
  35614. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  35615. this.addBehavior(this._autoRotationBehavior);
  35616. }
  35617. else {
  35618. this.removeBehavior(this._autoRotationBehavior);
  35619. this._autoRotationBehavior = null;
  35620. }
  35621. },
  35622. enumerable: true,
  35623. configurable: true
  35624. });
  35625. // Cache
  35626. ArcRotateCamera.prototype._initCache = function () {
  35627. _super.prototype._initCache.call(this);
  35628. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  35629. this._cache.alpha = undefined;
  35630. this._cache.beta = undefined;
  35631. this._cache.radius = undefined;
  35632. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  35633. };
  35634. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  35635. if (!ignoreParentClass) {
  35636. _super.prototype._updateCache.call(this);
  35637. }
  35638. this._cache._target.copyFrom(this._getTargetPosition());
  35639. this._cache.alpha = this.alpha;
  35640. this._cache.beta = this.beta;
  35641. this._cache.radius = this.radius;
  35642. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  35643. };
  35644. ArcRotateCamera.prototype._getTargetPosition = function () {
  35645. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  35646. var pos = this._targetHost.getAbsolutePosition();
  35647. if (this._targetBoundingCenter) {
  35648. pos.addToRef(this._targetBoundingCenter, this._target);
  35649. }
  35650. else {
  35651. this._target.copyFrom(pos);
  35652. }
  35653. }
  35654. var lockedTargetPosition = this._getLockedTargetPosition();
  35655. if (lockedTargetPosition) {
  35656. return lockedTargetPosition;
  35657. }
  35658. return this._target;
  35659. };
  35660. ArcRotateCamera.prototype.storeState = function () {
  35661. this._storedAlpha = this.alpha;
  35662. this._storedBeta = this.beta;
  35663. this._storedRadius = this.radius;
  35664. this._storedTarget = this._getTargetPosition().clone();
  35665. return _super.prototype.storeState.call(this);
  35666. };
  35667. /**
  35668. * Restored camera state. You must call storeState() first
  35669. */
  35670. ArcRotateCamera.prototype._restoreStateValues = function () {
  35671. if (!_super.prototype._restoreStateValues.call(this)) {
  35672. return false;
  35673. }
  35674. this.alpha = this._storedAlpha;
  35675. this.beta = this._storedBeta;
  35676. this.radius = this._storedRadius;
  35677. this.setTarget(this._storedTarget);
  35678. this.inertialAlphaOffset = 0;
  35679. this.inertialBetaOffset = 0;
  35680. this.inertialRadiusOffset = 0;
  35681. this.inertialPanningX = 0;
  35682. this.inertialPanningY = 0;
  35683. return true;
  35684. };
  35685. // Synchronized
  35686. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  35687. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  35688. return false;
  35689. return this._cache._target.equals(this._getTargetPosition())
  35690. && this._cache.alpha === this.alpha
  35691. && this._cache.beta === this.beta
  35692. && this._cache.radius === this.radius
  35693. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  35694. };
  35695. // Methods
  35696. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  35697. var _this = this;
  35698. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  35699. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  35700. this._useCtrlForPanning = useCtrlForPanning;
  35701. this._panningMouseButton = panningMouseButton;
  35702. this.inputs.attachElement(element, noPreventDefault);
  35703. this._reset = function () {
  35704. _this.inertialAlphaOffset = 0;
  35705. _this.inertialBetaOffset = 0;
  35706. _this.inertialRadiusOffset = 0;
  35707. _this.inertialPanningX = 0;
  35708. _this.inertialPanningY = 0;
  35709. };
  35710. };
  35711. ArcRotateCamera.prototype.detachControl = function (element) {
  35712. this.inputs.detachElement(element);
  35713. if (this._reset) {
  35714. this._reset();
  35715. }
  35716. };
  35717. ArcRotateCamera.prototype._checkInputs = function () {
  35718. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  35719. if (this._collisionTriggered) {
  35720. return;
  35721. }
  35722. this.inputs.checkInputs();
  35723. // Inertia
  35724. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  35725. if (this.getScene().useRightHandedSystem) {
  35726. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35727. }
  35728. else {
  35729. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35730. }
  35731. this.beta += this.inertialBetaOffset;
  35732. this.radius -= this.inertialRadiusOffset;
  35733. this.inertialAlphaOffset *= this.inertia;
  35734. this.inertialBetaOffset *= this.inertia;
  35735. this.inertialRadiusOffset *= this.inertia;
  35736. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  35737. this.inertialAlphaOffset = 0;
  35738. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  35739. this.inertialBetaOffset = 0;
  35740. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  35741. this.inertialRadiusOffset = 0;
  35742. }
  35743. // Panning inertia
  35744. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  35745. if (!this._localDirection) {
  35746. this._localDirection = BABYLON.Vector3.Zero();
  35747. this._transformedDirection = BABYLON.Vector3.Zero();
  35748. }
  35749. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  35750. this._localDirection.multiplyInPlace(this.panningAxis);
  35751. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  35752. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  35753. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  35754. if (!this.panningAxis.y) {
  35755. this._transformedDirection.y = 0;
  35756. }
  35757. if (!this._targetHost) {
  35758. if (this.panningDistanceLimit) {
  35759. this._transformedDirection.addInPlace(this._target);
  35760. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  35761. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  35762. this._target.copyFrom(this._transformedDirection);
  35763. }
  35764. }
  35765. else {
  35766. this._target.addInPlace(this._transformedDirection);
  35767. }
  35768. }
  35769. this.inertialPanningX *= this.panningInertia;
  35770. this.inertialPanningY *= this.panningInertia;
  35771. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  35772. this.inertialPanningX = 0;
  35773. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  35774. this.inertialPanningY = 0;
  35775. }
  35776. // Limits
  35777. this._checkLimits();
  35778. _super.prototype._checkInputs.call(this);
  35779. };
  35780. ArcRotateCamera.prototype._checkLimits = function () {
  35781. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  35782. if (this.allowUpsideDown && this.beta > Math.PI) {
  35783. this.beta = this.beta - (2 * Math.PI);
  35784. }
  35785. }
  35786. else {
  35787. if (this.beta < this.lowerBetaLimit) {
  35788. this.beta = this.lowerBetaLimit;
  35789. }
  35790. }
  35791. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  35792. if (this.allowUpsideDown && this.beta < -Math.PI) {
  35793. this.beta = this.beta + (2 * Math.PI);
  35794. }
  35795. }
  35796. else {
  35797. if (this.beta > this.upperBetaLimit) {
  35798. this.beta = this.upperBetaLimit;
  35799. }
  35800. }
  35801. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  35802. this.alpha = this.lowerAlphaLimit;
  35803. }
  35804. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  35805. this.alpha = this.upperAlphaLimit;
  35806. }
  35807. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  35808. this.radius = this.lowerRadiusLimit;
  35809. }
  35810. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  35811. this.radius = this.upperRadiusLimit;
  35812. }
  35813. };
  35814. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  35815. var radiusv3 = this.position.subtract(this._getTargetPosition());
  35816. this.radius = radiusv3.length();
  35817. if (this.radius === 0) {
  35818. this.radius = 0.0001; // Just to avoid division by zero
  35819. }
  35820. // Alpha
  35821. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  35822. if (radiusv3.z < 0) {
  35823. this.alpha = 2 * Math.PI - this.alpha;
  35824. }
  35825. // Beta
  35826. this.beta = Math.acos(radiusv3.y / this.radius);
  35827. this._checkLimits();
  35828. };
  35829. ArcRotateCamera.prototype.setPosition = function (position) {
  35830. if (this.position.equals(position)) {
  35831. return;
  35832. }
  35833. this.position.copyFrom(position);
  35834. this.rebuildAnglesAndRadius();
  35835. };
  35836. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  35837. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  35838. if (allowSamePosition === void 0) { allowSamePosition = false; }
  35839. if (target.getBoundingInfo) {
  35840. if (toBoundingCenter) {
  35841. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  35842. }
  35843. else {
  35844. this._targetBoundingCenter = null;
  35845. }
  35846. this._targetHost = target;
  35847. this._target = this._getTargetPosition();
  35848. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  35849. }
  35850. else {
  35851. var newTarget = target;
  35852. var currentTarget = this._getTargetPosition();
  35853. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  35854. return;
  35855. }
  35856. this._targetHost = null;
  35857. this._target = newTarget;
  35858. this._targetBoundingCenter = null;
  35859. this.onMeshTargetChangedObservable.notifyObservers(null);
  35860. }
  35861. this.rebuildAnglesAndRadius();
  35862. };
  35863. ArcRotateCamera.prototype._getViewMatrix = function () {
  35864. // Compute
  35865. var cosa = Math.cos(this.alpha);
  35866. var sina = Math.sin(this.alpha);
  35867. var cosb = Math.cos(this.beta);
  35868. var sinb = Math.sin(this.beta);
  35869. if (sinb === 0) {
  35870. sinb = 0.0001;
  35871. }
  35872. var target = this._getTargetPosition();
  35873. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  35874. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  35875. if (!this._collider) {
  35876. this._collider = new BABYLON.Collider();
  35877. }
  35878. this._collider.radius = this.collisionRadius;
  35879. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  35880. this._collisionTriggered = true;
  35881. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  35882. }
  35883. else {
  35884. this.position.copyFrom(this._newPosition);
  35885. var up = this.upVector;
  35886. if (this.allowUpsideDown && sinb < 0) {
  35887. up = up.clone();
  35888. up = up.negate();
  35889. }
  35890. if (this.getScene().useRightHandedSystem) {
  35891. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  35892. }
  35893. else {
  35894. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  35895. }
  35896. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  35897. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  35898. }
  35899. this._currentTarget = target;
  35900. return this._viewMatrix;
  35901. };
  35902. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  35903. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35904. meshes = meshes || this.getScene().meshes;
  35905. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  35906. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  35907. this.radius = distance * this.zoomOnFactor;
  35908. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  35909. };
  35910. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  35911. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35912. var meshesOrMinMaxVector;
  35913. var distance;
  35914. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  35915. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  35916. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  35917. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  35918. }
  35919. else {
  35920. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  35921. distance = meshesOrMinMaxVectorAndDistance.distance;
  35922. }
  35923. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  35924. if (!doNotUpdateMaxZ) {
  35925. this.maxZ = distance * 2;
  35926. }
  35927. };
  35928. /**
  35929. * @override
  35930. * Override Camera.createRigCamera
  35931. */
  35932. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  35933. var alphaShift;
  35934. switch (this.cameraRigMode) {
  35935. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35936. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35937. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35938. case BABYLON.Camera.RIG_MODE_VR:
  35939. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  35940. break;
  35941. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35942. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  35943. break;
  35944. }
  35945. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  35946. rigCam._cameraRigParams = {};
  35947. return rigCam;
  35948. };
  35949. /**
  35950. * @override
  35951. * Override Camera._updateRigCameras
  35952. */
  35953. ArcRotateCamera.prototype._updateRigCameras = function () {
  35954. var camLeft = this._rigCameras[0];
  35955. var camRight = this._rigCameras[1];
  35956. camLeft.beta = camRight.beta = this.beta;
  35957. camLeft.radius = camRight.radius = this.radius;
  35958. switch (this.cameraRigMode) {
  35959. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35960. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35961. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35962. case BABYLON.Camera.RIG_MODE_VR:
  35963. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35964. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35965. break;
  35966. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35967. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35968. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35969. break;
  35970. }
  35971. _super.prototype._updateRigCameras.call(this);
  35972. };
  35973. ArcRotateCamera.prototype.dispose = function () {
  35974. this.inputs.clear();
  35975. _super.prototype.dispose.call(this);
  35976. };
  35977. ArcRotateCamera.prototype.getClassName = function () {
  35978. return "ArcRotateCamera";
  35979. };
  35980. __decorate([
  35981. BABYLON.serialize()
  35982. ], ArcRotateCamera.prototype, "alpha", void 0);
  35983. __decorate([
  35984. BABYLON.serialize()
  35985. ], ArcRotateCamera.prototype, "beta", void 0);
  35986. __decorate([
  35987. BABYLON.serialize()
  35988. ], ArcRotateCamera.prototype, "radius", void 0);
  35989. __decorate([
  35990. BABYLON.serializeAsVector3("target")
  35991. ], ArcRotateCamera.prototype, "_target", void 0);
  35992. __decorate([
  35993. BABYLON.serialize()
  35994. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  35995. __decorate([
  35996. BABYLON.serialize()
  35997. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  35998. __decorate([
  35999. BABYLON.serialize()
  36000. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  36001. __decorate([
  36002. BABYLON.serialize()
  36003. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  36004. __decorate([
  36005. BABYLON.serialize()
  36006. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  36007. __decorate([
  36008. BABYLON.serialize()
  36009. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  36010. __decorate([
  36011. BABYLON.serialize()
  36012. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  36013. __decorate([
  36014. BABYLON.serialize()
  36015. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  36016. __decorate([
  36017. BABYLON.serialize()
  36018. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  36019. __decorate([
  36020. BABYLON.serialize()
  36021. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  36022. __decorate([
  36023. BABYLON.serialize()
  36024. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  36025. __decorate([
  36026. BABYLON.serialize()
  36027. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  36028. __decorate([
  36029. BABYLON.serialize()
  36030. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  36031. __decorate([
  36032. BABYLON.serializeAsVector3()
  36033. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  36034. __decorate([
  36035. BABYLON.serialize()
  36036. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  36037. __decorate([
  36038. BABYLON.serialize()
  36039. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  36040. __decorate([
  36041. BABYLON.serialize()
  36042. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  36043. return ArcRotateCamera;
  36044. }(BABYLON.TargetCamera));
  36045. BABYLON.ArcRotateCamera = ArcRotateCamera;
  36046. })(BABYLON || (BABYLON = {}));
  36047. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  36048. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  36049. var BABYLON;
  36050. (function (BABYLON) {
  36051. var ArcRotateCameraInputsManager = (function (_super) {
  36052. __extends(ArcRotateCameraInputsManager, _super);
  36053. function ArcRotateCameraInputsManager(camera) {
  36054. return _super.call(this, camera) || this;
  36055. }
  36056. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  36057. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  36058. return this;
  36059. };
  36060. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  36061. this.add(new BABYLON.ArcRotateCameraPointersInput());
  36062. return this;
  36063. };
  36064. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  36065. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  36066. return this;
  36067. };
  36068. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  36069. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  36070. return this;
  36071. };
  36072. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  36073. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  36074. return this;
  36075. };
  36076. return ArcRotateCameraInputsManager;
  36077. }(BABYLON.CameraInputsManager));
  36078. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  36079. })(BABYLON || (BABYLON = {}));
  36080. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  36081. var BABYLON;
  36082. (function (BABYLON) {
  36083. var HemisphericLight = (function (_super) {
  36084. __extends(HemisphericLight, _super);
  36085. /**
  36086. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  36087. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  36088. * The HemisphericLight can't cast shadows.
  36089. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36090. */
  36091. function HemisphericLight(name, direction, scene) {
  36092. var _this = _super.call(this, name, scene) || this;
  36093. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  36094. _this.direction = direction || BABYLON.Vector3.Up();
  36095. return _this;
  36096. }
  36097. HemisphericLight.prototype._buildUniformLayout = function () {
  36098. this._uniformBuffer.addUniform("vLightData", 4);
  36099. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36100. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36101. this._uniformBuffer.addUniform("vLightGround", 3);
  36102. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36103. this._uniformBuffer.addUniform("depthValues", 2);
  36104. this._uniformBuffer.create();
  36105. };
  36106. /**
  36107. * Returns the string "HemisphericLight".
  36108. */
  36109. HemisphericLight.prototype.getClassName = function () {
  36110. return "HemisphericLight";
  36111. };
  36112. /**
  36113. * Sets the HemisphericLight direction towards the passed target (Vector3).
  36114. * Returns the updated direction.
  36115. */
  36116. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  36117. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  36118. return this.direction;
  36119. };
  36120. HemisphericLight.prototype.getShadowGenerator = function () {
  36121. return null;
  36122. };
  36123. /**
  36124. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  36125. * Returns the HemisphericLight.
  36126. */
  36127. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  36128. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36129. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  36130. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  36131. return this;
  36132. };
  36133. HemisphericLight.prototype._getWorldMatrix = function () {
  36134. if (!this._worldMatrix) {
  36135. this._worldMatrix = BABYLON.Matrix.Identity();
  36136. }
  36137. return this._worldMatrix;
  36138. };
  36139. /**
  36140. * Returns the integer 3.
  36141. */
  36142. HemisphericLight.prototype.getTypeID = function () {
  36143. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  36144. };
  36145. __decorate([
  36146. BABYLON.serializeAsColor3()
  36147. ], HemisphericLight.prototype, "groundColor", void 0);
  36148. __decorate([
  36149. BABYLON.serializeAsVector3()
  36150. ], HemisphericLight.prototype, "direction", void 0);
  36151. return HemisphericLight;
  36152. }(BABYLON.Light));
  36153. BABYLON.HemisphericLight = HemisphericLight;
  36154. })(BABYLON || (BABYLON = {}));
  36155. //# sourceMappingURL=babylon.hemisphericLight.js.map
  36156. var BABYLON;
  36157. (function (BABYLON) {
  36158. var ShadowLight = (function (_super) {
  36159. __extends(ShadowLight, _super);
  36160. function ShadowLight() {
  36161. var _this = _super !== null && _super.apply(this, arguments) || this;
  36162. _this._needProjectionMatrixCompute = true;
  36163. return _this;
  36164. }
  36165. Object.defineProperty(ShadowLight.prototype, "direction", {
  36166. get: function () {
  36167. return this._direction;
  36168. },
  36169. set: function (value) {
  36170. this._direction = value;
  36171. },
  36172. enumerable: true,
  36173. configurable: true
  36174. });
  36175. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36176. get: function () {
  36177. return this._shadowMinZ;
  36178. },
  36179. set: function (value) {
  36180. this._shadowMinZ = value;
  36181. this.forceProjectionMatrixCompute();
  36182. },
  36183. enumerable: true,
  36184. configurable: true
  36185. });
  36186. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36187. get: function () {
  36188. return this._shadowMaxZ;
  36189. },
  36190. set: function (value) {
  36191. this._shadowMaxZ = value;
  36192. this.forceProjectionMatrixCompute();
  36193. },
  36194. enumerable: true,
  36195. configurable: true
  36196. });
  36197. /**
  36198. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36199. */
  36200. ShadowLight.prototype.computeTransformedInformation = function () {
  36201. if (this.parent && this.parent.getWorldMatrix) {
  36202. if (!this.transformedPosition) {
  36203. this.transformedPosition = BABYLON.Vector3.Zero();
  36204. }
  36205. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36206. // In case the direction is present.
  36207. if (this.direction) {
  36208. if (!this.transformedDirection) {
  36209. this.transformedDirection = BABYLON.Vector3.Zero();
  36210. }
  36211. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36212. }
  36213. return true;
  36214. }
  36215. return false;
  36216. };
  36217. /**
  36218. * Return the depth scale used for the shadow map.
  36219. */
  36220. ShadowLight.prototype.getDepthScale = function () {
  36221. return 50.0;
  36222. };
  36223. /**
  36224. * Returns the light direction (Vector3) for any passed face index.
  36225. */
  36226. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36227. return this.transformedDirection ? this.transformedDirection : this.direction;
  36228. };
  36229. /**
  36230. * Returns the DirectionalLight absolute position in the World.
  36231. */
  36232. ShadowLight.prototype.getAbsolutePosition = function () {
  36233. return this.transformedPosition ? this.transformedPosition : this.position;
  36234. };
  36235. /**
  36236. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36237. * Returns the updated DirectionalLight direction (Vector3).
  36238. */
  36239. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36240. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36241. return this.direction;
  36242. };
  36243. /**
  36244. * Returns the light rotation (Vector3).
  36245. */
  36246. ShadowLight.prototype.getRotation = function () {
  36247. this.direction.normalize();
  36248. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36249. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36250. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36251. };
  36252. /**
  36253. * Boolean : false by default.
  36254. */
  36255. ShadowLight.prototype.needCube = function () {
  36256. return false;
  36257. };
  36258. /**
  36259. * Specifies wether or not the projection matrix should be recomputed this frame.
  36260. */
  36261. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36262. return this._needProjectionMatrixCompute;
  36263. };
  36264. /**
  36265. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36266. */
  36267. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36268. this._needProjectionMatrixCompute = true;
  36269. };
  36270. /**
  36271. * Get the world matrix of the sahdow lights.
  36272. */
  36273. ShadowLight.prototype._getWorldMatrix = function () {
  36274. if (!this._worldMatrix) {
  36275. this._worldMatrix = BABYLON.Matrix.Identity();
  36276. }
  36277. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36278. return this._worldMatrix;
  36279. };
  36280. /**
  36281. * Gets the minZ used for shadow according to both the scene and the light.
  36282. * @param activeCamera
  36283. */
  36284. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36285. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36286. };
  36287. /**
  36288. * Gets the maxZ used for shadow according to both the scene and the light.
  36289. * @param activeCamera
  36290. */
  36291. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36292. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36293. };
  36294. /**
  36295. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36296. * Returns the light.
  36297. */
  36298. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36299. if (this.customProjectionMatrixBuilder) {
  36300. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36301. }
  36302. else {
  36303. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36304. }
  36305. return this;
  36306. };
  36307. __decorate([
  36308. BABYLON.serializeAsVector3()
  36309. ], ShadowLight.prototype, "position", void 0);
  36310. __decorate([
  36311. BABYLON.serializeAsVector3()
  36312. ], ShadowLight.prototype, "direction", null);
  36313. __decorate([
  36314. BABYLON.serialize()
  36315. ], ShadowLight.prototype, "shadowMinZ", null);
  36316. __decorate([
  36317. BABYLON.serialize()
  36318. ], ShadowLight.prototype, "shadowMaxZ", null);
  36319. return ShadowLight;
  36320. }(BABYLON.Light));
  36321. BABYLON.ShadowLight = ShadowLight;
  36322. })(BABYLON || (BABYLON = {}));
  36323. //# sourceMappingURL=babylon.shadowLight.js.map
  36324. var BABYLON;
  36325. (function (BABYLON) {
  36326. var PointLight = (function (_super) {
  36327. __extends(PointLight, _super);
  36328. /**
  36329. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36330. * A PointLight emits the light in every direction.
  36331. * It can cast shadows.
  36332. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36333. * ```javascript
  36334. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36335. * ```
  36336. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36337. */
  36338. function PointLight(name, position, scene) {
  36339. var _this = _super.call(this, name, scene) || this;
  36340. _this._shadowAngle = Math.PI / 2;
  36341. _this.position = position;
  36342. return _this;
  36343. }
  36344. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36345. /**
  36346. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36347. * This specifies what angle the shadow will use to be created.
  36348. *
  36349. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36350. */
  36351. get: function () {
  36352. return this._shadowAngle;
  36353. },
  36354. /**
  36355. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36356. * This specifies what angle the shadow will use to be created.
  36357. *
  36358. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36359. */
  36360. set: function (value) {
  36361. this._shadowAngle = value;
  36362. this.forceProjectionMatrixCompute();
  36363. },
  36364. enumerable: true,
  36365. configurable: true
  36366. });
  36367. Object.defineProperty(PointLight.prototype, "direction", {
  36368. get: function () {
  36369. return this._direction;
  36370. },
  36371. /**
  36372. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36373. */
  36374. set: function (value) {
  36375. var previousNeedCube = this.needCube();
  36376. this._direction = value;
  36377. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36378. this._shadowGenerator.recreateShadowMap();
  36379. }
  36380. },
  36381. enumerable: true,
  36382. configurable: true
  36383. });
  36384. /**
  36385. * Returns the string "PointLight"
  36386. */
  36387. PointLight.prototype.getClassName = function () {
  36388. return "PointLight";
  36389. };
  36390. /**
  36391. * Returns the integer 0.
  36392. */
  36393. PointLight.prototype.getTypeID = function () {
  36394. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36395. };
  36396. /**
  36397. * Specifies wether or not the shadowmap should be a cube texture.
  36398. */
  36399. PointLight.prototype.needCube = function () {
  36400. return !this.direction;
  36401. };
  36402. /**
  36403. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36404. */
  36405. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36406. if (this.direction) {
  36407. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36408. }
  36409. else {
  36410. switch (faceIndex) {
  36411. case 0:
  36412. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36413. case 1:
  36414. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36415. case 2:
  36416. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36417. case 3:
  36418. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36419. case 4:
  36420. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36421. case 5:
  36422. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36423. }
  36424. }
  36425. return BABYLON.Vector3.Zero();
  36426. };
  36427. /**
  36428. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36429. * - fov = PI / 2
  36430. * - aspect ratio : 1.0
  36431. * - z-near and far equal to the active camera minZ and maxZ.
  36432. * Returns the PointLight.
  36433. */
  36434. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36435. var activeCamera = this.getScene().activeCamera;
  36436. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36437. };
  36438. PointLight.prototype._buildUniformLayout = function () {
  36439. this._uniformBuffer.addUniform("vLightData", 4);
  36440. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36441. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36442. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36443. this._uniformBuffer.addUniform("depthValues", 2);
  36444. this._uniformBuffer.create();
  36445. };
  36446. /**
  36447. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36448. * Returns the PointLight.
  36449. */
  36450. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36451. if (this.computeTransformedInformation()) {
  36452. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36453. return this;
  36454. }
  36455. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36456. return this;
  36457. };
  36458. __decorate([
  36459. BABYLON.serialize()
  36460. ], PointLight.prototype, "shadowAngle", null);
  36461. return PointLight;
  36462. }(BABYLON.ShadowLight));
  36463. BABYLON.PointLight = PointLight;
  36464. })(BABYLON || (BABYLON = {}));
  36465. //# sourceMappingURL=babylon.pointLight.js.map
  36466. /// <reference path="babylon.light.ts" />
  36467. var BABYLON;
  36468. (function (BABYLON) {
  36469. var DirectionalLight = (function (_super) {
  36470. __extends(DirectionalLight, _super);
  36471. /**
  36472. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36473. * The directional light is emitted from everywhere in the given direction.
  36474. * It can cast shawdows.
  36475. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36476. */
  36477. function DirectionalLight(name, direction, scene) {
  36478. var _this = _super.call(this, name, scene) || this;
  36479. _this._shadowFrustumSize = 0;
  36480. _this._shadowOrthoScale = 0.5;
  36481. _this.autoUpdateExtends = true;
  36482. // Cache
  36483. _this._orthoLeft = Number.MAX_VALUE;
  36484. _this._orthoRight = Number.MIN_VALUE;
  36485. _this._orthoTop = Number.MIN_VALUE;
  36486. _this._orthoBottom = Number.MAX_VALUE;
  36487. _this.position = direction.scale(-1.0);
  36488. _this.direction = direction;
  36489. return _this;
  36490. }
  36491. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36492. /**
  36493. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36494. */
  36495. get: function () {
  36496. return this._shadowFrustumSize;
  36497. },
  36498. /**
  36499. * Specifies a fix frustum size for the shadow generation.
  36500. */
  36501. set: function (value) {
  36502. this._shadowFrustumSize = value;
  36503. this.forceProjectionMatrixCompute();
  36504. },
  36505. enumerable: true,
  36506. configurable: true
  36507. });
  36508. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36509. get: function () {
  36510. return this._shadowOrthoScale;
  36511. },
  36512. set: function (value) {
  36513. this._shadowOrthoScale = value;
  36514. this.forceProjectionMatrixCompute();
  36515. },
  36516. enumerable: true,
  36517. configurable: true
  36518. });
  36519. /**
  36520. * Returns the string "DirectionalLight".
  36521. */
  36522. DirectionalLight.prototype.getClassName = function () {
  36523. return "DirectionalLight";
  36524. };
  36525. /**
  36526. * Returns the integer 1.
  36527. */
  36528. DirectionalLight.prototype.getTypeID = function () {
  36529. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36530. };
  36531. /**
  36532. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36533. * Returns the DirectionalLight Shadow projection matrix.
  36534. */
  36535. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36536. if (this.shadowFrustumSize > 0) {
  36537. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36538. }
  36539. else {
  36540. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36541. }
  36542. };
  36543. /**
  36544. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36545. * Returns the DirectionalLight Shadow projection matrix.
  36546. */
  36547. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36548. var activeCamera = this.getScene().activeCamera;
  36549. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36550. };
  36551. /**
  36552. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36553. * Returns the DirectionalLight Shadow projection matrix.
  36554. */
  36555. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36556. var activeCamera = this.getScene().activeCamera;
  36557. // Check extends
  36558. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36559. var tempVector3 = BABYLON.Vector3.Zero();
  36560. this._orthoLeft = Number.MAX_VALUE;
  36561. this._orthoRight = Number.MIN_VALUE;
  36562. this._orthoTop = Number.MIN_VALUE;
  36563. this._orthoBottom = Number.MAX_VALUE;
  36564. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36565. var mesh = renderList[meshIndex];
  36566. if (!mesh) {
  36567. continue;
  36568. }
  36569. var boundingInfo = mesh.getBoundingInfo();
  36570. if (!boundingInfo) {
  36571. continue;
  36572. }
  36573. var boundingBox = boundingInfo.boundingBox;
  36574. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36575. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36576. if (tempVector3.x < this._orthoLeft)
  36577. this._orthoLeft = tempVector3.x;
  36578. if (tempVector3.y < this._orthoBottom)
  36579. this._orthoBottom = tempVector3.y;
  36580. if (tempVector3.x > this._orthoRight)
  36581. this._orthoRight = tempVector3.x;
  36582. if (tempVector3.y > this._orthoTop)
  36583. this._orthoTop = tempVector3.y;
  36584. }
  36585. }
  36586. }
  36587. var xOffset = this._orthoRight - this._orthoLeft;
  36588. var yOffset = this._orthoTop - this._orthoBottom;
  36589. 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);
  36590. };
  36591. DirectionalLight.prototype._buildUniformLayout = function () {
  36592. this._uniformBuffer.addUniform("vLightData", 4);
  36593. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36594. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36595. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36596. this._uniformBuffer.addUniform("depthValues", 2);
  36597. this._uniformBuffer.create();
  36598. };
  36599. /**
  36600. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36601. * Returns the DirectionalLight.
  36602. */
  36603. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36604. if (this.computeTransformedInformation()) {
  36605. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36606. return this;
  36607. }
  36608. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36609. return this;
  36610. };
  36611. /**
  36612. * Gets the minZ used for shadow according to both the scene and the light.
  36613. *
  36614. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36615. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36616. * @param activeCamera
  36617. */
  36618. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36619. return 1;
  36620. };
  36621. /**
  36622. * Gets the maxZ used for shadow according to both the scene and the light.
  36623. *
  36624. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36625. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36626. * @param activeCamera
  36627. */
  36628. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36629. return 1;
  36630. };
  36631. __decorate([
  36632. BABYLON.serialize()
  36633. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36634. __decorate([
  36635. BABYLON.serialize()
  36636. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36637. __decorate([
  36638. BABYLON.serialize()
  36639. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36640. return DirectionalLight;
  36641. }(BABYLON.ShadowLight));
  36642. BABYLON.DirectionalLight = DirectionalLight;
  36643. })(BABYLON || (BABYLON = {}));
  36644. //# sourceMappingURL=babylon.directionalLight.js.map
  36645. var BABYLON;
  36646. (function (BABYLON) {
  36647. var SpotLight = (function (_super) {
  36648. __extends(SpotLight, _super);
  36649. /**
  36650. * Creates a SpotLight object in the scene with the passed parameters :
  36651. * - `position` (Vector3) is the initial SpotLight position,
  36652. * - `direction` (Vector3) is the initial SpotLight direction,
  36653. * - `angle` (float, in radians) is the spot light cone angle,
  36654. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36655. * A spot light is a simply light oriented cone.
  36656. * It can cast shadows.
  36657. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36658. */
  36659. function SpotLight(name, position, direction, angle, exponent, scene) {
  36660. var _this = _super.call(this, name, scene) || this;
  36661. _this.position = position;
  36662. _this.direction = direction;
  36663. _this.angle = angle;
  36664. _this.exponent = exponent;
  36665. return _this;
  36666. }
  36667. Object.defineProperty(SpotLight.prototype, "angle", {
  36668. get: function () {
  36669. return this._angle;
  36670. },
  36671. set: function (value) {
  36672. this._angle = value;
  36673. this.forceProjectionMatrixCompute();
  36674. },
  36675. enumerable: true,
  36676. configurable: true
  36677. });
  36678. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36679. get: function () {
  36680. return this._shadowAngleScale;
  36681. },
  36682. /**
  36683. * Allows scaling the angle of the light for shadow generation only.
  36684. */
  36685. set: function (value) {
  36686. this._shadowAngleScale = value;
  36687. this.forceProjectionMatrixCompute();
  36688. },
  36689. enumerable: true,
  36690. configurable: true
  36691. });
  36692. /**
  36693. * Returns the string "SpotLight".
  36694. */
  36695. SpotLight.prototype.getClassName = function () {
  36696. return "SpotLight";
  36697. };
  36698. /**
  36699. * Returns the integer 2.
  36700. */
  36701. SpotLight.prototype.getTypeID = function () {
  36702. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36703. };
  36704. /**
  36705. * 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.
  36706. * Returns the SpotLight.
  36707. */
  36708. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36709. var activeCamera = this.getScene().activeCamera;
  36710. this._shadowAngleScale = this._shadowAngleScale || 1;
  36711. var angle = this._shadowAngleScale * this._angle;
  36712. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36713. };
  36714. SpotLight.prototype._buildUniformLayout = function () {
  36715. this._uniformBuffer.addUniform("vLightData", 4);
  36716. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36717. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36718. this._uniformBuffer.addUniform("vLightDirection", 3);
  36719. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36720. this._uniformBuffer.addUniform("depthValues", 2);
  36721. this._uniformBuffer.create();
  36722. };
  36723. /**
  36724. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36725. * Return the SpotLight.
  36726. */
  36727. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36728. var normalizeDirection;
  36729. if (this.computeTransformedInformation()) {
  36730. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36731. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36732. }
  36733. else {
  36734. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36735. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36736. }
  36737. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36738. return this;
  36739. };
  36740. __decorate([
  36741. BABYLON.serialize()
  36742. ], SpotLight.prototype, "angle", null);
  36743. __decorate([
  36744. BABYLON.serialize()
  36745. /**
  36746. * Allows scaling the angle of the light for shadow generation only.
  36747. */
  36748. ], SpotLight.prototype, "shadowAngleScale", null);
  36749. __decorate([
  36750. BABYLON.serialize()
  36751. ], SpotLight.prototype, "exponent", void 0);
  36752. return SpotLight;
  36753. }(BABYLON.ShadowLight));
  36754. BABYLON.SpotLight = SpotLight;
  36755. })(BABYLON || (BABYLON = {}));
  36756. //# sourceMappingURL=babylon.spotLight.js.map
  36757. var BABYLON;
  36758. (function (BABYLON) {
  36759. var AnimationRange = (function () {
  36760. function AnimationRange(name, from, to) {
  36761. this.name = name;
  36762. this.from = from;
  36763. this.to = to;
  36764. }
  36765. AnimationRange.prototype.clone = function () {
  36766. return new AnimationRange(this.name, this.from, this.to);
  36767. };
  36768. return AnimationRange;
  36769. }());
  36770. BABYLON.AnimationRange = AnimationRange;
  36771. /**
  36772. * Composed of a frame, and an action function
  36773. */
  36774. var AnimationEvent = (function () {
  36775. function AnimationEvent(frame, action, onlyOnce) {
  36776. this.frame = frame;
  36777. this.action = action;
  36778. this.onlyOnce = onlyOnce;
  36779. this.isDone = false;
  36780. }
  36781. return AnimationEvent;
  36782. }());
  36783. BABYLON.AnimationEvent = AnimationEvent;
  36784. var PathCursor = (function () {
  36785. function PathCursor(path) {
  36786. this.path = path;
  36787. this._onchange = new Array();
  36788. this.value = 0;
  36789. this.animations = new Array();
  36790. }
  36791. PathCursor.prototype.getPoint = function () {
  36792. var point = this.path.getPointAtLengthPosition(this.value);
  36793. return new BABYLON.Vector3(point.x, 0, point.y);
  36794. };
  36795. PathCursor.prototype.moveAhead = function (step) {
  36796. if (step === void 0) { step = 0.002; }
  36797. this.move(step);
  36798. return this;
  36799. };
  36800. PathCursor.prototype.moveBack = function (step) {
  36801. if (step === void 0) { step = 0.002; }
  36802. this.move(-step);
  36803. return this;
  36804. };
  36805. PathCursor.prototype.move = function (step) {
  36806. if (Math.abs(step) > 1) {
  36807. throw "step size should be less than 1.";
  36808. }
  36809. this.value += step;
  36810. this.ensureLimits();
  36811. this.raiseOnChange();
  36812. return this;
  36813. };
  36814. PathCursor.prototype.ensureLimits = function () {
  36815. while (this.value > 1) {
  36816. this.value -= 1;
  36817. }
  36818. while (this.value < 0) {
  36819. this.value += 1;
  36820. }
  36821. return this;
  36822. };
  36823. // used by animation engine
  36824. PathCursor.prototype.markAsDirty = function (propertyName) {
  36825. this.ensureLimits();
  36826. this.raiseOnChange();
  36827. return this;
  36828. };
  36829. PathCursor.prototype.raiseOnChange = function () {
  36830. var _this = this;
  36831. this._onchange.forEach(function (f) { return f(_this); });
  36832. return this;
  36833. };
  36834. PathCursor.prototype.onchange = function (f) {
  36835. this._onchange.push(f);
  36836. return this;
  36837. };
  36838. return PathCursor;
  36839. }());
  36840. BABYLON.PathCursor = PathCursor;
  36841. var Animation = (function () {
  36842. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  36843. this.name = name;
  36844. this.targetProperty = targetProperty;
  36845. this.framePerSecond = framePerSecond;
  36846. this.dataType = dataType;
  36847. this.loopMode = loopMode;
  36848. this.enableBlending = enableBlending;
  36849. this._offsetsCache = {};
  36850. this._highLimitsCache = {};
  36851. this._stopped = false;
  36852. this._blendingFactor = 0;
  36853. // The set of event that will be linked to this animation
  36854. this._events = new Array();
  36855. this.blendingSpeed = 0.01;
  36856. this._ranges = {};
  36857. this.targetPropertyPath = targetProperty.split(".");
  36858. this.dataType = dataType;
  36859. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  36860. }
  36861. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  36862. var dataType = undefined;
  36863. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  36864. dataType = Animation.ANIMATIONTYPE_FLOAT;
  36865. }
  36866. else if (from instanceof BABYLON.Quaternion) {
  36867. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  36868. }
  36869. else if (from instanceof BABYLON.Vector3) {
  36870. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  36871. }
  36872. else if (from instanceof BABYLON.Vector2) {
  36873. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  36874. }
  36875. else if (from instanceof BABYLON.Color3) {
  36876. dataType = Animation.ANIMATIONTYPE_COLOR3;
  36877. }
  36878. else if (from instanceof BABYLON.Size) {
  36879. dataType = Animation.ANIMATIONTYPE_SIZE;
  36880. }
  36881. if (dataType == undefined) {
  36882. return null;
  36883. }
  36884. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  36885. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  36886. animation.setKeys(keys);
  36887. if (easingFunction !== undefined) {
  36888. animation.setEasingFunction(easingFunction);
  36889. }
  36890. return animation;
  36891. };
  36892. /**
  36893. * Sets up an animation.
  36894. * @param property the property to animate
  36895. * @param animationType the animation type to apply
  36896. * @param easingFunction the easing function used in the animation
  36897. * @returns The created animation
  36898. */
  36899. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  36900. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36901. animation.setEasingFunction(easingFunction);
  36902. return animation;
  36903. };
  36904. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36905. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36906. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36907. };
  36908. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36909. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36910. node.animations.push(animation);
  36911. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36912. };
  36913. /**
  36914. * Transition property of the Camera to the target Value.
  36915. * @param property The property to transition
  36916. * @param targetValue The target Value of the property
  36917. * @param host The object where the property to animate belongs
  36918. * @param scene Scene used to run the animation
  36919. * @param frameRate Framerate (in frame/s) to use
  36920. * @param transition The transition type we want to use
  36921. * @param duration The duration of the animation, in milliseconds
  36922. * @param onAnimationEnd Call back trigger at the end of the animation.
  36923. */
  36924. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  36925. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  36926. if (duration <= 0) {
  36927. host[property] = targetValue;
  36928. if (onAnimationEnd) {
  36929. onAnimationEnd();
  36930. }
  36931. return;
  36932. }
  36933. var endFrame = frameRate * (duration / 1000);
  36934. transition.setKeys([{
  36935. frame: 0,
  36936. value: host[property].clone ? host[property].clone() : host[property]
  36937. },
  36938. {
  36939. frame: endFrame,
  36940. value: targetValue
  36941. }]);
  36942. if (!host.animations) {
  36943. host.animations = [];
  36944. }
  36945. host.animations.push(transition);
  36946. var animation = scene.beginAnimation(host, 0, endFrame, false);
  36947. animation.onAnimationEnd = onAnimationEnd;
  36948. return animation;
  36949. };
  36950. // Methods
  36951. /**
  36952. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  36953. */
  36954. Animation.prototype.toString = function (fullDetails) {
  36955. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  36956. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  36957. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  36958. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  36959. if (fullDetails) {
  36960. ret += ", Ranges: {";
  36961. var first = true;
  36962. for (var name in this._ranges) {
  36963. if (first) {
  36964. ret += ", ";
  36965. first = false;
  36966. }
  36967. ret += name;
  36968. }
  36969. ret += "}";
  36970. }
  36971. return ret;
  36972. };
  36973. /**
  36974. * Add an event to this animation.
  36975. */
  36976. Animation.prototype.addEvent = function (event) {
  36977. this._events.push(event);
  36978. };
  36979. /**
  36980. * Remove all events found at the given frame
  36981. * @param frame
  36982. */
  36983. Animation.prototype.removeEvents = function (frame) {
  36984. for (var index = 0; index < this._events.length; index++) {
  36985. if (this._events[index].frame === frame) {
  36986. this._events.splice(index, 1);
  36987. index--;
  36988. }
  36989. }
  36990. };
  36991. Animation.prototype.createRange = function (name, from, to) {
  36992. // check name not already in use; could happen for bones after serialized
  36993. if (!this._ranges[name]) {
  36994. this._ranges[name] = new AnimationRange(name, from, to);
  36995. }
  36996. };
  36997. Animation.prototype.deleteRange = function (name, deleteFrames) {
  36998. if (deleteFrames === void 0) { deleteFrames = true; }
  36999. if (this._ranges[name]) {
  37000. if (deleteFrames) {
  37001. var from = this._ranges[name].from;
  37002. var to = this._ranges[name].to;
  37003. // this loop MUST go high to low for multiple splices to work
  37004. for (var key = this._keys.length - 1; key >= 0; key--) {
  37005. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  37006. this._keys.splice(key, 1);
  37007. }
  37008. }
  37009. }
  37010. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  37011. }
  37012. };
  37013. Animation.prototype.getRange = function (name) {
  37014. return this._ranges[name];
  37015. };
  37016. Animation.prototype.reset = function () {
  37017. this._offsetsCache = {};
  37018. this._highLimitsCache = {};
  37019. this.currentFrame = 0;
  37020. this._blendingFactor = 0;
  37021. this._originalBlendValue = null;
  37022. };
  37023. Animation.prototype.isStopped = function () {
  37024. return this._stopped;
  37025. };
  37026. Animation.prototype.getKeys = function () {
  37027. return this._keys;
  37028. };
  37029. Animation.prototype.getHighestFrame = function () {
  37030. var ret = 0;
  37031. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  37032. if (ret < this._keys[key].frame) {
  37033. ret = this._keys[key].frame;
  37034. }
  37035. }
  37036. return ret;
  37037. };
  37038. Animation.prototype.getEasingFunction = function () {
  37039. return this._easingFunction;
  37040. };
  37041. Animation.prototype.setEasingFunction = function (easingFunction) {
  37042. this._easingFunction = easingFunction;
  37043. };
  37044. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  37045. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  37046. };
  37047. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37048. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37049. };
  37050. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  37051. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  37052. };
  37053. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37054. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  37055. };
  37056. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  37057. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  37058. };
  37059. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37060. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37061. };
  37062. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  37063. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  37064. };
  37065. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37066. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37067. };
  37068. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  37069. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  37070. };
  37071. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  37072. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  37073. };
  37074. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  37075. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  37076. };
  37077. Animation.prototype.clone = function () {
  37078. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  37079. clone.enableBlending = this.enableBlending;
  37080. clone.blendingSpeed = this.blendingSpeed;
  37081. if (this._keys) {
  37082. clone.setKeys(this._keys);
  37083. }
  37084. if (this._ranges) {
  37085. clone._ranges = {};
  37086. for (var name in this._ranges) {
  37087. clone._ranges[name] = this._ranges[name].clone();
  37088. }
  37089. }
  37090. return clone;
  37091. };
  37092. Animation.prototype.setKeys = function (values) {
  37093. this._keys = values.slice(0);
  37094. this._offsetsCache = {};
  37095. this._highLimitsCache = {};
  37096. };
  37097. Animation.prototype._getKeyValue = function (value) {
  37098. if (typeof value === "function") {
  37099. return value();
  37100. }
  37101. return value;
  37102. };
  37103. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  37104. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  37105. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  37106. }
  37107. this.currentFrame = currentFrame;
  37108. // Try to get a hash to find the right key
  37109. var startKeyIndex = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  37110. if (this._keys[startKeyIndex].frame >= currentFrame) {
  37111. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  37112. startKeyIndex--;
  37113. }
  37114. }
  37115. for (var key = startKeyIndex; key < this._keys.length; key++) {
  37116. var endKey = this._keys[key + 1];
  37117. if (endKey.frame >= currentFrame) {
  37118. var startKey = this._keys[key];
  37119. var startValue = this._getKeyValue(startKey.value);
  37120. var endValue = this._getKeyValue(endKey.value);
  37121. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  37122. var frameDelta = endKey.frame - startKey.frame;
  37123. // gradient : percent of currentFrame between the frame inf and the frame sup
  37124. var gradient = (currentFrame - startKey.frame) / frameDelta;
  37125. // check for easingFunction and correction of gradient
  37126. if (this._easingFunction != null) {
  37127. gradient = this._easingFunction.ease(gradient);
  37128. }
  37129. switch (this.dataType) {
  37130. // Float
  37131. case Animation.ANIMATIONTYPE_FLOAT:
  37132. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  37133. switch (loopMode) {
  37134. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37135. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37136. return floatValue;
  37137. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37138. return offsetValue * repeatCount + floatValue;
  37139. }
  37140. break;
  37141. // Quaternion
  37142. case Animation.ANIMATIONTYPE_QUATERNION:
  37143. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  37144. switch (loopMode) {
  37145. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37146. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37147. return quatValue;
  37148. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37149. return quatValue.add(offsetValue.scale(repeatCount));
  37150. }
  37151. return quatValue;
  37152. // Vector3
  37153. case Animation.ANIMATIONTYPE_VECTOR3:
  37154. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  37155. switch (loopMode) {
  37156. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37157. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37158. return vec3Value;
  37159. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37160. return vec3Value.add(offsetValue.scale(repeatCount));
  37161. }
  37162. // Vector2
  37163. case Animation.ANIMATIONTYPE_VECTOR2:
  37164. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  37165. switch (loopMode) {
  37166. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37167. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37168. return vec2Value;
  37169. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37170. return vec2Value.add(offsetValue.scale(repeatCount));
  37171. }
  37172. // Size
  37173. case Animation.ANIMATIONTYPE_SIZE:
  37174. switch (loopMode) {
  37175. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37176. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37177. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  37178. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37179. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37180. }
  37181. // Color3
  37182. case Animation.ANIMATIONTYPE_COLOR3:
  37183. switch (loopMode) {
  37184. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37185. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37186. return this.color3InterpolateFunction(startValue, endValue, gradient);
  37187. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37188. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37189. }
  37190. // Matrix
  37191. case Animation.ANIMATIONTYPE_MATRIX:
  37192. switch (loopMode) {
  37193. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37194. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37195. if (Animation.AllowMatricesInterpolation) {
  37196. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  37197. }
  37198. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37199. return startValue;
  37200. }
  37201. default:
  37202. break;
  37203. }
  37204. break;
  37205. }
  37206. }
  37207. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  37208. };
  37209. Animation.prototype.setValue = function (currentValue, blend) {
  37210. if (blend === void 0) { blend = false; }
  37211. // Set value
  37212. var path;
  37213. var destination;
  37214. if (this.targetPropertyPath.length > 1) {
  37215. var property = this._target[this.targetPropertyPath[0]];
  37216. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  37217. property = property[this.targetPropertyPath[index]];
  37218. }
  37219. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  37220. destination = property;
  37221. }
  37222. else {
  37223. path = this.targetPropertyPath[0];
  37224. destination = this._target;
  37225. }
  37226. // Blending
  37227. if (this.enableBlending && this._blendingFactor <= 1.0) {
  37228. if (!this._originalBlendValue) {
  37229. if (destination[path].clone) {
  37230. this._originalBlendValue = destination[path].clone();
  37231. }
  37232. else {
  37233. this._originalBlendValue = destination[path];
  37234. }
  37235. }
  37236. if (this._originalBlendValue.prototype) {
  37237. if (this._originalBlendValue.prototype.Lerp) {
  37238. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  37239. }
  37240. else {
  37241. destination[path] = currentValue;
  37242. }
  37243. }
  37244. else if (this._originalBlendValue.m) {
  37245. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  37246. }
  37247. else {
  37248. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  37249. }
  37250. this._blendingFactor += this.blendingSpeed;
  37251. }
  37252. else {
  37253. destination[path] = currentValue;
  37254. }
  37255. if (this._target.markAsDirty) {
  37256. this._target.markAsDirty(this.targetProperty);
  37257. }
  37258. };
  37259. Animation.prototype.goToFrame = function (frame) {
  37260. if (frame < this._keys[0].frame) {
  37261. frame = this._keys[0].frame;
  37262. }
  37263. else if (frame > this._keys[this._keys.length - 1].frame) {
  37264. frame = this._keys[this._keys.length - 1].frame;
  37265. }
  37266. var currentValue = this._interpolate(frame, 0, this.loopMode);
  37267. this.setValue(currentValue);
  37268. };
  37269. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  37270. if (blend === void 0) { blend = false; }
  37271. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  37272. this._stopped = true;
  37273. return false;
  37274. }
  37275. var returnValue = true;
  37276. // Adding a start key at frame 0 if missing
  37277. if (this._keys[0].frame !== 0) {
  37278. var newKey = { frame: 0, value: this._keys[0].value };
  37279. this._keys.splice(0, 0, newKey);
  37280. }
  37281. // Check limits
  37282. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  37283. from = this._keys[0].frame;
  37284. }
  37285. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  37286. to = this._keys[this._keys.length - 1].frame;
  37287. }
  37288. //to and from cannot be the same key
  37289. if (from === to) {
  37290. from++;
  37291. }
  37292. // Compute ratio
  37293. var range = to - from;
  37294. var offsetValue;
  37295. // ratio represents the frame delta between from and to
  37296. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  37297. var highLimitValue = 0;
  37298. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  37299. returnValue = false;
  37300. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  37301. }
  37302. else {
  37303. // Get max value if required
  37304. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  37305. var keyOffset = to.toString() + from.toString();
  37306. if (!this._offsetsCache[keyOffset]) {
  37307. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  37308. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  37309. switch (this.dataType) {
  37310. // Float
  37311. case Animation.ANIMATIONTYPE_FLOAT:
  37312. this._offsetsCache[keyOffset] = toValue - fromValue;
  37313. break;
  37314. // Quaternion
  37315. case Animation.ANIMATIONTYPE_QUATERNION:
  37316. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37317. break;
  37318. // Vector3
  37319. case Animation.ANIMATIONTYPE_VECTOR3:
  37320. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37321. // Vector2
  37322. case Animation.ANIMATIONTYPE_VECTOR2:
  37323. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37324. // Size
  37325. case Animation.ANIMATIONTYPE_SIZE:
  37326. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37327. // Color3
  37328. case Animation.ANIMATIONTYPE_COLOR3:
  37329. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37330. default:
  37331. break;
  37332. }
  37333. this._highLimitsCache[keyOffset] = toValue;
  37334. }
  37335. highLimitValue = this._highLimitsCache[keyOffset];
  37336. offsetValue = this._offsetsCache[keyOffset];
  37337. }
  37338. }
  37339. if (offsetValue === undefined) {
  37340. switch (this.dataType) {
  37341. // Float
  37342. case Animation.ANIMATIONTYPE_FLOAT:
  37343. offsetValue = 0;
  37344. break;
  37345. // Quaternion
  37346. case Animation.ANIMATIONTYPE_QUATERNION:
  37347. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  37348. break;
  37349. // Vector3
  37350. case Animation.ANIMATIONTYPE_VECTOR3:
  37351. offsetValue = BABYLON.Vector3.Zero();
  37352. break;
  37353. // Vector2
  37354. case Animation.ANIMATIONTYPE_VECTOR2:
  37355. offsetValue = BABYLON.Vector2.Zero();
  37356. break;
  37357. // Size
  37358. case Animation.ANIMATIONTYPE_SIZE:
  37359. offsetValue = BABYLON.Size.Zero();
  37360. break;
  37361. // Color3
  37362. case Animation.ANIMATIONTYPE_COLOR3:
  37363. offsetValue = BABYLON.Color3.Black();
  37364. }
  37365. }
  37366. // Compute value
  37367. var repeatCount = (ratio / range) >> 0;
  37368. var currentFrame = returnValue ? from + ratio % range : to;
  37369. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  37370. // Set value
  37371. this.setValue(currentValue);
  37372. // Check events
  37373. for (var index = 0; index < this._events.length; index++) {
  37374. // Make sure current frame has passed event frame and that event frame is within the current range
  37375. // Also, handle both forward and reverse animations
  37376. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  37377. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  37378. var event = this._events[index];
  37379. if (!event.isDone) {
  37380. // If event should be done only once, remove it.
  37381. if (event.onlyOnce) {
  37382. this._events.splice(index, 1);
  37383. index--;
  37384. }
  37385. event.isDone = true;
  37386. event.action();
  37387. } // Don't do anything if the event has already be done.
  37388. }
  37389. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  37390. // reset event, the animation is looping
  37391. this._events[index].isDone = false;
  37392. }
  37393. }
  37394. if (!returnValue) {
  37395. this._stopped = true;
  37396. }
  37397. return returnValue;
  37398. };
  37399. Animation.prototype.serialize = function () {
  37400. var serializationObject = {};
  37401. serializationObject.name = this.name;
  37402. serializationObject.property = this.targetProperty;
  37403. serializationObject.framePerSecond = this.framePerSecond;
  37404. serializationObject.dataType = this.dataType;
  37405. serializationObject.loopBehavior = this.loopMode;
  37406. serializationObject.enableBlending = this.enableBlending;
  37407. serializationObject.blendingSpeed = this.blendingSpeed;
  37408. var dataType = this.dataType;
  37409. serializationObject.keys = [];
  37410. var keys = this.getKeys();
  37411. for (var index = 0; index < keys.length; index++) {
  37412. var animationKey = keys[index];
  37413. var key = {};
  37414. key.frame = animationKey.frame;
  37415. switch (dataType) {
  37416. case Animation.ANIMATIONTYPE_FLOAT:
  37417. key.values = [animationKey.value];
  37418. break;
  37419. case Animation.ANIMATIONTYPE_QUATERNION:
  37420. case Animation.ANIMATIONTYPE_MATRIX:
  37421. case Animation.ANIMATIONTYPE_VECTOR3:
  37422. case Animation.ANIMATIONTYPE_COLOR3:
  37423. key.values = animationKey.value.asArray();
  37424. break;
  37425. }
  37426. serializationObject.keys.push(key);
  37427. }
  37428. serializationObject.ranges = [];
  37429. for (var name in this._ranges) {
  37430. var range = {};
  37431. range.name = name;
  37432. range.from = this._ranges[name].from;
  37433. range.to = this._ranges[name].to;
  37434. serializationObject.ranges.push(range);
  37435. }
  37436. return serializationObject;
  37437. };
  37438. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  37439. get: function () {
  37440. return Animation._ANIMATIONTYPE_FLOAT;
  37441. },
  37442. enumerable: true,
  37443. configurable: true
  37444. });
  37445. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  37446. get: function () {
  37447. return Animation._ANIMATIONTYPE_VECTOR3;
  37448. },
  37449. enumerable: true,
  37450. configurable: true
  37451. });
  37452. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  37453. get: function () {
  37454. return Animation._ANIMATIONTYPE_VECTOR2;
  37455. },
  37456. enumerable: true,
  37457. configurable: true
  37458. });
  37459. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  37460. get: function () {
  37461. return Animation._ANIMATIONTYPE_SIZE;
  37462. },
  37463. enumerable: true,
  37464. configurable: true
  37465. });
  37466. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  37467. get: function () {
  37468. return Animation._ANIMATIONTYPE_QUATERNION;
  37469. },
  37470. enumerable: true,
  37471. configurable: true
  37472. });
  37473. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37474. get: function () {
  37475. return Animation._ANIMATIONTYPE_MATRIX;
  37476. },
  37477. enumerable: true,
  37478. configurable: true
  37479. });
  37480. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37481. get: function () {
  37482. return Animation._ANIMATIONTYPE_COLOR3;
  37483. },
  37484. enumerable: true,
  37485. configurable: true
  37486. });
  37487. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37488. get: function () {
  37489. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37490. },
  37491. enumerable: true,
  37492. configurable: true
  37493. });
  37494. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37495. get: function () {
  37496. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37497. },
  37498. enumerable: true,
  37499. configurable: true
  37500. });
  37501. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37502. get: function () {
  37503. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37504. },
  37505. enumerable: true,
  37506. configurable: true
  37507. });
  37508. Animation.Parse = function (parsedAnimation) {
  37509. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37510. var dataType = parsedAnimation.dataType;
  37511. var keys = [];
  37512. var data;
  37513. var index;
  37514. if (parsedAnimation.enableBlending) {
  37515. animation.enableBlending = parsedAnimation.enableBlending;
  37516. }
  37517. if (parsedAnimation.blendingSpeed) {
  37518. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37519. }
  37520. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37521. var key = parsedAnimation.keys[index];
  37522. switch (dataType) {
  37523. case Animation.ANIMATIONTYPE_FLOAT:
  37524. data = key.values[0];
  37525. break;
  37526. case Animation.ANIMATIONTYPE_QUATERNION:
  37527. data = BABYLON.Quaternion.FromArray(key.values);
  37528. break;
  37529. case Animation.ANIMATIONTYPE_MATRIX:
  37530. data = BABYLON.Matrix.FromArray(key.values);
  37531. break;
  37532. case Animation.ANIMATIONTYPE_COLOR3:
  37533. data = BABYLON.Color3.FromArray(key.values);
  37534. break;
  37535. case Animation.ANIMATIONTYPE_VECTOR3:
  37536. default:
  37537. data = BABYLON.Vector3.FromArray(key.values);
  37538. break;
  37539. }
  37540. keys.push({
  37541. frame: key.frame,
  37542. value: data
  37543. });
  37544. }
  37545. animation.setKeys(keys);
  37546. if (parsedAnimation.ranges) {
  37547. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37548. data = parsedAnimation.ranges[index];
  37549. animation.createRange(data.name, data.from, data.to);
  37550. }
  37551. }
  37552. return animation;
  37553. };
  37554. Animation.AppendSerializedAnimations = function (source, destination) {
  37555. if (source.animations) {
  37556. destination.animations = [];
  37557. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37558. var animation = source.animations[animationIndex];
  37559. destination.animations.push(animation.serialize());
  37560. }
  37561. }
  37562. };
  37563. Animation.AllowMatricesInterpolation = false;
  37564. // Statics
  37565. Animation._ANIMATIONTYPE_FLOAT = 0;
  37566. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37567. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37568. Animation._ANIMATIONTYPE_MATRIX = 3;
  37569. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37570. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37571. Animation._ANIMATIONTYPE_SIZE = 6;
  37572. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37573. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37574. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37575. return Animation;
  37576. }());
  37577. BABYLON.Animation = Animation;
  37578. })(BABYLON || (BABYLON = {}));
  37579. //# sourceMappingURL=babylon.animation.js.map
  37580. var BABYLON;
  37581. (function (BABYLON) {
  37582. var Animatable = (function () {
  37583. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  37584. if (fromFrame === void 0) { fromFrame = 0; }
  37585. if (toFrame === void 0) { toFrame = 100; }
  37586. if (loopAnimation === void 0) { loopAnimation = false; }
  37587. if (speedRatio === void 0) { speedRatio = 1.0; }
  37588. this.target = target;
  37589. this.fromFrame = fromFrame;
  37590. this.toFrame = toFrame;
  37591. this.loopAnimation = loopAnimation;
  37592. this.speedRatio = speedRatio;
  37593. this.onAnimationEnd = onAnimationEnd;
  37594. this._localDelayOffset = null;
  37595. this._pausedDelay = null;
  37596. this._animations = new Array();
  37597. this._paused = false;
  37598. this.animationStarted = false;
  37599. if (animations) {
  37600. this.appendAnimations(target, animations);
  37601. }
  37602. this._scene = scene;
  37603. scene._activeAnimatables.push(this);
  37604. }
  37605. // Methods
  37606. Animatable.prototype.getAnimations = function () {
  37607. return this._animations;
  37608. };
  37609. Animatable.prototype.appendAnimations = function (target, animations) {
  37610. for (var index = 0; index < animations.length; index++) {
  37611. var animation = animations[index];
  37612. animation._target = target;
  37613. this._animations.push(animation);
  37614. }
  37615. };
  37616. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  37617. var animations = this._animations;
  37618. for (var index = 0; index < animations.length; index++) {
  37619. if (animations[index].targetProperty === property) {
  37620. return animations[index];
  37621. }
  37622. }
  37623. return null;
  37624. };
  37625. Animatable.prototype.reset = function () {
  37626. var animations = this._animations;
  37627. for (var index = 0; index < animations.length; index++) {
  37628. animations[index].reset();
  37629. }
  37630. this._localDelayOffset = null;
  37631. this._pausedDelay = null;
  37632. };
  37633. Animatable.prototype.enableBlending = function (blendingSpeed) {
  37634. var animations = this._animations;
  37635. for (var index = 0; index < animations.length; index++) {
  37636. animations[index].enableBlending = true;
  37637. animations[index].blendingSpeed = blendingSpeed;
  37638. }
  37639. };
  37640. Animatable.prototype.disableBlending = function () {
  37641. var animations = this._animations;
  37642. for (var index = 0; index < animations.length; index++) {
  37643. animations[index].enableBlending = false;
  37644. }
  37645. };
  37646. Animatable.prototype.goToFrame = function (frame) {
  37647. var animations = this._animations;
  37648. if (animations[0]) {
  37649. var fps = animations[0].framePerSecond;
  37650. var currentFrame = animations[0].currentFrame;
  37651. var adjustTime = frame - currentFrame;
  37652. var delay = adjustTime * 1000 / fps;
  37653. this._localDelayOffset -= delay;
  37654. }
  37655. for (var index = 0; index < animations.length; index++) {
  37656. animations[index].goToFrame(frame);
  37657. }
  37658. };
  37659. Animatable.prototype.pause = function () {
  37660. if (this._paused) {
  37661. return;
  37662. }
  37663. this._paused = true;
  37664. };
  37665. Animatable.prototype.restart = function () {
  37666. this._paused = false;
  37667. };
  37668. Animatable.prototype.stop = function (animationName) {
  37669. if (animationName) {
  37670. var idx = this._scene._activeAnimatables.indexOf(this);
  37671. if (idx > -1) {
  37672. var animations = this._animations;
  37673. for (var index = animations.length - 1; index >= 0; index--) {
  37674. if (typeof animationName === "string" && animations[index].name != animationName) {
  37675. continue;
  37676. }
  37677. animations[index].reset();
  37678. animations.splice(index, 1);
  37679. }
  37680. if (animations.length == 0) {
  37681. this._scene._activeAnimatables.splice(idx, 1);
  37682. if (this.onAnimationEnd) {
  37683. this.onAnimationEnd();
  37684. }
  37685. }
  37686. }
  37687. }
  37688. else {
  37689. var index = this._scene._activeAnimatables.indexOf(this);
  37690. if (index > -1) {
  37691. this._scene._activeAnimatables.splice(index, 1);
  37692. var animations = this._animations;
  37693. for (var index = 0; index < animations.length; index++) {
  37694. animations[index].reset();
  37695. }
  37696. if (this.onAnimationEnd) {
  37697. this.onAnimationEnd();
  37698. }
  37699. }
  37700. }
  37701. };
  37702. Animatable.prototype._animate = function (delay) {
  37703. if (this._paused) {
  37704. this.animationStarted = false;
  37705. if (this._pausedDelay === null) {
  37706. this._pausedDelay = delay;
  37707. }
  37708. return true;
  37709. }
  37710. if (this._localDelayOffset === null) {
  37711. this._localDelayOffset = delay;
  37712. }
  37713. else if (this._pausedDelay !== null) {
  37714. this._localDelayOffset += delay - this._pausedDelay;
  37715. this._pausedDelay = null;
  37716. }
  37717. // Animating
  37718. var running = false;
  37719. var animations = this._animations;
  37720. var index;
  37721. for (index = 0; index < animations.length; index++) {
  37722. var animation = animations[index];
  37723. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  37724. running = running || isRunning;
  37725. }
  37726. this.animationStarted = running;
  37727. if (!running) {
  37728. // Remove from active animatables
  37729. index = this._scene._activeAnimatables.indexOf(this);
  37730. this._scene._activeAnimatables.splice(index, 1);
  37731. }
  37732. if (!running && this.onAnimationEnd) {
  37733. this.onAnimationEnd();
  37734. this.onAnimationEnd = null;
  37735. }
  37736. return running;
  37737. };
  37738. return Animatable;
  37739. }());
  37740. BABYLON.Animatable = Animatable;
  37741. })(BABYLON || (BABYLON = {}));
  37742. //# sourceMappingURL=babylon.animatable.js.map
  37743. var BABYLON;
  37744. (function (BABYLON) {
  37745. var EasingFunction = (function () {
  37746. function EasingFunction() {
  37747. // Properties
  37748. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  37749. }
  37750. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  37751. get: function () {
  37752. return EasingFunction._EASINGMODE_EASEIN;
  37753. },
  37754. enumerable: true,
  37755. configurable: true
  37756. });
  37757. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  37758. get: function () {
  37759. return EasingFunction._EASINGMODE_EASEOUT;
  37760. },
  37761. enumerable: true,
  37762. configurable: true
  37763. });
  37764. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  37765. get: function () {
  37766. return EasingFunction._EASINGMODE_EASEINOUT;
  37767. },
  37768. enumerable: true,
  37769. configurable: true
  37770. });
  37771. EasingFunction.prototype.setEasingMode = function (easingMode) {
  37772. var n = Math.min(Math.max(easingMode, 0), 2);
  37773. this._easingMode = n;
  37774. };
  37775. EasingFunction.prototype.getEasingMode = function () {
  37776. return this._easingMode;
  37777. };
  37778. EasingFunction.prototype.easeInCore = function (gradient) {
  37779. throw new Error('You must implement this method');
  37780. };
  37781. EasingFunction.prototype.ease = function (gradient) {
  37782. switch (this._easingMode) {
  37783. case EasingFunction.EASINGMODE_EASEIN:
  37784. return this.easeInCore(gradient);
  37785. case EasingFunction.EASINGMODE_EASEOUT:
  37786. return (1 - this.easeInCore(1 - gradient));
  37787. }
  37788. if (gradient >= 0.5) {
  37789. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  37790. }
  37791. return (this.easeInCore(gradient * 2) * 0.5);
  37792. };
  37793. //Statics
  37794. EasingFunction._EASINGMODE_EASEIN = 0;
  37795. EasingFunction._EASINGMODE_EASEOUT = 1;
  37796. EasingFunction._EASINGMODE_EASEINOUT = 2;
  37797. return EasingFunction;
  37798. }());
  37799. BABYLON.EasingFunction = EasingFunction;
  37800. var CircleEase = (function (_super) {
  37801. __extends(CircleEase, _super);
  37802. function CircleEase() {
  37803. return _super !== null && _super.apply(this, arguments) || this;
  37804. }
  37805. CircleEase.prototype.easeInCore = function (gradient) {
  37806. gradient = Math.max(0, Math.min(1, gradient));
  37807. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  37808. };
  37809. return CircleEase;
  37810. }(EasingFunction));
  37811. BABYLON.CircleEase = CircleEase;
  37812. var BackEase = (function (_super) {
  37813. __extends(BackEase, _super);
  37814. function BackEase(amplitude) {
  37815. if (amplitude === void 0) { amplitude = 1; }
  37816. var _this = _super.call(this) || this;
  37817. _this.amplitude = amplitude;
  37818. return _this;
  37819. }
  37820. BackEase.prototype.easeInCore = function (gradient) {
  37821. var num = Math.max(0, this.amplitude);
  37822. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  37823. };
  37824. return BackEase;
  37825. }(EasingFunction));
  37826. BABYLON.BackEase = BackEase;
  37827. var BounceEase = (function (_super) {
  37828. __extends(BounceEase, _super);
  37829. function BounceEase(bounces, bounciness) {
  37830. if (bounces === void 0) { bounces = 3; }
  37831. if (bounciness === void 0) { bounciness = 2; }
  37832. var _this = _super.call(this) || this;
  37833. _this.bounces = bounces;
  37834. _this.bounciness = bounciness;
  37835. return _this;
  37836. }
  37837. BounceEase.prototype.easeInCore = function (gradient) {
  37838. var y = Math.max(0.0, this.bounces);
  37839. var bounciness = this.bounciness;
  37840. if (bounciness <= 1.0) {
  37841. bounciness = 1.001;
  37842. }
  37843. var num9 = Math.pow(bounciness, y);
  37844. var num5 = 1.0 - bounciness;
  37845. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  37846. var num15 = gradient * num4;
  37847. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  37848. var num3 = Math.floor(num65);
  37849. var num13 = num3 + 1.0;
  37850. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  37851. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  37852. var num7 = (num8 + num12) * 0.5;
  37853. var num6 = gradient - num7;
  37854. var num2 = num7 - num8;
  37855. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  37856. };
  37857. return BounceEase;
  37858. }(EasingFunction));
  37859. BABYLON.BounceEase = BounceEase;
  37860. var CubicEase = (function (_super) {
  37861. __extends(CubicEase, _super);
  37862. function CubicEase() {
  37863. return _super !== null && _super.apply(this, arguments) || this;
  37864. }
  37865. CubicEase.prototype.easeInCore = function (gradient) {
  37866. return (gradient * gradient * gradient);
  37867. };
  37868. return CubicEase;
  37869. }(EasingFunction));
  37870. BABYLON.CubicEase = CubicEase;
  37871. var ElasticEase = (function (_super) {
  37872. __extends(ElasticEase, _super);
  37873. function ElasticEase(oscillations, springiness) {
  37874. if (oscillations === void 0) { oscillations = 3; }
  37875. if (springiness === void 0) { springiness = 3; }
  37876. var _this = _super.call(this) || this;
  37877. _this.oscillations = oscillations;
  37878. _this.springiness = springiness;
  37879. return _this;
  37880. }
  37881. ElasticEase.prototype.easeInCore = function (gradient) {
  37882. var num2;
  37883. var num3 = Math.max(0.0, this.oscillations);
  37884. var num = Math.max(0.0, this.springiness);
  37885. if (num == 0) {
  37886. num2 = gradient;
  37887. }
  37888. else {
  37889. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  37890. }
  37891. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  37892. };
  37893. return ElasticEase;
  37894. }(EasingFunction));
  37895. BABYLON.ElasticEase = ElasticEase;
  37896. var ExponentialEase = (function (_super) {
  37897. __extends(ExponentialEase, _super);
  37898. function ExponentialEase(exponent) {
  37899. if (exponent === void 0) { exponent = 2; }
  37900. var _this = _super.call(this) || this;
  37901. _this.exponent = exponent;
  37902. return _this;
  37903. }
  37904. ExponentialEase.prototype.easeInCore = function (gradient) {
  37905. if (this.exponent <= 0) {
  37906. return gradient;
  37907. }
  37908. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  37909. };
  37910. return ExponentialEase;
  37911. }(EasingFunction));
  37912. BABYLON.ExponentialEase = ExponentialEase;
  37913. var PowerEase = (function (_super) {
  37914. __extends(PowerEase, _super);
  37915. function PowerEase(power) {
  37916. if (power === void 0) { power = 2; }
  37917. var _this = _super.call(this) || this;
  37918. _this.power = power;
  37919. return _this;
  37920. }
  37921. PowerEase.prototype.easeInCore = function (gradient) {
  37922. var y = Math.max(0.0, this.power);
  37923. return Math.pow(gradient, y);
  37924. };
  37925. return PowerEase;
  37926. }(EasingFunction));
  37927. BABYLON.PowerEase = PowerEase;
  37928. var QuadraticEase = (function (_super) {
  37929. __extends(QuadraticEase, _super);
  37930. function QuadraticEase() {
  37931. return _super !== null && _super.apply(this, arguments) || this;
  37932. }
  37933. QuadraticEase.prototype.easeInCore = function (gradient) {
  37934. return (gradient * gradient);
  37935. };
  37936. return QuadraticEase;
  37937. }(EasingFunction));
  37938. BABYLON.QuadraticEase = QuadraticEase;
  37939. var QuarticEase = (function (_super) {
  37940. __extends(QuarticEase, _super);
  37941. function QuarticEase() {
  37942. return _super !== null && _super.apply(this, arguments) || this;
  37943. }
  37944. QuarticEase.prototype.easeInCore = function (gradient) {
  37945. return (gradient * gradient * gradient * gradient);
  37946. };
  37947. return QuarticEase;
  37948. }(EasingFunction));
  37949. BABYLON.QuarticEase = QuarticEase;
  37950. var QuinticEase = (function (_super) {
  37951. __extends(QuinticEase, _super);
  37952. function QuinticEase() {
  37953. return _super !== null && _super.apply(this, arguments) || this;
  37954. }
  37955. QuinticEase.prototype.easeInCore = function (gradient) {
  37956. return (gradient * gradient * gradient * gradient * gradient);
  37957. };
  37958. return QuinticEase;
  37959. }(EasingFunction));
  37960. BABYLON.QuinticEase = QuinticEase;
  37961. var SineEase = (function (_super) {
  37962. __extends(SineEase, _super);
  37963. function SineEase() {
  37964. return _super !== null && _super.apply(this, arguments) || this;
  37965. }
  37966. SineEase.prototype.easeInCore = function (gradient) {
  37967. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  37968. };
  37969. return SineEase;
  37970. }(EasingFunction));
  37971. BABYLON.SineEase = SineEase;
  37972. var BezierCurveEase = (function (_super) {
  37973. __extends(BezierCurveEase, _super);
  37974. function BezierCurveEase(x1, y1, x2, y2) {
  37975. if (x1 === void 0) { x1 = 0; }
  37976. if (y1 === void 0) { y1 = 0; }
  37977. if (x2 === void 0) { x2 = 1; }
  37978. if (y2 === void 0) { y2 = 1; }
  37979. var _this = _super.call(this) || this;
  37980. _this.x1 = x1;
  37981. _this.y1 = y1;
  37982. _this.x2 = x2;
  37983. _this.y2 = y2;
  37984. return _this;
  37985. }
  37986. BezierCurveEase.prototype.easeInCore = function (gradient) {
  37987. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  37988. };
  37989. return BezierCurveEase;
  37990. }(EasingFunction));
  37991. BABYLON.BezierCurveEase = BezierCurveEase;
  37992. })(BABYLON || (BABYLON = {}));
  37993. //# sourceMappingURL=babylon.easing.js.map
  37994. var BABYLON;
  37995. (function (BABYLON) {
  37996. var Condition = (function () {
  37997. function Condition(actionManager) {
  37998. this._actionManager = actionManager;
  37999. }
  38000. Condition.prototype.isValid = function () {
  38001. return true;
  38002. };
  38003. Condition.prototype._getProperty = function (propertyPath) {
  38004. return this._actionManager._getProperty(propertyPath);
  38005. };
  38006. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38007. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38008. };
  38009. Condition.prototype.serialize = function () {
  38010. };
  38011. Condition.prototype._serialize = function (serializedCondition) {
  38012. return {
  38013. type: 2,
  38014. children: [],
  38015. name: serializedCondition.name,
  38016. properties: serializedCondition.properties
  38017. };
  38018. };
  38019. return Condition;
  38020. }());
  38021. BABYLON.Condition = Condition;
  38022. var ValueCondition = (function (_super) {
  38023. __extends(ValueCondition, _super);
  38024. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38025. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38026. var _this = _super.call(this, actionManager) || this;
  38027. _this.propertyPath = propertyPath;
  38028. _this.value = value;
  38029. _this.operator = operator;
  38030. _this._target = target;
  38031. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38032. _this._property = _this._getProperty(_this.propertyPath);
  38033. return _this;
  38034. }
  38035. Object.defineProperty(ValueCondition, "IsEqual", {
  38036. get: function () {
  38037. return ValueCondition._IsEqual;
  38038. },
  38039. enumerable: true,
  38040. configurable: true
  38041. });
  38042. Object.defineProperty(ValueCondition, "IsDifferent", {
  38043. get: function () {
  38044. return ValueCondition._IsDifferent;
  38045. },
  38046. enumerable: true,
  38047. configurable: true
  38048. });
  38049. Object.defineProperty(ValueCondition, "IsGreater", {
  38050. get: function () {
  38051. return ValueCondition._IsGreater;
  38052. },
  38053. enumerable: true,
  38054. configurable: true
  38055. });
  38056. Object.defineProperty(ValueCondition, "IsLesser", {
  38057. get: function () {
  38058. return ValueCondition._IsLesser;
  38059. },
  38060. enumerable: true,
  38061. configurable: true
  38062. });
  38063. // Methods
  38064. ValueCondition.prototype.isValid = function () {
  38065. switch (this.operator) {
  38066. case ValueCondition.IsGreater:
  38067. return this._effectiveTarget[this._property] > this.value;
  38068. case ValueCondition.IsLesser:
  38069. return this._effectiveTarget[this._property] < this.value;
  38070. case ValueCondition.IsEqual:
  38071. case ValueCondition.IsDifferent:
  38072. var check;
  38073. if (this.value.equals) {
  38074. check = this.value.equals(this._effectiveTarget[this._property]);
  38075. }
  38076. else {
  38077. check = this.value === this._effectiveTarget[this._property];
  38078. }
  38079. return this.operator === ValueCondition.IsEqual ? check : !check;
  38080. }
  38081. return false;
  38082. };
  38083. ValueCondition.prototype.serialize = function () {
  38084. return this._serialize({
  38085. name: "ValueCondition",
  38086. properties: [
  38087. BABYLON.Action._GetTargetProperty(this._target),
  38088. { name: "propertyPath", value: this.propertyPath },
  38089. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38090. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38091. ]
  38092. });
  38093. };
  38094. ValueCondition.GetOperatorName = function (operator) {
  38095. switch (operator) {
  38096. case ValueCondition._IsEqual: return "IsEqual";
  38097. case ValueCondition._IsDifferent: return "IsDifferent";
  38098. case ValueCondition._IsGreater: return "IsGreater";
  38099. case ValueCondition._IsLesser: return "IsLesser";
  38100. default: return "";
  38101. }
  38102. };
  38103. // Statics
  38104. ValueCondition._IsEqual = 0;
  38105. ValueCondition._IsDifferent = 1;
  38106. ValueCondition._IsGreater = 2;
  38107. ValueCondition._IsLesser = 3;
  38108. return ValueCondition;
  38109. }(Condition));
  38110. BABYLON.ValueCondition = ValueCondition;
  38111. var PredicateCondition = (function (_super) {
  38112. __extends(PredicateCondition, _super);
  38113. function PredicateCondition(actionManager, predicate) {
  38114. var _this = _super.call(this, actionManager) || this;
  38115. _this.predicate = predicate;
  38116. return _this;
  38117. }
  38118. PredicateCondition.prototype.isValid = function () {
  38119. return this.predicate();
  38120. };
  38121. return PredicateCondition;
  38122. }(Condition));
  38123. BABYLON.PredicateCondition = PredicateCondition;
  38124. var StateCondition = (function (_super) {
  38125. __extends(StateCondition, _super);
  38126. function StateCondition(actionManager, target, value) {
  38127. var _this = _super.call(this, actionManager) || this;
  38128. _this.value = value;
  38129. _this._target = target;
  38130. return _this;
  38131. }
  38132. // Methods
  38133. StateCondition.prototype.isValid = function () {
  38134. return this._target.state === this.value;
  38135. };
  38136. StateCondition.prototype.serialize = function () {
  38137. return this._serialize({
  38138. name: "StateCondition",
  38139. properties: [
  38140. BABYLON.Action._GetTargetProperty(this._target),
  38141. { name: "value", value: this.value }
  38142. ]
  38143. });
  38144. };
  38145. return StateCondition;
  38146. }(Condition));
  38147. BABYLON.StateCondition = StateCondition;
  38148. })(BABYLON || (BABYLON = {}));
  38149. //# sourceMappingURL=babylon.condition.js.map
  38150. var BABYLON;
  38151. (function (BABYLON) {
  38152. var Action = (function () {
  38153. function Action(triggerOptions, condition) {
  38154. this.triggerOptions = triggerOptions;
  38155. if (triggerOptions.parameter) {
  38156. this.trigger = triggerOptions.trigger;
  38157. this._triggerParameter = triggerOptions.parameter;
  38158. }
  38159. else {
  38160. this.trigger = triggerOptions;
  38161. }
  38162. this._nextActiveAction = this;
  38163. this._condition = condition;
  38164. }
  38165. // Methods
  38166. Action.prototype._prepare = function () {
  38167. };
  38168. Action.prototype.getTriggerParameter = function () {
  38169. return this._triggerParameter;
  38170. };
  38171. Action.prototype._executeCurrent = function (evt) {
  38172. if (this._nextActiveAction._condition) {
  38173. var condition = this._nextActiveAction._condition;
  38174. var currentRenderId = this._actionManager.getScene().getRenderId();
  38175. // We cache the current evaluation for the current frame
  38176. if (condition._evaluationId === currentRenderId) {
  38177. if (!condition._currentResult) {
  38178. return;
  38179. }
  38180. }
  38181. else {
  38182. condition._evaluationId = currentRenderId;
  38183. if (!condition.isValid()) {
  38184. condition._currentResult = false;
  38185. return;
  38186. }
  38187. condition._currentResult = true;
  38188. }
  38189. }
  38190. this._nextActiveAction.execute(evt);
  38191. this.skipToNextActiveAction();
  38192. };
  38193. Action.prototype.execute = function (evt) {
  38194. };
  38195. Action.prototype.skipToNextActiveAction = function () {
  38196. if (this._nextActiveAction._child) {
  38197. if (!this._nextActiveAction._child._actionManager) {
  38198. this._nextActiveAction._child._actionManager = this._actionManager;
  38199. }
  38200. this._nextActiveAction = this._nextActiveAction._child;
  38201. }
  38202. else {
  38203. this._nextActiveAction = this;
  38204. }
  38205. };
  38206. Action.prototype.then = function (action) {
  38207. this._child = action;
  38208. action._actionManager = this._actionManager;
  38209. action._prepare();
  38210. return action;
  38211. };
  38212. Action.prototype._getProperty = function (propertyPath) {
  38213. return this._actionManager._getProperty(propertyPath);
  38214. };
  38215. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38216. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38217. };
  38218. Action.prototype.serialize = function (parent) {
  38219. };
  38220. // Called by BABYLON.Action objects in serialize(...). Internal use
  38221. Action.prototype._serialize = function (serializedAction, parent) {
  38222. var serializationObject = {
  38223. type: 1,
  38224. children: [],
  38225. name: serializedAction.name,
  38226. properties: serializedAction.properties || []
  38227. };
  38228. // Serialize child
  38229. if (this._child) {
  38230. this._child.serialize(serializationObject);
  38231. }
  38232. // Check if "this" has a condition
  38233. if (this._condition) {
  38234. var serializedCondition = this._condition.serialize();
  38235. serializedCondition.children.push(serializationObject);
  38236. if (parent) {
  38237. parent.children.push(serializedCondition);
  38238. }
  38239. return serializedCondition;
  38240. }
  38241. if (parent) {
  38242. parent.children.push(serializationObject);
  38243. }
  38244. return serializationObject;
  38245. };
  38246. Action._SerializeValueAsString = function (value) {
  38247. if (typeof value === "number") {
  38248. return value.toString();
  38249. }
  38250. if (typeof value === "boolean") {
  38251. return value ? "true" : "false";
  38252. }
  38253. if (value instanceof BABYLON.Vector2) {
  38254. return value.x + ", " + value.y;
  38255. }
  38256. if (value instanceof BABYLON.Vector3) {
  38257. return value.x + ", " + value.y + ", " + value.z;
  38258. }
  38259. if (value instanceof BABYLON.Color3) {
  38260. return value.r + ", " + value.g + ", " + value.b;
  38261. }
  38262. if (value instanceof BABYLON.Color4) {
  38263. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38264. }
  38265. return value; // string
  38266. };
  38267. Action._GetTargetProperty = function (target) {
  38268. return {
  38269. name: "target",
  38270. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38271. : target instanceof BABYLON.Light ? "LightProperties"
  38272. : target instanceof BABYLON.Camera ? "CameraProperties"
  38273. : "SceneProperties",
  38274. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38275. };
  38276. };
  38277. return Action;
  38278. }());
  38279. BABYLON.Action = Action;
  38280. })(BABYLON || (BABYLON = {}));
  38281. //# sourceMappingURL=babylon.action.js.map
  38282. var BABYLON;
  38283. (function (BABYLON) {
  38284. /**
  38285. * ActionEvent is the event beint sent when an action is triggered.
  38286. */
  38287. var ActionEvent = (function () {
  38288. /**
  38289. * @param source The mesh or sprite that triggered the action.
  38290. * @param pointerX The X mouse cursor position at the time of the event
  38291. * @param pointerY The Y mouse cursor position at the time of the event
  38292. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38293. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38294. */
  38295. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38296. this.source = source;
  38297. this.pointerX = pointerX;
  38298. this.pointerY = pointerY;
  38299. this.meshUnderPointer = meshUnderPointer;
  38300. this.sourceEvent = sourceEvent;
  38301. this.additionalData = additionalData;
  38302. }
  38303. /**
  38304. * Helper function to auto-create an ActionEvent from a source mesh.
  38305. * @param source The source mesh that triggered the event
  38306. * @param evt {Event} The original (browser) event
  38307. */
  38308. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38309. var scene = source.getScene();
  38310. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38311. };
  38312. /**
  38313. * Helper function to auto-create an ActionEvent from a source mesh.
  38314. * @param source The source sprite that triggered the event
  38315. * @param scene Scene associated with the sprite
  38316. * @param evt {Event} The original (browser) event
  38317. */
  38318. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38319. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38320. };
  38321. /**
  38322. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38323. * @param scene the scene where the event occurred
  38324. * @param evt {Event} The original (browser) event
  38325. */
  38326. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38327. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38328. };
  38329. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38330. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38331. };
  38332. return ActionEvent;
  38333. }());
  38334. BABYLON.ActionEvent = ActionEvent;
  38335. /**
  38336. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38337. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38338. */
  38339. var ActionManager = (function () {
  38340. function ActionManager(scene) {
  38341. // Members
  38342. this.actions = new Array();
  38343. this.hoverCursor = '';
  38344. this._scene = scene;
  38345. scene._actionManagers.push(this);
  38346. }
  38347. Object.defineProperty(ActionManager, "NothingTrigger", {
  38348. get: function () {
  38349. return ActionManager._NothingTrigger;
  38350. },
  38351. enumerable: true,
  38352. configurable: true
  38353. });
  38354. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38355. get: function () {
  38356. return ActionManager._OnPickTrigger;
  38357. },
  38358. enumerable: true,
  38359. configurable: true
  38360. });
  38361. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38362. get: function () {
  38363. return ActionManager._OnLeftPickTrigger;
  38364. },
  38365. enumerable: true,
  38366. configurable: true
  38367. });
  38368. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38369. get: function () {
  38370. return ActionManager._OnRightPickTrigger;
  38371. },
  38372. enumerable: true,
  38373. configurable: true
  38374. });
  38375. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38376. get: function () {
  38377. return ActionManager._OnCenterPickTrigger;
  38378. },
  38379. enumerable: true,
  38380. configurable: true
  38381. });
  38382. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38383. get: function () {
  38384. return ActionManager._OnPickDownTrigger;
  38385. },
  38386. enumerable: true,
  38387. configurable: true
  38388. });
  38389. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  38390. get: function () {
  38391. return ActionManager._OnDoublePickTrigger;
  38392. },
  38393. enumerable: true,
  38394. configurable: true
  38395. });
  38396. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38397. get: function () {
  38398. return ActionManager._OnPickUpTrigger;
  38399. },
  38400. enumerable: true,
  38401. configurable: true
  38402. });
  38403. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38404. /// This trigger will only be raised if you also declared a OnPickDown
  38405. get: function () {
  38406. return ActionManager._OnPickOutTrigger;
  38407. },
  38408. enumerable: true,
  38409. configurable: true
  38410. });
  38411. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38412. get: function () {
  38413. return ActionManager._OnLongPressTrigger;
  38414. },
  38415. enumerable: true,
  38416. configurable: true
  38417. });
  38418. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38419. get: function () {
  38420. return ActionManager._OnPointerOverTrigger;
  38421. },
  38422. enumerable: true,
  38423. configurable: true
  38424. });
  38425. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38426. get: function () {
  38427. return ActionManager._OnPointerOutTrigger;
  38428. },
  38429. enumerable: true,
  38430. configurable: true
  38431. });
  38432. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38433. get: function () {
  38434. return ActionManager._OnEveryFrameTrigger;
  38435. },
  38436. enumerable: true,
  38437. configurable: true
  38438. });
  38439. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38440. get: function () {
  38441. return ActionManager._OnIntersectionEnterTrigger;
  38442. },
  38443. enumerable: true,
  38444. configurable: true
  38445. });
  38446. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38447. get: function () {
  38448. return ActionManager._OnIntersectionExitTrigger;
  38449. },
  38450. enumerable: true,
  38451. configurable: true
  38452. });
  38453. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38454. get: function () {
  38455. return ActionManager._OnKeyDownTrigger;
  38456. },
  38457. enumerable: true,
  38458. configurable: true
  38459. });
  38460. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38461. get: function () {
  38462. return ActionManager._OnKeyUpTrigger;
  38463. },
  38464. enumerable: true,
  38465. configurable: true
  38466. });
  38467. // Methods
  38468. ActionManager.prototype.dispose = function () {
  38469. var index = this._scene._actionManagers.indexOf(this);
  38470. for (var i = 0; i < this.actions.length; i++) {
  38471. var action = this.actions[i];
  38472. ActionManager.Triggers[action.trigger]--;
  38473. if (ActionManager.Triggers[action.trigger] === 0) {
  38474. delete ActionManager.Triggers[action.trigger];
  38475. }
  38476. }
  38477. if (index > -1) {
  38478. this._scene._actionManagers.splice(index, 1);
  38479. }
  38480. };
  38481. ActionManager.prototype.getScene = function () {
  38482. return this._scene;
  38483. };
  38484. /**
  38485. * Does this action manager handles actions of any of the given triggers
  38486. * @param {number[]} triggers - the triggers to be tested
  38487. * @return {boolean} whether one (or more) of the triggers is handeled
  38488. */
  38489. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38490. for (var index = 0; index < this.actions.length; index++) {
  38491. var action = this.actions[index];
  38492. if (triggers.indexOf(action.trigger) > -1) {
  38493. return true;
  38494. }
  38495. }
  38496. return false;
  38497. };
  38498. /**
  38499. * Does this action manager handles actions of a given trigger
  38500. * @param {number} trigger - the trigger to be tested
  38501. * @return {boolean} whether the trigger is handeled
  38502. */
  38503. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38504. for (var index = 0; index < this.actions.length; index++) {
  38505. var action = this.actions[index];
  38506. if (action.trigger === trigger) {
  38507. return true;
  38508. }
  38509. }
  38510. return false;
  38511. };
  38512. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38513. /**
  38514. * Does this action manager has pointer triggers
  38515. * @return {boolean} whether or not it has pointer triggers
  38516. */
  38517. get: function () {
  38518. for (var index = 0; index < this.actions.length; index++) {
  38519. var action = this.actions[index];
  38520. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38521. return true;
  38522. }
  38523. }
  38524. return false;
  38525. },
  38526. enumerable: true,
  38527. configurable: true
  38528. });
  38529. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38530. /**
  38531. * Does this action manager has pick triggers
  38532. * @return {boolean} whether or not it has pick triggers
  38533. */
  38534. get: function () {
  38535. for (var index = 0; index < this.actions.length; index++) {
  38536. var action = this.actions[index];
  38537. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38538. return true;
  38539. }
  38540. }
  38541. return false;
  38542. },
  38543. enumerable: true,
  38544. configurable: true
  38545. });
  38546. Object.defineProperty(ActionManager, "HasTriggers", {
  38547. /**
  38548. * Does exist one action manager with at least one trigger
  38549. * @return {boolean} whether or not it exists one action manager with one trigger
  38550. **/
  38551. get: function () {
  38552. for (var t in ActionManager.Triggers) {
  38553. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38554. return true;
  38555. }
  38556. }
  38557. return false;
  38558. },
  38559. enumerable: true,
  38560. configurable: true
  38561. });
  38562. Object.defineProperty(ActionManager, "HasPickTriggers", {
  38563. /**
  38564. * Does exist one action manager with at least one pick trigger
  38565. * @return {boolean} whether or not it exists one action manager with one pick trigger
  38566. **/
  38567. get: function () {
  38568. for (var t in ActionManager.Triggers) {
  38569. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38570. var t_int = parseInt(t);
  38571. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  38572. return true;
  38573. }
  38574. }
  38575. }
  38576. return false;
  38577. },
  38578. enumerable: true,
  38579. configurable: true
  38580. });
  38581. /**
  38582. * Does exist one action manager that handles actions of a given trigger
  38583. * @param {number} trigger - the trigger to be tested
  38584. * @return {boolean} whether the trigger is handeled by at least one action manager
  38585. **/
  38586. ActionManager.HasSpecificTrigger = function (trigger) {
  38587. for (var t in ActionManager.Triggers) {
  38588. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38589. var t_int = parseInt(t);
  38590. if (t_int === trigger) {
  38591. return true;
  38592. }
  38593. }
  38594. }
  38595. return false;
  38596. };
  38597. /**
  38598. * Registers an action to this action manager
  38599. * @param {BABYLON.Action} action - the action to be registered
  38600. * @return {BABYLON.Action} the action amended (prepared) after registration
  38601. */
  38602. ActionManager.prototype.registerAction = function (action) {
  38603. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38604. if (this.getScene().actionManager !== this) {
  38605. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38606. return null;
  38607. }
  38608. }
  38609. this.actions.push(action);
  38610. if (ActionManager.Triggers[action.trigger]) {
  38611. ActionManager.Triggers[action.trigger]++;
  38612. }
  38613. else {
  38614. ActionManager.Triggers[action.trigger] = 1;
  38615. }
  38616. action._actionManager = this;
  38617. action._prepare();
  38618. return action;
  38619. };
  38620. /**
  38621. * Process a specific trigger
  38622. * @param {number} trigger - the trigger to process
  38623. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38624. */
  38625. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38626. for (var index = 0; index < this.actions.length; index++) {
  38627. var action = this.actions[index];
  38628. if (action.trigger === trigger) {
  38629. if (trigger === ActionManager.OnKeyUpTrigger
  38630. || trigger === ActionManager.OnKeyDownTrigger) {
  38631. var parameter = action.getTriggerParameter();
  38632. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38633. if (!parameter.toLowerCase) {
  38634. continue;
  38635. }
  38636. var lowerCase = parameter.toLowerCase();
  38637. if (lowerCase !== evt.sourceEvent.key) {
  38638. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38639. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38640. if (actualkey !== lowerCase) {
  38641. continue;
  38642. }
  38643. }
  38644. }
  38645. }
  38646. action._executeCurrent(evt);
  38647. }
  38648. }
  38649. };
  38650. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38651. var properties = propertyPath.split(".");
  38652. for (var index = 0; index < properties.length - 1; index++) {
  38653. target = target[properties[index]];
  38654. }
  38655. return target;
  38656. };
  38657. ActionManager.prototype._getProperty = function (propertyPath) {
  38658. var properties = propertyPath.split(".");
  38659. return properties[properties.length - 1];
  38660. };
  38661. ActionManager.prototype.serialize = function (name) {
  38662. var root = {
  38663. children: [],
  38664. name: name,
  38665. type: 3,
  38666. properties: [] // Empty for root but required
  38667. };
  38668. for (var i = 0; i < this.actions.length; i++) {
  38669. var triggerObject = {
  38670. type: 0,
  38671. children: [],
  38672. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38673. properties: []
  38674. };
  38675. var triggerOptions = this.actions[i].triggerOptions;
  38676. if (triggerOptions && typeof triggerOptions !== "number") {
  38677. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38678. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38679. }
  38680. else {
  38681. var parameter = {};
  38682. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38683. if (triggerOptions.parameter.mesh) {
  38684. parameter._meshId = triggerOptions.parameter.mesh.id;
  38685. }
  38686. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38687. }
  38688. }
  38689. // Serialize child action, recursively
  38690. this.actions[i].serialize(triggerObject);
  38691. // Add serialized trigger
  38692. root.children.push(triggerObject);
  38693. }
  38694. return root;
  38695. };
  38696. ActionManager.Parse = function (parsedActions, object, scene) {
  38697. var actionManager = new BABYLON.ActionManager(scene);
  38698. if (object === null)
  38699. scene.actionManager = actionManager;
  38700. else
  38701. object.actionManager = actionManager;
  38702. // instanciate a new object
  38703. var instanciate = function (name, params) {
  38704. var newInstance = Object.create(BABYLON[name].prototype);
  38705. newInstance.constructor.apply(newInstance, params);
  38706. return newInstance;
  38707. };
  38708. var parseParameter = function (name, value, target, propertyPath) {
  38709. if (propertyPath === null) {
  38710. // String, boolean or float
  38711. var floatValue = parseFloat(value);
  38712. if (value === "true" || value === "false")
  38713. return value === "true";
  38714. else
  38715. return isNaN(floatValue) ? value : floatValue;
  38716. }
  38717. var effectiveTarget = propertyPath.split(".");
  38718. var values = value.split(",");
  38719. // Get effective Target
  38720. for (var i = 0; i < effectiveTarget.length; i++) {
  38721. target = target[effectiveTarget[i]];
  38722. }
  38723. // Return appropriate value with its type
  38724. if (typeof (target) === "boolean")
  38725. return values[0] === "true";
  38726. if (typeof (target) === "string")
  38727. return values[0];
  38728. // Parameters with multiple values such as Vector3 etc.
  38729. var split = new Array();
  38730. for (var i = 0; i < values.length; i++)
  38731. split.push(parseFloat(values[i]));
  38732. if (target instanceof BABYLON.Vector3)
  38733. return BABYLON.Vector3.FromArray(split);
  38734. if (target instanceof BABYLON.Vector4)
  38735. return BABYLON.Vector4.FromArray(split);
  38736. if (target instanceof BABYLON.Color3)
  38737. return BABYLON.Color3.FromArray(split);
  38738. if (target instanceof BABYLON.Color4)
  38739. return BABYLON.Color4.FromArray(split);
  38740. return parseFloat(values[0]);
  38741. };
  38742. // traverse graph per trigger
  38743. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38744. if (combineArray === void 0) { combineArray = null; }
  38745. if (parsedAction.detached)
  38746. return;
  38747. var parameters = new Array();
  38748. var target = null;
  38749. var propertyPath = null;
  38750. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38751. // Parameters
  38752. if (parsedAction.type === 2)
  38753. parameters.push(actionManager);
  38754. else
  38755. parameters.push(trigger);
  38756. if (combine) {
  38757. var actions = new Array();
  38758. for (var j = 0; j < parsedAction.combine.length; j++) {
  38759. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38760. }
  38761. parameters.push(actions);
  38762. }
  38763. else {
  38764. for (var i = 0; i < parsedAction.properties.length; i++) {
  38765. var value = parsedAction.properties[i].value;
  38766. var name = parsedAction.properties[i].name;
  38767. var targetType = parsedAction.properties[i].targetType;
  38768. if (name === "target")
  38769. if (targetType !== null && targetType === "SceneProperties")
  38770. value = target = scene;
  38771. else
  38772. value = target = scene.getNodeByName(value);
  38773. else if (name === "parent")
  38774. value = scene.getNodeByName(value);
  38775. else if (name === "sound")
  38776. value = scene.getSoundByName(value);
  38777. else if (name !== "propertyPath") {
  38778. if (parsedAction.type === 2 && name === "operator")
  38779. value = BABYLON.ValueCondition[value];
  38780. else
  38781. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38782. }
  38783. else {
  38784. propertyPath = value;
  38785. }
  38786. parameters.push(value);
  38787. }
  38788. }
  38789. if (combineArray === null) {
  38790. parameters.push(condition);
  38791. }
  38792. else {
  38793. parameters.push(null);
  38794. }
  38795. // If interpolate value action
  38796. if (parsedAction.name === "InterpolateValueAction") {
  38797. var param = parameters[parameters.length - 2];
  38798. parameters[parameters.length - 1] = param;
  38799. parameters[parameters.length - 2] = condition;
  38800. }
  38801. // Action or condition(s) and not CombineAction
  38802. var newAction = instanciate(parsedAction.name, parameters);
  38803. if (newAction instanceof BABYLON.Condition && condition !== null) {
  38804. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  38805. if (action)
  38806. action.then(nothing);
  38807. else
  38808. actionManager.registerAction(nothing);
  38809. action = nothing;
  38810. }
  38811. if (combineArray === null) {
  38812. if (newAction instanceof BABYLON.Condition) {
  38813. condition = newAction;
  38814. newAction = action;
  38815. }
  38816. else {
  38817. condition = null;
  38818. if (action)
  38819. action.then(newAction);
  38820. else
  38821. actionManager.registerAction(newAction);
  38822. }
  38823. }
  38824. else {
  38825. combineArray.push(newAction);
  38826. }
  38827. for (var i = 0; i < parsedAction.children.length; i++)
  38828. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  38829. };
  38830. // triggers
  38831. for (var i = 0; i < parsedActions.children.length; i++) {
  38832. var triggerParams;
  38833. var trigger = parsedActions.children[i];
  38834. if (trigger.properties.length > 0) {
  38835. var param = trigger.properties[0].value;
  38836. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  38837. if (value._meshId) {
  38838. value.mesh = scene.getMeshByID(value._meshId);
  38839. }
  38840. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  38841. }
  38842. else
  38843. triggerParams = BABYLON.ActionManager[trigger.name];
  38844. for (var j = 0; j < trigger.children.length; j++) {
  38845. if (!trigger.detached)
  38846. traverse(trigger.children[j], triggerParams, null, null);
  38847. }
  38848. }
  38849. };
  38850. ActionManager.GetTriggerName = function (trigger) {
  38851. switch (trigger) {
  38852. case 0: return "NothingTrigger";
  38853. case 1: return "OnPickTrigger";
  38854. case 2: return "OnLeftPickTrigger";
  38855. case 3: return "OnRightPickTrigger";
  38856. case 4: return "OnCenterPickTrigger";
  38857. case 5: return "OnPickDownTrigger";
  38858. case 6: return "OnPickUpTrigger";
  38859. case 7: return "OnLongPressTrigger";
  38860. case 8: return "OnPointerOverTrigger";
  38861. case 9: return "OnPointerOutTrigger";
  38862. case 10: return "OnEveryFrameTrigger";
  38863. case 11: return "OnIntersectionEnterTrigger";
  38864. case 12: return "OnIntersectionExitTrigger";
  38865. case 13: return "OnKeyDownTrigger";
  38866. case 14: return "OnKeyUpTrigger";
  38867. case 15: return "OnPickOutTrigger";
  38868. default: return "";
  38869. }
  38870. };
  38871. // Statics
  38872. ActionManager._NothingTrigger = 0;
  38873. ActionManager._OnPickTrigger = 1;
  38874. ActionManager._OnLeftPickTrigger = 2;
  38875. ActionManager._OnRightPickTrigger = 3;
  38876. ActionManager._OnCenterPickTrigger = 4;
  38877. ActionManager._OnPickDownTrigger = 5;
  38878. ActionManager._OnDoublePickTrigger = 6;
  38879. ActionManager._OnPickUpTrigger = 7;
  38880. ActionManager._OnLongPressTrigger = 8;
  38881. ActionManager._OnPointerOverTrigger = 9;
  38882. ActionManager._OnPointerOutTrigger = 10;
  38883. ActionManager._OnEveryFrameTrigger = 11;
  38884. ActionManager._OnIntersectionEnterTrigger = 12;
  38885. ActionManager._OnIntersectionExitTrigger = 13;
  38886. ActionManager._OnKeyDownTrigger = 14;
  38887. ActionManager._OnKeyUpTrigger = 15;
  38888. ActionManager._OnPickOutTrigger = 16;
  38889. ActionManager.Triggers = {};
  38890. return ActionManager;
  38891. }());
  38892. BABYLON.ActionManager = ActionManager;
  38893. })(BABYLON || (BABYLON = {}));
  38894. //# sourceMappingURL=babylon.actionManager.js.map
  38895. var BABYLON;
  38896. (function (BABYLON) {
  38897. var InterpolateValueAction = (function (_super) {
  38898. __extends(InterpolateValueAction, _super);
  38899. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  38900. if (duration === void 0) { duration = 1000; }
  38901. var _this = _super.call(this, triggerOptions, condition) || this;
  38902. _this.propertyPath = propertyPath;
  38903. _this.value = value;
  38904. _this.duration = duration;
  38905. _this.stopOtherAnimations = stopOtherAnimations;
  38906. _this.onInterpolationDone = onInterpolationDone;
  38907. _this._target = _this._effectiveTarget = target;
  38908. return _this;
  38909. }
  38910. InterpolateValueAction.prototype._prepare = function () {
  38911. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38912. this._property = this._getProperty(this.propertyPath);
  38913. };
  38914. InterpolateValueAction.prototype.execute = function () {
  38915. var scene = this._actionManager.getScene();
  38916. var keys = [
  38917. {
  38918. frame: 0,
  38919. value: this._effectiveTarget[this._property]
  38920. }, {
  38921. frame: 100,
  38922. value: this.value
  38923. }
  38924. ];
  38925. var dataType;
  38926. if (typeof this.value === "number") {
  38927. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  38928. }
  38929. else if (this.value instanceof BABYLON.Color3) {
  38930. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  38931. }
  38932. else if (this.value instanceof BABYLON.Vector3) {
  38933. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  38934. }
  38935. else if (this.value instanceof BABYLON.Matrix) {
  38936. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  38937. }
  38938. else if (this.value instanceof BABYLON.Quaternion) {
  38939. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  38940. }
  38941. else {
  38942. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  38943. return;
  38944. }
  38945. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  38946. animation.setKeys(keys);
  38947. if (this.stopOtherAnimations) {
  38948. scene.stopAnimation(this._effectiveTarget);
  38949. }
  38950. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  38951. };
  38952. InterpolateValueAction.prototype.serialize = function (parent) {
  38953. return _super.prototype._serialize.call(this, {
  38954. name: "InterpolateValueAction",
  38955. properties: [
  38956. BABYLON.Action._GetTargetProperty(this._target),
  38957. { name: "propertyPath", value: this.propertyPath },
  38958. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38959. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  38960. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  38961. ]
  38962. }, parent);
  38963. };
  38964. return InterpolateValueAction;
  38965. }(BABYLON.Action));
  38966. BABYLON.InterpolateValueAction = InterpolateValueAction;
  38967. })(BABYLON || (BABYLON = {}));
  38968. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  38969. var BABYLON;
  38970. (function (BABYLON) {
  38971. var SwitchBooleanAction = (function (_super) {
  38972. __extends(SwitchBooleanAction, _super);
  38973. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  38974. var _this = _super.call(this, triggerOptions, condition) || this;
  38975. _this.propertyPath = propertyPath;
  38976. _this._target = _this._effectiveTarget = target;
  38977. return _this;
  38978. }
  38979. SwitchBooleanAction.prototype._prepare = function () {
  38980. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38981. this._property = this._getProperty(this.propertyPath);
  38982. };
  38983. SwitchBooleanAction.prototype.execute = function () {
  38984. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  38985. };
  38986. SwitchBooleanAction.prototype.serialize = function (parent) {
  38987. return _super.prototype._serialize.call(this, {
  38988. name: "SwitchBooleanAction",
  38989. properties: [
  38990. BABYLON.Action._GetTargetProperty(this._target),
  38991. { name: "propertyPath", value: this.propertyPath }
  38992. ]
  38993. }, parent);
  38994. };
  38995. return SwitchBooleanAction;
  38996. }(BABYLON.Action));
  38997. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  38998. var SetStateAction = (function (_super) {
  38999. __extends(SetStateAction, _super);
  39000. function SetStateAction(triggerOptions, target, value, condition) {
  39001. var _this = _super.call(this, triggerOptions, condition) || this;
  39002. _this.value = value;
  39003. _this._target = target;
  39004. return _this;
  39005. }
  39006. SetStateAction.prototype.execute = function () {
  39007. this._target.state = this.value;
  39008. };
  39009. SetStateAction.prototype.serialize = function (parent) {
  39010. return _super.prototype._serialize.call(this, {
  39011. name: "SetStateAction",
  39012. properties: [
  39013. BABYLON.Action._GetTargetProperty(this._target),
  39014. { name: "value", value: this.value }
  39015. ]
  39016. }, parent);
  39017. };
  39018. return SetStateAction;
  39019. }(BABYLON.Action));
  39020. BABYLON.SetStateAction = SetStateAction;
  39021. var SetValueAction = (function (_super) {
  39022. __extends(SetValueAction, _super);
  39023. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39024. var _this = _super.call(this, triggerOptions, condition) || this;
  39025. _this.propertyPath = propertyPath;
  39026. _this.value = value;
  39027. _this._target = _this._effectiveTarget = target;
  39028. return _this;
  39029. }
  39030. SetValueAction.prototype._prepare = function () {
  39031. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39032. this._property = this._getProperty(this.propertyPath);
  39033. };
  39034. SetValueAction.prototype.execute = function () {
  39035. this._effectiveTarget[this._property] = this.value;
  39036. if (this._target.markAsDirty) {
  39037. this._target.markAsDirty(this._property);
  39038. }
  39039. };
  39040. SetValueAction.prototype.serialize = function (parent) {
  39041. return _super.prototype._serialize.call(this, {
  39042. name: "SetValueAction",
  39043. properties: [
  39044. BABYLON.Action._GetTargetProperty(this._target),
  39045. { name: "propertyPath", value: this.propertyPath },
  39046. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39047. ]
  39048. }, parent);
  39049. };
  39050. return SetValueAction;
  39051. }(BABYLON.Action));
  39052. BABYLON.SetValueAction = SetValueAction;
  39053. var IncrementValueAction = (function (_super) {
  39054. __extends(IncrementValueAction, _super);
  39055. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39056. var _this = _super.call(this, triggerOptions, condition) || this;
  39057. _this.propertyPath = propertyPath;
  39058. _this.value = value;
  39059. _this._target = _this._effectiveTarget = target;
  39060. return _this;
  39061. }
  39062. IncrementValueAction.prototype._prepare = function () {
  39063. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39064. this._property = this._getProperty(this.propertyPath);
  39065. if (typeof this._effectiveTarget[this._property] !== "number") {
  39066. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39067. }
  39068. };
  39069. IncrementValueAction.prototype.execute = function () {
  39070. this._effectiveTarget[this._property] += this.value;
  39071. if (this._target.markAsDirty) {
  39072. this._target.markAsDirty(this._property);
  39073. }
  39074. };
  39075. IncrementValueAction.prototype.serialize = function (parent) {
  39076. return _super.prototype._serialize.call(this, {
  39077. name: "IncrementValueAction",
  39078. properties: [
  39079. BABYLON.Action._GetTargetProperty(this._target),
  39080. { name: "propertyPath", value: this.propertyPath },
  39081. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39082. ]
  39083. }, parent);
  39084. };
  39085. return IncrementValueAction;
  39086. }(BABYLON.Action));
  39087. BABYLON.IncrementValueAction = IncrementValueAction;
  39088. var PlayAnimationAction = (function (_super) {
  39089. __extends(PlayAnimationAction, _super);
  39090. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39091. var _this = _super.call(this, triggerOptions, condition) || this;
  39092. _this.from = from;
  39093. _this.to = to;
  39094. _this.loop = loop;
  39095. _this._target = target;
  39096. return _this;
  39097. }
  39098. PlayAnimationAction.prototype._prepare = function () {
  39099. };
  39100. PlayAnimationAction.prototype.execute = function () {
  39101. var scene = this._actionManager.getScene();
  39102. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39103. };
  39104. PlayAnimationAction.prototype.serialize = function (parent) {
  39105. return _super.prototype._serialize.call(this, {
  39106. name: "PlayAnimationAction",
  39107. properties: [
  39108. BABYLON.Action._GetTargetProperty(this._target),
  39109. { name: "from", value: String(this.from) },
  39110. { name: "to", value: String(this.to) },
  39111. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39112. ]
  39113. }, parent);
  39114. };
  39115. return PlayAnimationAction;
  39116. }(BABYLON.Action));
  39117. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39118. var StopAnimationAction = (function (_super) {
  39119. __extends(StopAnimationAction, _super);
  39120. function StopAnimationAction(triggerOptions, target, condition) {
  39121. var _this = _super.call(this, triggerOptions, condition) || this;
  39122. _this._target = target;
  39123. return _this;
  39124. }
  39125. StopAnimationAction.prototype._prepare = function () {
  39126. };
  39127. StopAnimationAction.prototype.execute = function () {
  39128. var scene = this._actionManager.getScene();
  39129. scene.stopAnimation(this._target);
  39130. };
  39131. StopAnimationAction.prototype.serialize = function (parent) {
  39132. return _super.prototype._serialize.call(this, {
  39133. name: "StopAnimationAction",
  39134. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39135. }, parent);
  39136. };
  39137. return StopAnimationAction;
  39138. }(BABYLON.Action));
  39139. BABYLON.StopAnimationAction = StopAnimationAction;
  39140. var DoNothingAction = (function (_super) {
  39141. __extends(DoNothingAction, _super);
  39142. function DoNothingAction(triggerOptions, condition) {
  39143. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39144. return _super.call(this, triggerOptions, condition) || this;
  39145. }
  39146. DoNothingAction.prototype.execute = function () {
  39147. };
  39148. DoNothingAction.prototype.serialize = function (parent) {
  39149. return _super.prototype._serialize.call(this, {
  39150. name: "DoNothingAction",
  39151. properties: []
  39152. }, parent);
  39153. };
  39154. return DoNothingAction;
  39155. }(BABYLON.Action));
  39156. BABYLON.DoNothingAction = DoNothingAction;
  39157. var CombineAction = (function (_super) {
  39158. __extends(CombineAction, _super);
  39159. function CombineAction(triggerOptions, children, condition) {
  39160. var _this = _super.call(this, triggerOptions, condition) || this;
  39161. _this.children = children;
  39162. return _this;
  39163. }
  39164. CombineAction.prototype._prepare = function () {
  39165. for (var index = 0; index < this.children.length; index++) {
  39166. this.children[index]._actionManager = this._actionManager;
  39167. this.children[index]._prepare();
  39168. }
  39169. };
  39170. CombineAction.prototype.execute = function (evt) {
  39171. for (var index = 0; index < this.children.length; index++) {
  39172. this.children[index].execute(evt);
  39173. }
  39174. };
  39175. CombineAction.prototype.serialize = function (parent) {
  39176. var serializationObject = _super.prototype._serialize.call(this, {
  39177. name: "CombineAction",
  39178. properties: [],
  39179. combine: []
  39180. }, parent);
  39181. for (var i = 0; i < this.children.length; i++) {
  39182. serializationObject.combine.push(this.children[i].serialize(null));
  39183. }
  39184. return serializationObject;
  39185. };
  39186. return CombineAction;
  39187. }(BABYLON.Action));
  39188. BABYLON.CombineAction = CombineAction;
  39189. var ExecuteCodeAction = (function (_super) {
  39190. __extends(ExecuteCodeAction, _super);
  39191. function ExecuteCodeAction(triggerOptions, func, condition) {
  39192. var _this = _super.call(this, triggerOptions, condition) || this;
  39193. _this.func = func;
  39194. return _this;
  39195. }
  39196. ExecuteCodeAction.prototype.execute = function (evt) {
  39197. this.func(evt);
  39198. };
  39199. return ExecuteCodeAction;
  39200. }(BABYLON.Action));
  39201. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39202. var SetParentAction = (function (_super) {
  39203. __extends(SetParentAction, _super);
  39204. function SetParentAction(triggerOptions, target, parent, condition) {
  39205. var _this = _super.call(this, triggerOptions, condition) || this;
  39206. _this._target = target;
  39207. _this._parent = parent;
  39208. return _this;
  39209. }
  39210. SetParentAction.prototype._prepare = function () {
  39211. };
  39212. SetParentAction.prototype.execute = function () {
  39213. if (this._target.parent === this._parent) {
  39214. return;
  39215. }
  39216. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39217. invertParentWorldMatrix.invert();
  39218. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39219. this._target.parent = this._parent;
  39220. };
  39221. SetParentAction.prototype.serialize = function (parent) {
  39222. return _super.prototype._serialize.call(this, {
  39223. name: "SetParentAction",
  39224. properties: [
  39225. BABYLON.Action._GetTargetProperty(this._target),
  39226. BABYLON.Action._GetTargetProperty(this._parent),
  39227. ]
  39228. }, parent);
  39229. };
  39230. return SetParentAction;
  39231. }(BABYLON.Action));
  39232. BABYLON.SetParentAction = SetParentAction;
  39233. var PlaySoundAction = (function (_super) {
  39234. __extends(PlaySoundAction, _super);
  39235. function PlaySoundAction(triggerOptions, sound, condition) {
  39236. var _this = _super.call(this, triggerOptions, condition) || this;
  39237. _this._sound = sound;
  39238. return _this;
  39239. }
  39240. PlaySoundAction.prototype._prepare = function () {
  39241. };
  39242. PlaySoundAction.prototype.execute = function () {
  39243. if (this._sound !== undefined)
  39244. this._sound.play();
  39245. };
  39246. PlaySoundAction.prototype.serialize = function (parent) {
  39247. return _super.prototype._serialize.call(this, {
  39248. name: "PlaySoundAction",
  39249. properties: [{ name: "sound", value: this._sound.name }]
  39250. }, parent);
  39251. };
  39252. return PlaySoundAction;
  39253. }(BABYLON.Action));
  39254. BABYLON.PlaySoundAction = PlaySoundAction;
  39255. var StopSoundAction = (function (_super) {
  39256. __extends(StopSoundAction, _super);
  39257. function StopSoundAction(triggerOptions, sound, condition) {
  39258. var _this = _super.call(this, triggerOptions, condition) || this;
  39259. _this._sound = sound;
  39260. return _this;
  39261. }
  39262. StopSoundAction.prototype._prepare = function () {
  39263. };
  39264. StopSoundAction.prototype.execute = function () {
  39265. if (this._sound !== undefined)
  39266. this._sound.stop();
  39267. };
  39268. StopSoundAction.prototype.serialize = function (parent) {
  39269. return _super.prototype._serialize.call(this, {
  39270. name: "StopSoundAction",
  39271. properties: [{ name: "sound", value: this._sound.name }]
  39272. }, parent);
  39273. };
  39274. return StopSoundAction;
  39275. }(BABYLON.Action));
  39276. BABYLON.StopSoundAction = StopSoundAction;
  39277. })(BABYLON || (BABYLON = {}));
  39278. //# sourceMappingURL=babylon.directActions.js.map
  39279. var BABYLON;
  39280. (function (BABYLON) {
  39281. var SpriteManager = (function () {
  39282. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  39283. if (epsilon === void 0) { epsilon = 0.01; }
  39284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39285. this.name = name;
  39286. this.sprites = new Array();
  39287. this.renderingGroupId = 0;
  39288. this.layerMask = 0x0FFFFFFF;
  39289. this.fogEnabled = true;
  39290. this.isPickable = false;
  39291. /**
  39292. * An event triggered when the manager is disposed.
  39293. * @type {BABYLON.Observable}
  39294. */
  39295. this.onDisposeObservable = new BABYLON.Observable();
  39296. this._vertexBuffers = {};
  39297. this._capacity = capacity;
  39298. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  39299. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39300. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39301. if (cellSize.width && cellSize.height) {
  39302. this.cellWidth = cellSize.width;
  39303. this.cellHeight = cellSize.height;
  39304. }
  39305. else if (cellSize !== undefined) {
  39306. this.cellWidth = cellSize;
  39307. this.cellHeight = cellSize;
  39308. }
  39309. else {
  39310. return;
  39311. }
  39312. this._epsilon = epsilon;
  39313. this._scene = scene;
  39314. this._scene.spriteManagers.push(this);
  39315. var indices = [];
  39316. var index = 0;
  39317. for (var count = 0; count < capacity; count++) {
  39318. indices.push(index);
  39319. indices.push(index + 1);
  39320. indices.push(index + 2);
  39321. indices.push(index);
  39322. indices.push(index + 2);
  39323. indices.push(index + 3);
  39324. index += 4;
  39325. }
  39326. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39327. // VBO
  39328. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  39329. this._vertexData = new Float32Array(capacity * 16 * 4);
  39330. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  39331. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  39332. var options = this._buffer.createVertexBuffer("options", 4, 4);
  39333. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  39334. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  39335. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39336. this._vertexBuffers["options"] = options;
  39337. this._vertexBuffers["cellInfo"] = cellInfo;
  39338. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39339. // Effects
  39340. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  39341. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  39342. }
  39343. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  39344. set: function (callback) {
  39345. if (this._onDisposeObserver) {
  39346. this.onDisposeObservable.remove(this._onDisposeObserver);
  39347. }
  39348. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39349. },
  39350. enumerable: true,
  39351. configurable: true
  39352. });
  39353. Object.defineProperty(SpriteManager.prototype, "texture", {
  39354. get: function () {
  39355. return this._spriteTexture;
  39356. },
  39357. set: function (value) {
  39358. this._spriteTexture = value;
  39359. },
  39360. enumerable: true,
  39361. configurable: true
  39362. });
  39363. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  39364. var arrayOffset = index * 16;
  39365. if (offsetX === 0)
  39366. offsetX = this._epsilon;
  39367. else if (offsetX === 1)
  39368. offsetX = 1 - this._epsilon;
  39369. if (offsetY === 0)
  39370. offsetY = this._epsilon;
  39371. else if (offsetY === 1)
  39372. offsetY = 1 - this._epsilon;
  39373. this._vertexData[arrayOffset] = sprite.position.x;
  39374. this._vertexData[arrayOffset + 1] = sprite.position.y;
  39375. this._vertexData[arrayOffset + 2] = sprite.position.z;
  39376. this._vertexData[arrayOffset + 3] = sprite.angle;
  39377. this._vertexData[arrayOffset + 4] = sprite.width;
  39378. this._vertexData[arrayOffset + 5] = sprite.height;
  39379. this._vertexData[arrayOffset + 6] = offsetX;
  39380. this._vertexData[arrayOffset + 7] = offsetY;
  39381. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  39382. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  39383. var offset = (sprite.cellIndex / rowSize) >> 0;
  39384. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  39385. this._vertexData[arrayOffset + 11] = offset;
  39386. // Color
  39387. this._vertexData[arrayOffset + 12] = sprite.color.r;
  39388. this._vertexData[arrayOffset + 13] = sprite.color.g;
  39389. this._vertexData[arrayOffset + 14] = sprite.color.b;
  39390. this._vertexData[arrayOffset + 15] = sprite.color.a;
  39391. };
  39392. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  39393. var count = Math.min(this._capacity, this.sprites.length);
  39394. var min = BABYLON.Vector3.Zero();
  39395. var max = BABYLON.Vector3.Zero();
  39396. var distance = Number.MAX_VALUE;
  39397. var currentSprite;
  39398. var cameraSpacePosition = BABYLON.Vector3.Zero();
  39399. var cameraView = camera.getViewMatrix();
  39400. for (var index = 0; index < count; index++) {
  39401. var sprite = this.sprites[index];
  39402. if (!sprite) {
  39403. continue;
  39404. }
  39405. if (predicate) {
  39406. if (!predicate(sprite)) {
  39407. continue;
  39408. }
  39409. }
  39410. else if (!sprite.isPickable) {
  39411. continue;
  39412. }
  39413. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  39414. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  39415. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  39416. if (ray.intersectsBoxMinMax(min, max)) {
  39417. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  39418. if (distance > currentDistance) {
  39419. distance = currentDistance;
  39420. currentSprite = sprite;
  39421. if (fastCheck) {
  39422. break;
  39423. }
  39424. }
  39425. }
  39426. }
  39427. if (currentSprite) {
  39428. var result = new BABYLON.PickingInfo();
  39429. result.hit = true;
  39430. result.pickedSprite = currentSprite;
  39431. result.distance = distance;
  39432. return result;
  39433. }
  39434. return null;
  39435. };
  39436. SpriteManager.prototype.render = function () {
  39437. // Check
  39438. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  39439. return;
  39440. var engine = this._scene.getEngine();
  39441. var baseSize = this._spriteTexture.getBaseSize();
  39442. // Sprites
  39443. var deltaTime = engine.getDeltaTime();
  39444. var max = Math.min(this._capacity, this.sprites.length);
  39445. var rowSize = baseSize.width / this.cellWidth;
  39446. var offset = 0;
  39447. for (var index = 0; index < max; index++) {
  39448. var sprite = this.sprites[index];
  39449. if (!sprite) {
  39450. continue;
  39451. }
  39452. sprite._animate(deltaTime);
  39453. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  39454. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  39455. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  39456. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  39457. }
  39458. this._buffer.update(this._vertexData);
  39459. // Render
  39460. var effect = this._effectBase;
  39461. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39462. effect = this._effectFog;
  39463. }
  39464. engine.enableEffect(effect);
  39465. var viewMatrix = this._scene.getViewMatrix();
  39466. effect.setTexture("diffuseSampler", this._spriteTexture);
  39467. effect.setMatrix("view", viewMatrix);
  39468. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39469. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  39470. // Fog
  39471. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39472. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39473. effect.setColor3("vFogColor", this._scene.fogColor);
  39474. }
  39475. // VBOs
  39476. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39477. // Draw order
  39478. engine.setDepthFunctionToLessOrEqual();
  39479. effect.setBool("alphaTest", true);
  39480. engine.setColorWrite(false);
  39481. engine.draw(true, 0, max * 6);
  39482. engine.setColorWrite(true);
  39483. effect.setBool("alphaTest", false);
  39484. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39485. engine.draw(true, 0, max * 6);
  39486. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39487. };
  39488. SpriteManager.prototype.dispose = function () {
  39489. if (this._buffer) {
  39490. this._buffer.dispose();
  39491. this._buffer = null;
  39492. }
  39493. if (this._indexBuffer) {
  39494. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39495. this._indexBuffer = null;
  39496. }
  39497. if (this._spriteTexture) {
  39498. this._spriteTexture.dispose();
  39499. this._spriteTexture = null;
  39500. }
  39501. // Remove from scene
  39502. var index = this._scene.spriteManagers.indexOf(this);
  39503. this._scene.spriteManagers.splice(index, 1);
  39504. // Callback
  39505. this.onDisposeObservable.notifyObservers(this);
  39506. this.onDisposeObservable.clear();
  39507. };
  39508. return SpriteManager;
  39509. }());
  39510. BABYLON.SpriteManager = SpriteManager;
  39511. })(BABYLON || (BABYLON = {}));
  39512. //# sourceMappingURL=babylon.spriteManager.js.map
  39513. var BABYLON;
  39514. (function (BABYLON) {
  39515. var Sprite = (function () {
  39516. function Sprite(name, manager) {
  39517. this.name = name;
  39518. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39519. this.width = 1.0;
  39520. this.height = 1.0;
  39521. this.angle = 0;
  39522. this.cellIndex = 0;
  39523. this.invertU = 0;
  39524. this.invertV = 0;
  39525. this.animations = new Array();
  39526. this.isPickable = false;
  39527. this._animationStarted = false;
  39528. this._loopAnimation = false;
  39529. this._fromIndex = 0;
  39530. this._toIndex = 0;
  39531. this._delay = 0;
  39532. this._direction = 1;
  39533. this._frameCount = 0;
  39534. this._time = 0;
  39535. this._manager = manager;
  39536. this._manager.sprites.push(this);
  39537. this.position = BABYLON.Vector3.Zero();
  39538. }
  39539. Object.defineProperty(Sprite.prototype, "size", {
  39540. get: function () {
  39541. return this.width;
  39542. },
  39543. set: function (value) {
  39544. this.width = value;
  39545. this.height = value;
  39546. },
  39547. enumerable: true,
  39548. configurable: true
  39549. });
  39550. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  39551. this._fromIndex = from;
  39552. this._toIndex = to;
  39553. this._loopAnimation = loop;
  39554. this._delay = delay;
  39555. this._animationStarted = true;
  39556. this._direction = from < to ? 1 : -1;
  39557. this.cellIndex = from;
  39558. this._time = 0;
  39559. this._onAnimationEnd = onAnimationEnd;
  39560. };
  39561. Sprite.prototype.stopAnimation = function () {
  39562. this._animationStarted = false;
  39563. };
  39564. Sprite.prototype._animate = function (deltaTime) {
  39565. if (!this._animationStarted)
  39566. return;
  39567. this._time += deltaTime;
  39568. if (this._time > this._delay) {
  39569. this._time = this._time % this._delay;
  39570. this.cellIndex += this._direction;
  39571. if (this.cellIndex === this._toIndex) {
  39572. if (this._loopAnimation) {
  39573. this.cellIndex = this._fromIndex;
  39574. }
  39575. else {
  39576. this._animationStarted = false;
  39577. if (this._onAnimationEnd) {
  39578. this._onAnimationEnd();
  39579. }
  39580. if (this.disposeWhenFinishedAnimating) {
  39581. this.dispose();
  39582. }
  39583. }
  39584. }
  39585. }
  39586. };
  39587. Sprite.prototype.dispose = function () {
  39588. for (var i = 0; i < this._manager.sprites.length; i++) {
  39589. if (this._manager.sprites[i] == this) {
  39590. this._manager.sprites.splice(i, 1);
  39591. }
  39592. }
  39593. };
  39594. return Sprite;
  39595. }());
  39596. BABYLON.Sprite = Sprite;
  39597. })(BABYLON || (BABYLON = {}));
  39598. //# sourceMappingURL=babylon.sprite.js.map
  39599. var BABYLON;
  39600. (function (BABYLON) {
  39601. var IntersectionInfo = (function () {
  39602. function IntersectionInfo(bu, bv, distance) {
  39603. this.bu = bu;
  39604. this.bv = bv;
  39605. this.distance = distance;
  39606. this.faceId = 0;
  39607. this.subMeshId = 0;
  39608. }
  39609. return IntersectionInfo;
  39610. }());
  39611. BABYLON.IntersectionInfo = IntersectionInfo;
  39612. var PickingInfo = (function () {
  39613. function PickingInfo() {
  39614. this.hit = false;
  39615. this.distance = 0;
  39616. this.pickedPoint = null;
  39617. this.pickedMesh = null;
  39618. this.bu = 0;
  39619. this.bv = 0;
  39620. this.faceId = -1;
  39621. this.subMeshId = 0;
  39622. this.pickedSprite = null;
  39623. }
  39624. // Methods
  39625. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  39626. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  39627. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  39628. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39629. return null;
  39630. }
  39631. var indices = this.pickedMesh.getIndices();
  39632. var result;
  39633. if (useVerticesNormals) {
  39634. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39635. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  39636. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  39637. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  39638. normal0 = normal0.scale(this.bu);
  39639. normal1 = normal1.scale(this.bv);
  39640. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  39641. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  39642. }
  39643. else {
  39644. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39645. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  39646. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  39647. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  39648. var p1p2 = vertex1.subtract(vertex2);
  39649. var p3p2 = vertex3.subtract(vertex2);
  39650. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  39651. }
  39652. if (useWorldCoordinates) {
  39653. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  39654. }
  39655. return BABYLON.Vector3.Normalize(result);
  39656. };
  39657. PickingInfo.prototype.getTextureCoordinates = function () {
  39658. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39659. return null;
  39660. }
  39661. var indices = this.pickedMesh.getIndices();
  39662. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39663. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  39664. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  39665. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  39666. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  39667. uv1 = uv1.scale(this.bu);
  39668. uv2 = uv2.scale(this.bv);
  39669. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  39670. };
  39671. return PickingInfo;
  39672. }());
  39673. BABYLON.PickingInfo = PickingInfo;
  39674. })(BABYLON || (BABYLON = {}));
  39675. //# sourceMappingURL=babylon.pickingInfo.js.map
  39676. var BABYLON;
  39677. (function (BABYLON) {
  39678. var Ray = (function () {
  39679. function Ray(origin, direction, length) {
  39680. if (length === void 0) { length = Number.MAX_VALUE; }
  39681. this.origin = origin;
  39682. this.direction = direction;
  39683. this.length = length;
  39684. }
  39685. // Methods
  39686. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  39687. var d = 0.0;
  39688. var maxValue = Number.MAX_VALUE;
  39689. var inv;
  39690. var min;
  39691. var max;
  39692. var temp;
  39693. if (Math.abs(this.direction.x) < 0.0000001) {
  39694. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  39695. return false;
  39696. }
  39697. }
  39698. else {
  39699. inv = 1.0 / this.direction.x;
  39700. min = (minimum.x - this.origin.x) * inv;
  39701. max = (maximum.x - this.origin.x) * inv;
  39702. if (max === -Infinity) {
  39703. max = Infinity;
  39704. }
  39705. if (min > max) {
  39706. temp = min;
  39707. min = max;
  39708. max = temp;
  39709. }
  39710. d = Math.max(min, d);
  39711. maxValue = Math.min(max, maxValue);
  39712. if (d > maxValue) {
  39713. return false;
  39714. }
  39715. }
  39716. if (Math.abs(this.direction.y) < 0.0000001) {
  39717. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  39718. return false;
  39719. }
  39720. }
  39721. else {
  39722. inv = 1.0 / this.direction.y;
  39723. min = (minimum.y - this.origin.y) * inv;
  39724. max = (maximum.y - this.origin.y) * inv;
  39725. if (max === -Infinity) {
  39726. max = Infinity;
  39727. }
  39728. if (min > max) {
  39729. temp = min;
  39730. min = max;
  39731. max = temp;
  39732. }
  39733. d = Math.max(min, d);
  39734. maxValue = Math.min(max, maxValue);
  39735. if (d > maxValue) {
  39736. return false;
  39737. }
  39738. }
  39739. if (Math.abs(this.direction.z) < 0.0000001) {
  39740. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  39741. return false;
  39742. }
  39743. }
  39744. else {
  39745. inv = 1.0 / this.direction.z;
  39746. min = (minimum.z - this.origin.z) * inv;
  39747. max = (maximum.z - this.origin.z) * inv;
  39748. if (max === -Infinity) {
  39749. max = Infinity;
  39750. }
  39751. if (min > max) {
  39752. temp = min;
  39753. min = max;
  39754. max = temp;
  39755. }
  39756. d = Math.max(min, d);
  39757. maxValue = Math.min(max, maxValue);
  39758. if (d > maxValue) {
  39759. return false;
  39760. }
  39761. }
  39762. return true;
  39763. };
  39764. Ray.prototype.intersectsBox = function (box) {
  39765. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  39766. };
  39767. Ray.prototype.intersectsSphere = function (sphere) {
  39768. var x = sphere.center.x - this.origin.x;
  39769. var y = sphere.center.y - this.origin.y;
  39770. var z = sphere.center.z - this.origin.z;
  39771. var pyth = (x * x) + (y * y) + (z * z);
  39772. var rr = sphere.radius * sphere.radius;
  39773. if (pyth <= rr) {
  39774. return true;
  39775. }
  39776. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  39777. if (dot < 0.0) {
  39778. return false;
  39779. }
  39780. var temp = pyth - (dot * dot);
  39781. return temp <= rr;
  39782. };
  39783. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  39784. if (!this._edge1) {
  39785. this._edge1 = BABYLON.Vector3.Zero();
  39786. this._edge2 = BABYLON.Vector3.Zero();
  39787. this._pvec = BABYLON.Vector3.Zero();
  39788. this._tvec = BABYLON.Vector3.Zero();
  39789. this._qvec = BABYLON.Vector3.Zero();
  39790. }
  39791. vertex1.subtractToRef(vertex0, this._edge1);
  39792. vertex2.subtractToRef(vertex0, this._edge2);
  39793. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  39794. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  39795. if (det === 0) {
  39796. return null;
  39797. }
  39798. var invdet = 1 / det;
  39799. this.origin.subtractToRef(vertex0, this._tvec);
  39800. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  39801. if (bu < 0 || bu > 1.0) {
  39802. return null;
  39803. }
  39804. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  39805. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  39806. if (bv < 0 || bu + bv > 1.0) {
  39807. return null;
  39808. }
  39809. //check if the distance is longer than the predefined length.
  39810. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  39811. if (distance > this.length) {
  39812. return null;
  39813. }
  39814. return new BABYLON.IntersectionInfo(bu, bv, distance);
  39815. };
  39816. Ray.prototype.intersectsPlane = function (plane) {
  39817. var distance;
  39818. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  39819. if (Math.abs(result1) < 9.99999997475243E-07) {
  39820. return null;
  39821. }
  39822. else {
  39823. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  39824. distance = (-plane.d - result2) / result1;
  39825. if (distance < 0.0) {
  39826. if (distance < -9.99999997475243E-07) {
  39827. return null;
  39828. }
  39829. else {
  39830. return 0;
  39831. }
  39832. }
  39833. return distance;
  39834. }
  39835. };
  39836. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  39837. var tm = BABYLON.Tmp.Matrix[0];
  39838. mesh.getWorldMatrix().invertToRef(tm);
  39839. if (this._tmpRay) {
  39840. Ray.TransformToRef(this, tm, this._tmpRay);
  39841. }
  39842. else {
  39843. this._tmpRay = Ray.Transform(this, tm);
  39844. }
  39845. return mesh.intersects(this._tmpRay, fastCheck);
  39846. };
  39847. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  39848. if (results) {
  39849. results.length = 0;
  39850. }
  39851. else {
  39852. results = [];
  39853. }
  39854. for (var i = 0; i < meshes.length; i++) {
  39855. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  39856. if (pickInfo.hit) {
  39857. results.push(pickInfo);
  39858. }
  39859. }
  39860. results.sort(this._comparePickingInfo);
  39861. return results;
  39862. };
  39863. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  39864. if (pickingInfoA.distance < pickingInfoB.distance) {
  39865. return -1;
  39866. }
  39867. else if (pickingInfoA.distance > pickingInfoB.distance) {
  39868. return 1;
  39869. }
  39870. else {
  39871. return 0;
  39872. }
  39873. };
  39874. /**
  39875. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  39876. * @param sega the first point of the segment to test the intersection against
  39877. * @param segb the second point of the segment to test the intersection against
  39878. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  39879. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  39880. */
  39881. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  39882. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  39883. var u = segb.subtract(sega);
  39884. var v = rsegb.subtract(this.origin);
  39885. var w = sega.subtract(this.origin);
  39886. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  39887. var b = BABYLON.Vector3.Dot(u, v);
  39888. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  39889. var d = BABYLON.Vector3.Dot(u, w);
  39890. var e = BABYLON.Vector3.Dot(v, w);
  39891. var D = a * c - b * b; // always >= 0
  39892. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  39893. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  39894. // compute the line parameters of the two closest points
  39895. if (D < Ray.smallnum) {
  39896. sN = 0.0; // force using point P0 on segment S1
  39897. sD = 1.0; // to prevent possible division by 0.0 later
  39898. tN = e;
  39899. tD = c;
  39900. }
  39901. else {
  39902. sN = (b * e - c * d);
  39903. tN = (a * e - b * d);
  39904. if (sN < 0.0) {
  39905. sN = 0.0;
  39906. tN = e;
  39907. tD = c;
  39908. }
  39909. else if (sN > sD) {
  39910. sN = sD;
  39911. tN = e + b;
  39912. tD = c;
  39913. }
  39914. }
  39915. if (tN < 0.0) {
  39916. tN = 0.0;
  39917. // recompute sc for this edge
  39918. if (-d < 0.0) {
  39919. sN = 0.0;
  39920. }
  39921. else if (-d > a)
  39922. sN = sD;
  39923. else {
  39924. sN = -d;
  39925. sD = a;
  39926. }
  39927. }
  39928. else if (tN > tD) {
  39929. tN = tD;
  39930. // recompute sc for this edge
  39931. if ((-d + b) < 0.0) {
  39932. sN = 0;
  39933. }
  39934. else if ((-d + b) > a) {
  39935. sN = sD;
  39936. }
  39937. else {
  39938. sN = (-d + b);
  39939. sD = a;
  39940. }
  39941. }
  39942. // finally do the division to get sc and tc
  39943. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  39944. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  39945. // get the difference of the two closest points
  39946. var qtc = v.multiplyByFloats(tc, tc, tc);
  39947. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  39948. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  39949. if (isIntersected) {
  39950. return qtc.length();
  39951. }
  39952. return -1;
  39953. };
  39954. // Statics
  39955. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  39956. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  39957. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  39958. var direction = end.subtract(start);
  39959. direction.normalize();
  39960. return new Ray(start, direction);
  39961. };
  39962. /**
  39963. * 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
  39964. * transformed to the given world matrix.
  39965. * @param origin The origin point
  39966. * @param end The end point
  39967. * @param world a matrix to transform the ray to. Default is the identity matrix.
  39968. */
  39969. Ray.CreateNewFromTo = function (origin, end, world) {
  39970. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  39971. var direction = end.subtract(origin);
  39972. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  39973. direction.normalize();
  39974. return Ray.Transform(new Ray(origin, direction, length), world);
  39975. };
  39976. Ray.Transform = function (ray, matrix) {
  39977. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  39978. Ray.TransformToRef(ray, matrix, result);
  39979. return result;
  39980. };
  39981. Ray.TransformToRef = function (ray, matrix, result) {
  39982. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  39983. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  39984. result.length = ray.length;
  39985. var dir = result.direction;
  39986. var len = dir.length();
  39987. if (!(len === 0 || len === 1)) {
  39988. var num = 1.0 / len;
  39989. dir.x *= num;
  39990. dir.y *= num;
  39991. dir.z *= num;
  39992. result.length *= len;
  39993. }
  39994. };
  39995. Ray.smallnum = 0.00000001;
  39996. Ray.rayl = 10e8;
  39997. return Ray;
  39998. }());
  39999. BABYLON.Ray = Ray;
  40000. })(BABYLON || (BABYLON = {}));
  40001. //# sourceMappingURL=babylon.ray.js.map
  40002. var BABYLON;
  40003. (function (BABYLON) {
  40004. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  40005. if (boxMin.x > sphereCenter.x + sphereRadius)
  40006. return false;
  40007. if (sphereCenter.x - sphereRadius > boxMax.x)
  40008. return false;
  40009. if (boxMin.y > sphereCenter.y + sphereRadius)
  40010. return false;
  40011. if (sphereCenter.y - sphereRadius > boxMax.y)
  40012. return false;
  40013. if (boxMin.z > sphereCenter.z + sphereRadius)
  40014. return false;
  40015. if (sphereCenter.z - sphereRadius > boxMax.z)
  40016. return false;
  40017. return true;
  40018. };
  40019. var getLowestRoot = (function () {
  40020. var result = { root: 0, found: false };
  40021. return function (a, b, c, maxR) {
  40022. result.root = 0;
  40023. result.found = false;
  40024. var determinant = b * b - 4.0 * a * c;
  40025. if (determinant < 0)
  40026. return result;
  40027. var sqrtD = Math.sqrt(determinant);
  40028. var r1 = (-b - sqrtD) / (2.0 * a);
  40029. var r2 = (-b + sqrtD) / (2.0 * a);
  40030. if (r1 > r2) {
  40031. var temp = r2;
  40032. r2 = r1;
  40033. r1 = temp;
  40034. }
  40035. if (r1 > 0 && r1 < maxR) {
  40036. result.root = r1;
  40037. result.found = true;
  40038. return result;
  40039. }
  40040. if (r2 > 0 && r2 < maxR) {
  40041. result.root = r2;
  40042. result.found = true;
  40043. return result;
  40044. }
  40045. return result;
  40046. };
  40047. })();
  40048. var Collider = (function () {
  40049. function Collider() {
  40050. this.radius = BABYLON.Vector3.One();
  40051. this.retry = 0;
  40052. this.basePointWorld = BABYLON.Vector3.Zero();
  40053. this.velocityWorld = BABYLON.Vector3.Zero();
  40054. this.normalizedVelocity = BABYLON.Vector3.Zero();
  40055. this._collisionPoint = BABYLON.Vector3.Zero();
  40056. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  40057. this._tempVector = BABYLON.Vector3.Zero();
  40058. this._tempVector2 = BABYLON.Vector3.Zero();
  40059. this._tempVector3 = BABYLON.Vector3.Zero();
  40060. this._tempVector4 = BABYLON.Vector3.Zero();
  40061. this._edge = BABYLON.Vector3.Zero();
  40062. this._baseToVertex = BABYLON.Vector3.Zero();
  40063. this._destinationPoint = BABYLON.Vector3.Zero();
  40064. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  40065. this._displacementVector = BABYLON.Vector3.Zero();
  40066. this._collisionMask = -1;
  40067. }
  40068. Object.defineProperty(Collider.prototype, "collisionMask", {
  40069. get: function () {
  40070. return this._collisionMask;
  40071. },
  40072. set: function (mask) {
  40073. this._collisionMask = !isNaN(mask) ? mask : -1;
  40074. },
  40075. enumerable: true,
  40076. configurable: true
  40077. });
  40078. // Methods
  40079. Collider.prototype._initialize = function (source, dir, e) {
  40080. this.velocity = dir;
  40081. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  40082. this.basePoint = source;
  40083. source.multiplyToRef(this.radius, this.basePointWorld);
  40084. dir.multiplyToRef(this.radius, this.velocityWorld);
  40085. this.velocityWorldLength = this.velocityWorld.length();
  40086. this.epsilon = e;
  40087. this.collisionFound = false;
  40088. };
  40089. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  40090. pa.subtractToRef(point, this._tempVector);
  40091. pb.subtractToRef(point, this._tempVector2);
  40092. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  40093. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40094. if (d < 0)
  40095. return false;
  40096. pc.subtractToRef(point, this._tempVector3);
  40097. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  40098. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40099. if (d < 0)
  40100. return false;
  40101. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  40102. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40103. return d >= 0;
  40104. };
  40105. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  40106. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  40107. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  40108. if (distance > this.velocityWorldLength + max + sphereRadius) {
  40109. return false;
  40110. }
  40111. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  40112. return false;
  40113. return true;
  40114. };
  40115. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  40116. var t0;
  40117. var embeddedInPlane = false;
  40118. //defensive programming, actually not needed.
  40119. if (!trianglePlaneArray) {
  40120. trianglePlaneArray = [];
  40121. }
  40122. if (!trianglePlaneArray[faceIndex]) {
  40123. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  40124. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  40125. }
  40126. var trianglePlane = trianglePlaneArray[faceIndex];
  40127. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  40128. return;
  40129. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  40130. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  40131. if (normalDotVelocity == 0) {
  40132. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  40133. return;
  40134. embeddedInPlane = true;
  40135. t0 = 0;
  40136. }
  40137. else {
  40138. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40139. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40140. if (t0 > t1) {
  40141. var temp = t1;
  40142. t1 = t0;
  40143. t0 = temp;
  40144. }
  40145. if (t0 > 1.0 || t1 < 0.0)
  40146. return;
  40147. if (t0 < 0)
  40148. t0 = 0;
  40149. if (t0 > 1.0)
  40150. t0 = 1.0;
  40151. }
  40152. this._collisionPoint.copyFromFloats(0, 0, 0);
  40153. var found = false;
  40154. var t = 1.0;
  40155. if (!embeddedInPlane) {
  40156. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  40157. this.velocity.scaleToRef(t0, this._tempVector);
  40158. this._planeIntersectionPoint.addInPlace(this._tempVector);
  40159. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  40160. found = true;
  40161. t = t0;
  40162. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  40163. }
  40164. }
  40165. if (!found) {
  40166. var velocitySquaredLength = this.velocity.lengthSquared();
  40167. var a = velocitySquaredLength;
  40168. this.basePoint.subtractToRef(p1, this._tempVector);
  40169. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40170. var c = this._tempVector.lengthSquared() - 1.0;
  40171. var lowestRoot = getLowestRoot(a, b, c, t);
  40172. if (lowestRoot.found) {
  40173. t = lowestRoot.root;
  40174. found = true;
  40175. this._collisionPoint.copyFrom(p1);
  40176. }
  40177. this.basePoint.subtractToRef(p2, this._tempVector);
  40178. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40179. c = this._tempVector.lengthSquared() - 1.0;
  40180. lowestRoot = getLowestRoot(a, b, c, t);
  40181. if (lowestRoot.found) {
  40182. t = lowestRoot.root;
  40183. found = true;
  40184. this._collisionPoint.copyFrom(p2);
  40185. }
  40186. this.basePoint.subtractToRef(p3, this._tempVector);
  40187. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40188. c = this._tempVector.lengthSquared() - 1.0;
  40189. lowestRoot = getLowestRoot(a, b, c, t);
  40190. if (lowestRoot.found) {
  40191. t = lowestRoot.root;
  40192. found = true;
  40193. this._collisionPoint.copyFrom(p3);
  40194. }
  40195. p2.subtractToRef(p1, this._edge);
  40196. p1.subtractToRef(this.basePoint, this._baseToVertex);
  40197. var edgeSquaredLength = this._edge.lengthSquared();
  40198. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40199. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40200. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40201. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40202. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40203. lowestRoot = getLowestRoot(a, b, c, t);
  40204. if (lowestRoot.found) {
  40205. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40206. if (f >= 0.0 && f <= 1.0) {
  40207. t = lowestRoot.root;
  40208. found = true;
  40209. this._edge.scaleInPlace(f);
  40210. p1.addToRef(this._edge, this._collisionPoint);
  40211. }
  40212. }
  40213. p3.subtractToRef(p2, this._edge);
  40214. p2.subtractToRef(this.basePoint, this._baseToVertex);
  40215. edgeSquaredLength = this._edge.lengthSquared();
  40216. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40217. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40218. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40219. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40220. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40221. lowestRoot = getLowestRoot(a, b, c, t);
  40222. if (lowestRoot.found) {
  40223. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40224. if (f >= 0.0 && f <= 1.0) {
  40225. t = lowestRoot.root;
  40226. found = true;
  40227. this._edge.scaleInPlace(f);
  40228. p2.addToRef(this._edge, this._collisionPoint);
  40229. }
  40230. }
  40231. p1.subtractToRef(p3, this._edge);
  40232. p3.subtractToRef(this.basePoint, this._baseToVertex);
  40233. edgeSquaredLength = this._edge.lengthSquared();
  40234. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40235. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40236. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40237. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40238. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40239. lowestRoot = getLowestRoot(a, b, c, t);
  40240. if (lowestRoot.found) {
  40241. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40242. if (f >= 0.0 && f <= 1.0) {
  40243. t = lowestRoot.root;
  40244. found = true;
  40245. this._edge.scaleInPlace(f);
  40246. p3.addToRef(this._edge, this._collisionPoint);
  40247. }
  40248. }
  40249. }
  40250. if (found) {
  40251. var distToCollision = t * this.velocity.length();
  40252. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  40253. if (!this.intersectionPoint) {
  40254. this.intersectionPoint = this._collisionPoint.clone();
  40255. }
  40256. else {
  40257. this.intersectionPoint.copyFrom(this._collisionPoint);
  40258. }
  40259. this.nearestDistance = distToCollision;
  40260. this.collisionFound = true;
  40261. }
  40262. }
  40263. };
  40264. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  40265. for (var i = indexStart; i < indexEnd; i += 3) {
  40266. var p1 = pts[indices[i] - decal];
  40267. var p2 = pts[indices[i + 1] - decal];
  40268. var p3 = pts[indices[i + 2] - decal];
  40269. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  40270. }
  40271. };
  40272. Collider.prototype._getResponse = function (pos, vel) {
  40273. pos.addToRef(vel, this._destinationPoint);
  40274. vel.scaleInPlace((this.nearestDistance / vel.length()));
  40275. this.basePoint.addToRef(vel, pos);
  40276. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  40277. this._slidePlaneNormal.normalize();
  40278. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  40279. pos.addInPlace(this._displacementVector);
  40280. this.intersectionPoint.addInPlace(this._displacementVector);
  40281. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  40282. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  40283. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  40284. };
  40285. return Collider;
  40286. }());
  40287. BABYLON.Collider = Collider;
  40288. })(BABYLON || (BABYLON = {}));
  40289. //# sourceMappingURL=babylon.collider.js.map
  40290. var BABYLON;
  40291. (function (BABYLON) {
  40292. //WebWorker code will be inserted to this variable.
  40293. BABYLON.CollisionWorker = "";
  40294. var WorkerTaskType;
  40295. (function (WorkerTaskType) {
  40296. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  40297. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  40298. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  40299. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  40300. var WorkerReplyType;
  40301. (function (WorkerReplyType) {
  40302. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  40303. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  40304. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  40305. var CollisionCoordinatorWorker = (function () {
  40306. function CollisionCoordinatorWorker() {
  40307. var _this = this;
  40308. this._scaledPosition = BABYLON.Vector3.Zero();
  40309. this._scaledVelocity = BABYLON.Vector3.Zero();
  40310. this.onMeshUpdated = function (mesh) {
  40311. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  40312. };
  40313. this.onGeometryUpdated = function (geometry) {
  40314. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  40315. };
  40316. this._afterRender = function () {
  40317. if (!_this._init)
  40318. return;
  40319. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  40320. return;
  40321. }
  40322. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  40323. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  40324. if (_this._runningUpdated > 4) {
  40325. return;
  40326. }
  40327. ++_this._runningUpdated;
  40328. var payload = {
  40329. updatedMeshes: _this._addUpdateMeshesList,
  40330. updatedGeometries: _this._addUpdateGeometriesList,
  40331. removedGeometries: _this._toRemoveGeometryArray,
  40332. removedMeshes: _this._toRemoveMeshesArray
  40333. };
  40334. var message = {
  40335. payload: payload,
  40336. taskType: WorkerTaskType.UPDATE
  40337. };
  40338. var serializable = [];
  40339. for (var id in payload.updatedGeometries) {
  40340. if (payload.updatedGeometries.hasOwnProperty(id)) {
  40341. //prepare transferables
  40342. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  40343. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  40344. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  40345. }
  40346. }
  40347. _this._worker.postMessage(message, serializable);
  40348. _this._addUpdateMeshesList = {};
  40349. _this._addUpdateGeometriesList = {};
  40350. _this._toRemoveGeometryArray = [];
  40351. _this._toRemoveMeshesArray = [];
  40352. };
  40353. this._onMessageFromWorker = function (e) {
  40354. var returnData = e.data;
  40355. if (returnData.error != WorkerReplyType.SUCCESS) {
  40356. //TODO what errors can be returned from the worker?
  40357. BABYLON.Tools.Warn("error returned from worker!");
  40358. return;
  40359. }
  40360. switch (returnData.taskType) {
  40361. case WorkerTaskType.INIT:
  40362. _this._init = true;
  40363. //Update the worked with ALL of the scene's current state
  40364. _this._scene.meshes.forEach(function (mesh) {
  40365. _this.onMeshAdded(mesh);
  40366. });
  40367. _this._scene.getGeometries().forEach(function (geometry) {
  40368. _this.onGeometryAdded(geometry);
  40369. });
  40370. break;
  40371. case WorkerTaskType.UPDATE:
  40372. _this._runningUpdated--;
  40373. break;
  40374. case WorkerTaskType.COLLIDE:
  40375. _this._runningCollisionTask = false;
  40376. var returnPayload = returnData.payload;
  40377. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  40378. return;
  40379. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  40380. //cleanup
  40381. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  40382. break;
  40383. }
  40384. };
  40385. this._collisionsCallbackArray = [];
  40386. this._init = false;
  40387. this._runningUpdated = 0;
  40388. this._runningCollisionTask = false;
  40389. this._addUpdateMeshesList = {};
  40390. this._addUpdateGeometriesList = {};
  40391. this._toRemoveGeometryArray = [];
  40392. this._toRemoveMeshesArray = [];
  40393. }
  40394. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40395. if (!this._init)
  40396. return;
  40397. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  40398. return;
  40399. position.divideToRef(collider.radius, this._scaledPosition);
  40400. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40401. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  40402. var payload = {
  40403. collider: {
  40404. position: this._scaledPosition.asArray(),
  40405. velocity: this._scaledVelocity.asArray(),
  40406. radius: collider.radius.asArray()
  40407. },
  40408. collisionId: collisionIndex,
  40409. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  40410. maximumRetry: maximumRetry
  40411. };
  40412. var message = {
  40413. payload: payload,
  40414. taskType: WorkerTaskType.COLLIDE
  40415. };
  40416. this._worker.postMessage(message);
  40417. };
  40418. CollisionCoordinatorWorker.prototype.init = function (scene) {
  40419. this._scene = scene;
  40420. this._scene.registerAfterRender(this._afterRender);
  40421. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  40422. this._worker = new Worker(workerUrl);
  40423. this._worker.onmessage = this._onMessageFromWorker;
  40424. var message = {
  40425. payload: {},
  40426. taskType: WorkerTaskType.INIT
  40427. };
  40428. this._worker.postMessage(message);
  40429. };
  40430. CollisionCoordinatorWorker.prototype.destroy = function () {
  40431. this._scene.unregisterAfterRender(this._afterRender);
  40432. this._worker.terminate();
  40433. };
  40434. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  40435. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  40436. this.onMeshUpdated(mesh);
  40437. };
  40438. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  40439. this._toRemoveMeshesArray.push(mesh.uniqueId);
  40440. };
  40441. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  40442. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  40443. geometry.onGeometryUpdated = this.onGeometryUpdated;
  40444. this.onGeometryUpdated(geometry);
  40445. };
  40446. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  40447. this._toRemoveGeometryArray.push(geometry.id);
  40448. };
  40449. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  40450. var submeshes = [];
  40451. if (mesh.subMeshes) {
  40452. submeshes = mesh.subMeshes.map(function (sm, idx) {
  40453. return {
  40454. position: idx,
  40455. verticesStart: sm.verticesStart,
  40456. verticesCount: sm.verticesCount,
  40457. indexStart: sm.indexStart,
  40458. indexCount: sm.indexCount,
  40459. hasMaterial: !!sm.getMaterial(),
  40460. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40461. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  40462. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40463. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  40464. };
  40465. });
  40466. }
  40467. var geometryId = null;
  40468. if (mesh instanceof BABYLON.Mesh) {
  40469. geometryId = mesh.geometry ? mesh.geometry.id : null;
  40470. }
  40471. else if (mesh instanceof BABYLON.InstancedMesh) {
  40472. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40473. }
  40474. return {
  40475. uniqueId: mesh.uniqueId,
  40476. id: mesh.id,
  40477. name: mesh.name,
  40478. geometryId: geometryId,
  40479. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40480. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  40481. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40482. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  40483. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  40484. subMeshes: submeshes,
  40485. checkCollisions: mesh.checkCollisions
  40486. };
  40487. };
  40488. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  40489. return {
  40490. id: geometry.id,
  40491. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  40492. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  40493. indices: new Uint32Array(geometry.getIndices() || []),
  40494. };
  40495. };
  40496. return CollisionCoordinatorWorker;
  40497. }());
  40498. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  40499. var CollisionCoordinatorLegacy = (function () {
  40500. function CollisionCoordinatorLegacy() {
  40501. this._scaledPosition = BABYLON.Vector3.Zero();
  40502. this._scaledVelocity = BABYLON.Vector3.Zero();
  40503. this._finalPosition = BABYLON.Vector3.Zero();
  40504. }
  40505. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40506. position.divideToRef(collider.radius, this._scaledPosition);
  40507. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40508. collider.collidedMesh = null;
  40509. collider.retry = 0;
  40510. collider.initialVelocity = this._scaledVelocity;
  40511. collider.initialPosition = this._scaledPosition;
  40512. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  40513. this._finalPosition.multiplyInPlace(collider.radius);
  40514. //run the callback
  40515. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  40516. };
  40517. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  40518. this._scene = scene;
  40519. };
  40520. CollisionCoordinatorLegacy.prototype.destroy = function () {
  40521. //Legacy need no destruction method.
  40522. };
  40523. //No update in legacy mode
  40524. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  40525. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  40526. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  40527. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  40528. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  40529. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  40530. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  40531. if (excludedMesh === void 0) { excludedMesh = null; }
  40532. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  40533. if (collider.retry >= maximumRetry) {
  40534. finalPosition.copyFrom(position);
  40535. return;
  40536. }
  40537. // Check if this is a mesh else camera or -1
  40538. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  40539. collider._initialize(position, velocity, closeDistance);
  40540. // Check all meshes
  40541. for (var index = 0; index < this._scene.meshes.length; index++) {
  40542. var mesh = this._scene.meshes[index];
  40543. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  40544. mesh._checkCollision(collider);
  40545. }
  40546. }
  40547. if (!collider.collisionFound) {
  40548. position.addToRef(velocity, finalPosition);
  40549. return;
  40550. }
  40551. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  40552. collider._getResponse(position, velocity);
  40553. }
  40554. if (velocity.length() <= closeDistance) {
  40555. finalPosition.copyFrom(position);
  40556. return;
  40557. }
  40558. collider.retry++;
  40559. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  40560. };
  40561. return CollisionCoordinatorLegacy;
  40562. }());
  40563. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  40564. })(BABYLON || (BABYLON = {}));
  40565. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  40566. var BABYLON;
  40567. (function (BABYLON) {
  40568. var Particle = (function () {
  40569. function Particle() {
  40570. this.position = BABYLON.Vector3.Zero();
  40571. this.direction = BABYLON.Vector3.Zero();
  40572. this.color = new BABYLON.Color4(0, 0, 0, 0);
  40573. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  40574. this.lifeTime = 1.0;
  40575. this.age = 0;
  40576. this.size = 0;
  40577. this.angle = 0;
  40578. this.angularSpeed = 0;
  40579. }
  40580. Particle.prototype.copyTo = function (other) {
  40581. other.position.copyFrom(this.position);
  40582. other.direction.copyFrom(this.direction);
  40583. other.color.copyFrom(this.color);
  40584. other.colorStep.copyFrom(this.colorStep);
  40585. other.lifeTime = this.lifeTime;
  40586. other.age = this.age;
  40587. other.size = this.size;
  40588. other.angle = this.angle;
  40589. other.angularSpeed = this.angularSpeed;
  40590. };
  40591. return Particle;
  40592. }());
  40593. BABYLON.Particle = Particle;
  40594. })(BABYLON || (BABYLON = {}));
  40595. //# sourceMappingURL=babylon.particle.js.map
  40596. var BABYLON;
  40597. (function (BABYLON) {
  40598. var randomNumber = function (min, max) {
  40599. if (min === max) {
  40600. return (min);
  40601. }
  40602. var random = Math.random();
  40603. return ((random * (max - min)) + min);
  40604. };
  40605. var ParticleSystem = (function () {
  40606. function ParticleSystem(name, capacity, scene, customEffect) {
  40607. var _this = this;
  40608. this.name = name;
  40609. // Members
  40610. this.animations = [];
  40611. this.renderingGroupId = 0;
  40612. this.emitter = null;
  40613. this.emitRate = 10;
  40614. this.manualEmitCount = -1;
  40615. this.updateSpeed = 0.01;
  40616. this.targetStopDuration = 0;
  40617. this.disposeOnStop = false;
  40618. this.minEmitPower = 1;
  40619. this.maxEmitPower = 1;
  40620. this.minLifeTime = 1;
  40621. this.maxLifeTime = 1;
  40622. this.minSize = 1;
  40623. this.maxSize = 1;
  40624. this.minAngularSpeed = 0;
  40625. this.maxAngularSpeed = 0;
  40626. this.layerMask = 0x0FFFFFFF;
  40627. this.customShader = null;
  40628. this.preventAutoStart = false;
  40629. /**
  40630. * An event triggered when the system is disposed.
  40631. * @type {BABYLON.Observable}
  40632. */
  40633. this.onDisposeObservable = new BABYLON.Observable();
  40634. this.onAnimationEnd = null;
  40635. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  40636. this.forceDepthWrite = false;
  40637. this.gravity = BABYLON.Vector3.Zero();
  40638. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  40639. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  40640. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  40641. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40642. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40643. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40644. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  40645. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40646. this.particles = new Array();
  40647. this._stockParticles = new Array();
  40648. this._newPartsExcess = 0;
  40649. this._vertexBuffers = {};
  40650. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  40651. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  40652. this._scaledDirection = BABYLON.Vector3.Zero();
  40653. this._scaledGravity = BABYLON.Vector3.Zero();
  40654. this._currentRenderId = -1;
  40655. this._started = false;
  40656. this._stopped = false;
  40657. this._actualFrame = 0;
  40658. this.id = name;
  40659. this._capacity = capacity;
  40660. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40661. this._customEffect = customEffect;
  40662. scene.particleSystems.push(this);
  40663. this._createIndexBuffer();
  40664. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  40665. this._vertexData = new Float32Array(capacity * 11 * 4);
  40666. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  40667. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  40668. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  40669. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  40670. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  40671. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  40672. this._vertexBuffers["options"] = options;
  40673. // Default behaviors
  40674. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  40675. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  40676. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  40677. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  40678. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  40679. };
  40680. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  40681. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  40682. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  40683. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  40684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  40685. };
  40686. this.updateFunction = function (particles) {
  40687. for (var index = 0; index < particles.length; index++) {
  40688. var particle = particles[index];
  40689. particle.age += _this._scaledUpdateSpeed;
  40690. if (particle.age >= particle.lifeTime) {
  40691. _this.recycleParticle(particle);
  40692. index--;
  40693. continue;
  40694. }
  40695. else {
  40696. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  40697. particle.color.addInPlace(_this._scaledColorStep);
  40698. if (particle.color.a < 0)
  40699. particle.color.a = 0;
  40700. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  40701. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  40702. particle.position.addInPlace(_this._scaledDirection);
  40703. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  40704. particle.direction.addInPlace(_this._scaledGravity);
  40705. }
  40706. }
  40707. };
  40708. }
  40709. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  40710. set: function (callback) {
  40711. if (this._onDisposeObserver) {
  40712. this.onDisposeObservable.remove(this._onDisposeObserver);
  40713. }
  40714. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40715. },
  40716. enumerable: true,
  40717. configurable: true
  40718. });
  40719. ParticleSystem.prototype._createIndexBuffer = function () {
  40720. var indices = [];
  40721. var index = 0;
  40722. for (var count = 0; count < this._capacity; count++) {
  40723. indices.push(index);
  40724. indices.push(index + 1);
  40725. indices.push(index + 2);
  40726. indices.push(index);
  40727. indices.push(index + 2);
  40728. indices.push(index + 3);
  40729. index += 4;
  40730. }
  40731. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40732. };
  40733. ParticleSystem.prototype.recycleParticle = function (particle) {
  40734. var lastParticle = this.particles.pop();
  40735. if (lastParticle !== particle) {
  40736. lastParticle.copyTo(particle);
  40737. this._stockParticles.push(lastParticle);
  40738. }
  40739. };
  40740. ParticleSystem.prototype.getCapacity = function () {
  40741. return this._capacity;
  40742. };
  40743. ParticleSystem.prototype.isAlive = function () {
  40744. return this._alive;
  40745. };
  40746. ParticleSystem.prototype.isStarted = function () {
  40747. return this._started;
  40748. };
  40749. ParticleSystem.prototype.start = function () {
  40750. this._started = true;
  40751. this._stopped = false;
  40752. this._actualFrame = 0;
  40753. };
  40754. ParticleSystem.prototype.stop = function () {
  40755. this._stopped = true;
  40756. };
  40757. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  40758. var offset = index * 11;
  40759. this._vertexData[offset] = particle.position.x;
  40760. this._vertexData[offset + 1] = particle.position.y;
  40761. this._vertexData[offset + 2] = particle.position.z;
  40762. this._vertexData[offset + 3] = particle.color.r;
  40763. this._vertexData[offset + 4] = particle.color.g;
  40764. this._vertexData[offset + 5] = particle.color.b;
  40765. this._vertexData[offset + 6] = particle.color.a;
  40766. this._vertexData[offset + 7] = particle.angle;
  40767. this._vertexData[offset + 8] = particle.size;
  40768. this._vertexData[offset + 9] = offsetX;
  40769. this._vertexData[offset + 10] = offsetY;
  40770. };
  40771. ParticleSystem.prototype._update = function (newParticles) {
  40772. // Update current
  40773. this._alive = this.particles.length > 0;
  40774. this.updateFunction(this.particles);
  40775. // Add new ones
  40776. var worldMatrix;
  40777. if (this.emitter.position) {
  40778. var emitterMesh = this.emitter;
  40779. worldMatrix = emitterMesh.getWorldMatrix();
  40780. }
  40781. else {
  40782. var emitterPosition = this.emitter;
  40783. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  40784. }
  40785. var particle;
  40786. for (var index = 0; index < newParticles; index++) {
  40787. if (this.particles.length === this._capacity) {
  40788. break;
  40789. }
  40790. if (this._stockParticles.length !== 0) {
  40791. particle = this._stockParticles.pop();
  40792. particle.age = 0;
  40793. }
  40794. else {
  40795. particle = new BABYLON.Particle();
  40796. }
  40797. this.particles.push(particle);
  40798. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  40799. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  40800. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  40801. particle.size = randomNumber(this.minSize, this.maxSize);
  40802. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  40803. this.startPositionFunction(worldMatrix, particle.position, particle);
  40804. var step = randomNumber(0, 1.0);
  40805. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  40806. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  40807. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  40808. }
  40809. };
  40810. ParticleSystem.prototype._getEffect = function () {
  40811. if (this._customEffect) {
  40812. return this._customEffect;
  40813. }
  40814. ;
  40815. var defines = [];
  40816. if (this._scene.clipPlane) {
  40817. defines.push("#define CLIPPLANE");
  40818. }
  40819. // Effect
  40820. var join = defines.join("\n");
  40821. if (this._cachedDefines !== join) {
  40822. this._cachedDefines = join;
  40823. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  40824. }
  40825. return this._effect;
  40826. };
  40827. ParticleSystem.prototype.animate = function () {
  40828. if (!this._started)
  40829. return;
  40830. var effect = this._getEffect();
  40831. // Check
  40832. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  40833. return;
  40834. if (this._currentRenderId === this._scene.getRenderId()) {
  40835. return;
  40836. }
  40837. this._currentRenderId = this._scene.getRenderId();
  40838. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  40839. // determine the number of particles we need to create
  40840. var newParticles;
  40841. if (this.manualEmitCount > -1) {
  40842. newParticles = this.manualEmitCount;
  40843. this._newPartsExcess = 0;
  40844. this.manualEmitCount = 0;
  40845. }
  40846. else {
  40847. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  40848. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  40849. }
  40850. if (this._newPartsExcess > 1.0) {
  40851. newParticles += this._newPartsExcess >> 0;
  40852. this._newPartsExcess -= this._newPartsExcess >> 0;
  40853. }
  40854. this._alive = false;
  40855. if (!this._stopped) {
  40856. this._actualFrame += this._scaledUpdateSpeed;
  40857. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  40858. this.stop();
  40859. }
  40860. else {
  40861. newParticles = 0;
  40862. }
  40863. this._update(newParticles);
  40864. // Stopped?
  40865. if (this._stopped) {
  40866. if (!this._alive) {
  40867. this._started = false;
  40868. if (this.onAnimationEnd) {
  40869. this.onAnimationEnd();
  40870. }
  40871. if (this.disposeOnStop) {
  40872. this._scene._toBeDisposed.push(this);
  40873. }
  40874. }
  40875. }
  40876. // Update VBO
  40877. var offset = 0;
  40878. for (var index = 0; index < this.particles.length; index++) {
  40879. var particle = this.particles[index];
  40880. this._appendParticleVertex(offset++, particle, 0, 0);
  40881. this._appendParticleVertex(offset++, particle, 1, 0);
  40882. this._appendParticleVertex(offset++, particle, 1, 1);
  40883. this._appendParticleVertex(offset++, particle, 0, 1);
  40884. }
  40885. this._vertexBuffer.update(this._vertexData);
  40886. };
  40887. ParticleSystem.prototype.rebuild = function () {
  40888. this._createIndexBuffer();
  40889. this._vertexBuffer._rebuild();
  40890. };
  40891. ParticleSystem.prototype.render = function () {
  40892. var effect = this._getEffect();
  40893. // Check
  40894. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  40895. return 0;
  40896. var engine = this._scene.getEngine();
  40897. // Render
  40898. engine.enableEffect(effect);
  40899. engine.setState(false);
  40900. var viewMatrix = this._scene.getViewMatrix();
  40901. effect.setTexture("diffuseSampler", this.particleTexture);
  40902. effect.setMatrix("view", viewMatrix);
  40903. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  40904. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  40905. if (this._scene.clipPlane) {
  40906. var clipPlane = this._scene.clipPlane;
  40907. var invView = viewMatrix.clone();
  40908. invView.invert();
  40909. effect.setMatrix("invView", invView);
  40910. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  40911. }
  40912. // VBOs
  40913. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40914. // Draw order
  40915. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  40916. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  40917. }
  40918. else {
  40919. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40920. }
  40921. if (this.forceDepthWrite) {
  40922. engine.setDepthWrite(true);
  40923. }
  40924. engine.draw(true, 0, this.particles.length * 6);
  40925. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40926. return this.particles.length;
  40927. };
  40928. ParticleSystem.prototype.dispose = function () {
  40929. if (this._vertexBuffer) {
  40930. this._vertexBuffer.dispose();
  40931. this._vertexBuffer = null;
  40932. }
  40933. if (this._indexBuffer) {
  40934. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40935. this._indexBuffer = null;
  40936. }
  40937. if (this.particleTexture) {
  40938. this.particleTexture.dispose();
  40939. this.particleTexture = null;
  40940. }
  40941. // Remove from scene
  40942. var index = this._scene.particleSystems.indexOf(this);
  40943. if (index > -1) {
  40944. this._scene.particleSystems.splice(index, 1);
  40945. }
  40946. // Callback
  40947. this.onDisposeObservable.notifyObservers(this);
  40948. this.onDisposeObservable.clear();
  40949. };
  40950. // Clone
  40951. ParticleSystem.prototype.clone = function (name, newEmitter) {
  40952. var custom = null;
  40953. var program = null;
  40954. if (this.customShader != null) {
  40955. program = this.customShader;
  40956. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  40957. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  40958. }
  40959. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  40960. result.customShader = program;
  40961. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  40962. if (newEmitter === undefined) {
  40963. newEmitter = this.emitter;
  40964. }
  40965. result.emitter = newEmitter;
  40966. if (this.particleTexture) {
  40967. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  40968. }
  40969. if (!this.preventAutoStart) {
  40970. result.start();
  40971. }
  40972. return result;
  40973. };
  40974. ParticleSystem.prototype.serialize = function () {
  40975. var serializationObject = {};
  40976. serializationObject.name = this.name;
  40977. serializationObject.id = this.id;
  40978. // Emitter
  40979. if (this.emitter.position) {
  40980. var emitterMesh = this.emitter;
  40981. serializationObject.emitterId = emitterMesh.id;
  40982. }
  40983. else {
  40984. var emitterPosition = this.emitter;
  40985. serializationObject.emitter = emitterPosition.asArray();
  40986. }
  40987. serializationObject.capacity = this.getCapacity();
  40988. if (this.particleTexture) {
  40989. serializationObject.textureName = this.particleTexture.name;
  40990. }
  40991. // Animations
  40992. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  40993. // Particle system
  40994. serializationObject.minAngularSpeed = this.minAngularSpeed;
  40995. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  40996. serializationObject.minSize = this.minSize;
  40997. serializationObject.maxSize = this.maxSize;
  40998. serializationObject.minEmitPower = this.minEmitPower;
  40999. serializationObject.maxEmitPower = this.maxEmitPower;
  41000. serializationObject.minLifeTime = this.minLifeTime;
  41001. serializationObject.maxLifeTime = this.maxLifeTime;
  41002. serializationObject.emitRate = this.emitRate;
  41003. serializationObject.minEmitBox = this.minEmitBox.asArray();
  41004. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  41005. serializationObject.gravity = this.gravity.asArray();
  41006. serializationObject.direction1 = this.direction1.asArray();
  41007. serializationObject.direction2 = this.direction2.asArray();
  41008. serializationObject.color1 = this.color1.asArray();
  41009. serializationObject.color2 = this.color2.asArray();
  41010. serializationObject.colorDead = this.colorDead.asArray();
  41011. serializationObject.updateSpeed = this.updateSpeed;
  41012. serializationObject.targetStopDuration = this.targetStopDuration;
  41013. serializationObject.textureMask = this.textureMask.asArray();
  41014. serializationObject.blendMode = this.blendMode;
  41015. serializationObject.customShader = this.customShader;
  41016. serializationObject.preventAutoStart = this.preventAutoStart;
  41017. return serializationObject;
  41018. };
  41019. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  41020. var name = parsedParticleSystem.name;
  41021. var custom = null;
  41022. var program = null;
  41023. if (parsedParticleSystem.customShader) {
  41024. program = parsedParticleSystem.customShader;
  41025. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41026. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41027. }
  41028. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  41029. particleSystem.customShader = program;
  41030. if (parsedParticleSystem.id) {
  41031. particleSystem.id = parsedParticleSystem.id;
  41032. }
  41033. // Auto start
  41034. if (parsedParticleSystem.preventAutoStart) {
  41035. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  41036. }
  41037. // Texture
  41038. if (parsedParticleSystem.textureName) {
  41039. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  41040. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  41041. }
  41042. // Emitter
  41043. if (parsedParticleSystem.emitterId) {
  41044. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  41045. }
  41046. else {
  41047. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  41048. }
  41049. // Animations
  41050. if (parsedParticleSystem.animations) {
  41051. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  41052. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  41053. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  41054. }
  41055. }
  41056. if (parsedParticleSystem.autoAnimate) {
  41057. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  41058. }
  41059. // Particle system
  41060. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  41061. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  41062. particleSystem.minSize = parsedParticleSystem.minSize;
  41063. particleSystem.maxSize = parsedParticleSystem.maxSize;
  41064. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  41065. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  41066. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  41067. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  41068. particleSystem.emitRate = parsedParticleSystem.emitRate;
  41069. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  41070. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  41071. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  41072. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  41073. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  41074. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  41075. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  41076. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  41077. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  41078. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  41079. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  41080. particleSystem.blendMode = parsedParticleSystem.blendMode;
  41081. if (!particleSystem.preventAutoStart) {
  41082. particleSystem.start();
  41083. }
  41084. return particleSystem;
  41085. };
  41086. // Statics
  41087. ParticleSystem.BLENDMODE_ONEONE = 0;
  41088. ParticleSystem.BLENDMODE_STANDARD = 1;
  41089. return ParticleSystem;
  41090. }());
  41091. BABYLON.ParticleSystem = ParticleSystem;
  41092. })(BABYLON || (BABYLON = {}));
  41093. //# sourceMappingURL=babylon.particleSystem.js.map
  41094. var BABYLON;
  41095. (function (BABYLON) {
  41096. var SolidParticle = (function () {
  41097. /**
  41098. * Creates a Solid Particle object.
  41099. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  41100. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  41101. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  41102. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  41103. * `shapeId` (integer) is the model shape identifier in the SPS.
  41104. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  41105. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  41106. */
  41107. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  41108. this.idx = 0; // particle global index
  41109. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  41110. this.position = BABYLON.Vector3.Zero(); // position
  41111. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41112. this.scaling = BABYLON.Vector3.One(); // scaling
  41113. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  41114. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41115. this.alive = true; // alive
  41116. this.isVisible = true; // visibility
  41117. this._pos = 0; // index of this particle in the global "positions" array
  41118. this.shapeId = 0; // model shape id
  41119. this.idxInShape = 0; // index of the particle in its shape id
  41120. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  41121. this.idx = particleIndex;
  41122. this._pos = positionIndex;
  41123. this._model = model;
  41124. this.shapeId = shapeId;
  41125. this.idxInShape = idxInShape;
  41126. this._sps = sps;
  41127. if (modelBoundingInfo) {
  41128. this._modelBoundingInfo = modelBoundingInfo;
  41129. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  41130. }
  41131. }
  41132. Object.defineProperty(SolidParticle.prototype, "scale", {
  41133. /**
  41134. * legacy support, changed scale to scaling
  41135. */
  41136. get: function () {
  41137. return this.scaling;
  41138. },
  41139. set: function (scale) {
  41140. this.scaling = scale;
  41141. },
  41142. enumerable: true,
  41143. configurable: true
  41144. });
  41145. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41146. /**
  41147. * legacy support, changed quaternion to rotationQuaternion
  41148. */
  41149. get: function () {
  41150. return this.rotationQuaternion;
  41151. },
  41152. set: function (q) {
  41153. this.rotationQuaternion = q;
  41154. },
  41155. enumerable: true,
  41156. configurable: true
  41157. });
  41158. /**
  41159. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  41160. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  41161. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  41162. */
  41163. SolidParticle.prototype.intersectsMesh = function (target) {
  41164. if (!this._boundingInfo || !target._boundingInfo) {
  41165. return false;
  41166. }
  41167. if (this._sps._bSphereOnly) {
  41168. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  41169. }
  41170. return this._boundingInfo.intersects(target._boundingInfo, false);
  41171. };
  41172. return SolidParticle;
  41173. }());
  41174. BABYLON.SolidParticle = SolidParticle;
  41175. var ModelShape = (function () {
  41176. /**
  41177. * 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.
  41178. * SPS internal tool, don't use it manually.
  41179. */
  41180. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41181. this.shapeID = id;
  41182. this._shape = shape;
  41183. this._shapeUV = shapeUV;
  41184. this._positionFunction = posFunction;
  41185. this._vertexFunction = vtxFunction;
  41186. }
  41187. return ModelShape;
  41188. }());
  41189. BABYLON.ModelShape = ModelShape;
  41190. })(BABYLON || (BABYLON = {}));
  41191. //# sourceMappingURL=babylon.solidParticle.js.map
  41192. var BABYLON;
  41193. (function (BABYLON) {
  41194. /**
  41195. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  41196. */
  41197. var SolidParticleSystem = (function () {
  41198. /**
  41199. * Creates a SPS (Solid Particle System) object.
  41200. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41201. * `scene` (Scene) is the scene in which the SPS is added.
  41202. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  41203. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  41204. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  41205. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  41206. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  41207. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  41208. */
  41209. function SolidParticleSystem(name, scene, options) {
  41210. // public members
  41211. /**
  41212. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41213. * Example : var p = SPS.particles[i];
  41214. */
  41215. this.particles = new Array();
  41216. /**
  41217. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41218. */
  41219. this.nbParticles = 0;
  41220. /**
  41221. * If the particles must ever face the camera (default false). Useful for planar particles.
  41222. */
  41223. this.billboard = false;
  41224. /**
  41225. * Recompute normals when adding a shape
  41226. */
  41227. this.recomputeNormals = true;
  41228. /**
  41229. * This a counter ofr your own usage. It's not set by any SPS functions.
  41230. */
  41231. this.counter = 0;
  41232. /**
  41233. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41234. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  41235. */
  41236. this.vars = {};
  41237. this._positions = new Array();
  41238. this._indices = new Array();
  41239. this._normals = new Array();
  41240. this._colors = new Array();
  41241. this._uvs = new Array();
  41242. this._index = 0; // indices index
  41243. this._updatable = true;
  41244. this._pickable = false;
  41245. this._isVisibilityBoxLocked = false;
  41246. this._alwaysVisible = false;
  41247. this._shapeCounter = 0;
  41248. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  41249. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41250. this._computeParticleColor = true;
  41251. this._computeParticleTexture = true;
  41252. this._computeParticleRotation = true;
  41253. this._computeParticleVertex = false;
  41254. this._computeBoundingBox = false;
  41255. this._cam_axisZ = BABYLON.Vector3.Zero();
  41256. this._cam_axisY = BABYLON.Vector3.Zero();
  41257. this._cam_axisX = BABYLON.Vector3.Zero();
  41258. this._axisX = BABYLON.Axis.X;
  41259. this._axisY = BABYLON.Axis.Y;
  41260. this._axisZ = BABYLON.Axis.Z;
  41261. this._camDir = BABYLON.Vector3.Zero();
  41262. this._rotMatrix = new BABYLON.Matrix();
  41263. this._invertMatrix = new BABYLON.Matrix();
  41264. this._rotated = BABYLON.Vector3.Zero();
  41265. this._quaternion = new BABYLON.Quaternion();
  41266. this._vertex = BABYLON.Vector3.Zero();
  41267. this._normal = BABYLON.Vector3.Zero();
  41268. this._yaw = 0.0;
  41269. this._pitch = 0.0;
  41270. this._roll = 0.0;
  41271. this._halfroll = 0.0;
  41272. this._halfpitch = 0.0;
  41273. this._halfyaw = 0.0;
  41274. this._sinRoll = 0.0;
  41275. this._cosRoll = 0.0;
  41276. this._sinPitch = 0.0;
  41277. this._cosPitch = 0.0;
  41278. this._sinYaw = 0.0;
  41279. this._cosYaw = 0.0;
  41280. this._w = 0.0;
  41281. this._mustUnrotateFixedNormals = false;
  41282. this._minimum = BABYLON.Tmp.Vector3[0];
  41283. this._maximum = BABYLON.Tmp.Vector3[1];
  41284. this._scale = BABYLON.Tmp.Vector3[2];
  41285. this._translation = BABYLON.Tmp.Vector3[3];
  41286. this._minBbox = BABYLON.Tmp.Vector3[4];
  41287. this._maxBbox = BABYLON.Tmp.Vector3[5];
  41288. this._particlesIntersect = false;
  41289. this._bSphereOnly = false;
  41290. this._bSphereRadiusFactor = 1.0;
  41291. this.name = name;
  41292. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41293. this._camera = scene.activeCamera;
  41294. this._pickable = options ? options.isPickable : false;
  41295. this._particlesIntersect = options ? options.particleIntersection : false;
  41296. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  41297. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  41298. if (options && options.updatable) {
  41299. this._updatable = options.updatable;
  41300. }
  41301. else {
  41302. this._updatable = true;
  41303. }
  41304. if (this._pickable) {
  41305. this.pickedParticles = [];
  41306. }
  41307. }
  41308. /**
  41309. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41310. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41311. */
  41312. SolidParticleSystem.prototype.buildMesh = function () {
  41313. if (this.nbParticles === 0) {
  41314. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41315. this.addShape(triangle, 1);
  41316. triangle.dispose();
  41317. }
  41318. this._positions32 = new Float32Array(this._positions);
  41319. this._uvs32 = new Float32Array(this._uvs);
  41320. this._colors32 = new Float32Array(this._colors);
  41321. if (this.recomputeNormals) {
  41322. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41323. }
  41324. this._normals32 = new Float32Array(this._normals);
  41325. this._fixedNormal32 = new Float32Array(this._normals);
  41326. if (this._mustUnrotateFixedNormals) {
  41327. this._unrotateFixedNormals();
  41328. }
  41329. var vertexData = new BABYLON.VertexData();
  41330. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41331. vertexData.indices = this._indices;
  41332. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41333. if (this._uvs32) {
  41334. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41335. ;
  41336. }
  41337. if (this._colors32) {
  41338. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41339. }
  41340. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41341. vertexData.applyToMesh(mesh, this._updatable);
  41342. this.mesh = mesh;
  41343. this.mesh.isPickable = this._pickable;
  41344. // free memory
  41345. this._positions = null;
  41346. this._normals = null;
  41347. this._uvs = null;
  41348. this._colors = null;
  41349. if (!this._updatable) {
  41350. this.particles.length = 0;
  41351. }
  41352. return mesh;
  41353. };
  41354. /**
  41355. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41356. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41357. * Thus the particles generated from `digest()` have their property `position` set yet.
  41358. * `mesh` ( Mesh ) is the mesh to be digested
  41359. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41360. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41361. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41362. */
  41363. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41364. var size = (options && options.facetNb) || 1;
  41365. var number = (options && options.number);
  41366. var delta = (options && options.delta) || 0;
  41367. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41368. var meshInd = mesh.getIndices();
  41369. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41370. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41371. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41372. var f = 0; // facet counter
  41373. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41374. // compute size from number
  41375. if (number) {
  41376. number = (number > totalFacets) ? totalFacets : number;
  41377. size = Math.round(totalFacets / number);
  41378. delta = 0;
  41379. }
  41380. else {
  41381. size = (size > totalFacets) ? totalFacets : size;
  41382. }
  41383. var facetPos = []; // submesh positions
  41384. var facetInd = []; // submesh indices
  41385. var facetUV = []; // submesh UV
  41386. var facetCol = []; // submesh colors
  41387. var barycenter = BABYLON.Tmp.Vector3[0];
  41388. var rand;
  41389. var sizeO = size;
  41390. while (f < totalFacets) {
  41391. size = sizeO + Math.floor((1 + delta) * Math.random());
  41392. if (f > totalFacets - size) {
  41393. size = totalFacets - f;
  41394. }
  41395. // reset temp arrays
  41396. facetPos.length = 0;
  41397. facetInd.length = 0;
  41398. facetUV.length = 0;
  41399. facetCol.length = 0;
  41400. // iterate over "size" facets
  41401. var fi = 0;
  41402. for (var j = f * 3; j < (f + size) * 3; j++) {
  41403. facetInd.push(fi);
  41404. var i = meshInd[j];
  41405. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41406. if (meshUV) {
  41407. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41408. }
  41409. if (meshCol) {
  41410. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41411. }
  41412. fi++;
  41413. }
  41414. // create a model shape for each single particle
  41415. var idx = this.nbParticles;
  41416. var shape = this._posToShape(facetPos);
  41417. var shapeUV = this._uvsToShapeUV(facetUV);
  41418. // compute the barycenter of the shape
  41419. var v;
  41420. for (v = 0; v < shape.length; v++) {
  41421. barycenter.addInPlace(shape[v]);
  41422. }
  41423. barycenter.scaleInPlace(1 / shape.length);
  41424. // shift the shape from its barycenter to the origin
  41425. for (v = 0; v < shape.length; v++) {
  41426. shape[v].subtractInPlace(barycenter);
  41427. }
  41428. var bInfo;
  41429. if (this._particlesIntersect) {
  41430. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  41431. }
  41432. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41433. // add the particle in the SPS
  41434. var currentPos = this._positions.length;
  41435. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  41436. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  41437. // initialize the particle position
  41438. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41439. this._index += shape.length;
  41440. idx++;
  41441. this.nbParticles++;
  41442. this._shapeCounter++;
  41443. f += size;
  41444. }
  41445. return this;
  41446. };
  41447. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  41448. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  41449. var index = 0;
  41450. var idx = 0;
  41451. for (var p = 0; p < this.particles.length; p++) {
  41452. this._particle = this.particles[p];
  41453. this._shape = this._particle._model._shape;
  41454. if (this._particle.rotationQuaternion) {
  41455. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41456. }
  41457. else {
  41458. this._yaw = this._particle.rotation.y;
  41459. this._pitch = this._particle.rotation.x;
  41460. this._roll = this._particle.rotation.z;
  41461. this._quaternionRotationYPR();
  41462. }
  41463. this._quaternionToRotationMatrix();
  41464. this._rotMatrix.invertToRef(this._invertMatrix);
  41465. for (var pt = 0; pt < this._shape.length; pt++) {
  41466. idx = index + pt * 3;
  41467. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  41468. this._fixedNormal32[idx] = this._normal.x;
  41469. this._fixedNormal32[idx + 1] = this._normal.y;
  41470. this._fixedNormal32[idx + 2] = this._normal.z;
  41471. }
  41472. index = idx + 3;
  41473. }
  41474. };
  41475. //reset copy
  41476. SolidParticleSystem.prototype._resetCopy = function () {
  41477. this._copy.position.x = 0;
  41478. this._copy.position.y = 0;
  41479. this._copy.position.z = 0;
  41480. this._copy.rotation.x = 0;
  41481. this._copy.rotation.y = 0;
  41482. this._copy.rotation.z = 0;
  41483. this._copy.rotationQuaternion = null;
  41484. this._copy.scaling.x = 1;
  41485. this._copy.scaling.y = 1;
  41486. this._copy.scaling.z = 1;
  41487. this._copy.uvs.x = 0;
  41488. this._copy.uvs.y = 0;
  41489. this._copy.uvs.z = 1;
  41490. this._copy.uvs.w = 1;
  41491. this._copy.color = null;
  41492. };
  41493. // _meshBuilder : inserts the shape model in the global SPS mesh
  41494. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  41495. var i;
  41496. var u = 0;
  41497. var c = 0;
  41498. var n = 0;
  41499. this._resetCopy();
  41500. if (options && options.positionFunction) {
  41501. options.positionFunction(this._copy, idx, idxInShape);
  41502. this._mustUnrotateFixedNormals = true;
  41503. }
  41504. if (this._copy.rotationQuaternion) {
  41505. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41506. }
  41507. else {
  41508. this._yaw = this._copy.rotation.y;
  41509. this._pitch = this._copy.rotation.x;
  41510. this._roll = this._copy.rotation.z;
  41511. this._quaternionRotationYPR();
  41512. }
  41513. this._quaternionToRotationMatrix();
  41514. for (i = 0; i < shape.length; i++) {
  41515. this._vertex.x = shape[i].x;
  41516. this._vertex.y = shape[i].y;
  41517. this._vertex.z = shape[i].z;
  41518. if (options && options.vertexFunction) {
  41519. options.vertexFunction(this._copy, this._vertex, i);
  41520. }
  41521. this._vertex.x *= this._copy.scaling.x;
  41522. this._vertex.y *= this._copy.scaling.y;
  41523. this._vertex.z *= this._copy.scaling.z;
  41524. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41525. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41526. if (meshUV) {
  41527. 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);
  41528. u += 2;
  41529. }
  41530. if (this._copy.color) {
  41531. this._color = this._copy.color;
  41532. }
  41533. else if (meshCol && meshCol[c] !== undefined) {
  41534. this._color.r = meshCol[c];
  41535. this._color.g = meshCol[c + 1];
  41536. this._color.b = meshCol[c + 2];
  41537. this._color.a = meshCol[c + 3];
  41538. }
  41539. else {
  41540. this._color.r = 1;
  41541. this._color.g = 1;
  41542. this._color.b = 1;
  41543. this._color.a = 1;
  41544. }
  41545. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41546. c += 4;
  41547. if (!this.recomputeNormals && meshNor) {
  41548. this._normal.x = meshNor[n];
  41549. this._normal.y = meshNor[n + 1];
  41550. this._normal.z = meshNor[n + 2];
  41551. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  41552. normals.push(this._normal.x, this._normal.y, this._normal.z);
  41553. n += 3;
  41554. }
  41555. }
  41556. for (i = 0; i < meshInd.length; i++) {
  41557. indices.push(p + meshInd[i]);
  41558. }
  41559. if (this._pickable) {
  41560. var nbfaces = meshInd.length / 3;
  41561. for (i = 0; i < nbfaces; i++) {
  41562. this.pickedParticles.push({ idx: idx, faceId: i });
  41563. }
  41564. }
  41565. return this._copy;
  41566. };
  41567. // returns a shape array from positions array
  41568. SolidParticleSystem.prototype._posToShape = function (positions) {
  41569. var shape = [];
  41570. for (var i = 0; i < positions.length; i += 3) {
  41571. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41572. }
  41573. return shape;
  41574. };
  41575. // returns a shapeUV array from a Vector4 uvs
  41576. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41577. var shapeUV = [];
  41578. if (uvs) {
  41579. for (var i = 0; i < uvs.length; i++)
  41580. shapeUV.push(uvs[i]);
  41581. }
  41582. return shapeUV;
  41583. };
  41584. // adds a new particle object in the particles array
  41585. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  41586. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  41587. this.particles.push(sp);
  41588. return sp;
  41589. };
  41590. /**
  41591. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41592. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  41593. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  41594. * `nb` (positive integer) the number of particles to be created from this model
  41595. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41596. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41597. */
  41598. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41599. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41600. var meshInd = mesh.getIndices();
  41601. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41602. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41603. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41604. var bbInfo;
  41605. if (this._particlesIntersect) {
  41606. bbInfo = mesh.getBoundingInfo();
  41607. }
  41608. var shape = this._posToShape(meshPos);
  41609. var shapeUV = this._uvsToShapeUV(meshUV);
  41610. var posfunc = options ? options.positionFunction : null;
  41611. var vtxfunc = options ? options.vertexFunction : null;
  41612. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41613. // particles
  41614. var sp;
  41615. var currentCopy;
  41616. var idx = this.nbParticles;
  41617. for (var i = 0; i < nb; i++) {
  41618. var currentPos = this._positions.length;
  41619. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  41620. if (this._updatable) {
  41621. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  41622. sp.position.copyFrom(currentCopy.position);
  41623. sp.rotation.copyFrom(currentCopy.rotation);
  41624. if (currentCopy.rotationQuaternion) {
  41625. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  41626. }
  41627. if (currentCopy.color) {
  41628. sp.color.copyFrom(currentCopy.color);
  41629. }
  41630. sp.scaling.copyFrom(currentCopy.scaling);
  41631. sp.uvs.copyFrom(currentCopy.uvs);
  41632. }
  41633. this._index += shape.length;
  41634. idx++;
  41635. }
  41636. this.nbParticles += nb;
  41637. this._shapeCounter++;
  41638. return this._shapeCounter - 1;
  41639. };
  41640. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41641. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41642. this._resetCopy();
  41643. if (particle._model._positionFunction) {
  41644. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41645. }
  41646. if (this._copy.rotationQuaternion) {
  41647. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41648. }
  41649. else {
  41650. this._yaw = this._copy.rotation.y;
  41651. this._pitch = this._copy.rotation.x;
  41652. this._roll = this._copy.rotation.z;
  41653. this._quaternionRotationYPR();
  41654. }
  41655. this._quaternionToRotationMatrix();
  41656. this._shape = particle._model._shape;
  41657. for (var pt = 0; pt < this._shape.length; pt++) {
  41658. this._vertex.x = this._shape[pt].x;
  41659. this._vertex.y = this._shape[pt].y;
  41660. this._vertex.z = this._shape[pt].z;
  41661. if (particle._model._vertexFunction) {
  41662. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41663. }
  41664. this._vertex.x *= this._copy.scaling.x;
  41665. this._vertex.y *= this._copy.scaling.y;
  41666. this._vertex.z *= this._copy.scaling.z;
  41667. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41668. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41669. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41670. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41671. }
  41672. particle.position.x = 0.0;
  41673. particle.position.y = 0.0;
  41674. particle.position.z = 0.0;
  41675. particle.rotation.x = 0.0;
  41676. particle.rotation.y = 0.0;
  41677. particle.rotation.z = 0.0;
  41678. particle.rotationQuaternion = null;
  41679. particle.scaling.x = 1.0;
  41680. particle.scaling.y = 1.0;
  41681. particle.scaling.z = 1.0;
  41682. };
  41683. /**
  41684. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41685. * Returns the SPS.
  41686. */
  41687. SolidParticleSystem.prototype.rebuildMesh = function () {
  41688. for (var p = 0; p < this.particles.length; p++) {
  41689. this._rebuildParticle(this.particles[p]);
  41690. }
  41691. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41692. return this;
  41693. };
  41694. /**
  41695. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41696. * This method calls `updateParticle()` for each particle of the SPS.
  41697. * For an animated SPS, it is usually called within the render loop.
  41698. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  41699. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  41700. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  41701. * Returns the SPS.
  41702. */
  41703. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41704. if (start === void 0) { start = 0; }
  41705. if (end === void 0) { end = this.nbParticles - 1; }
  41706. if (update === void 0) { update = true; }
  41707. if (!this._updatable) {
  41708. return;
  41709. }
  41710. // custom beforeUpdate
  41711. this.beforeUpdateParticles(start, end, update);
  41712. this._cam_axisX.x = 1.0;
  41713. this._cam_axisX.y = 0.0;
  41714. this._cam_axisX.z = 0.0;
  41715. this._cam_axisY.x = 0.0;
  41716. this._cam_axisY.y = 1.0;
  41717. this._cam_axisY.z = 0.0;
  41718. this._cam_axisZ.x = 0.0;
  41719. this._cam_axisZ.y = 0.0;
  41720. this._cam_axisZ.z = 1.0;
  41721. // if the particles will always face the camera
  41722. if (this.billboard) {
  41723. this.mesh.computeWorldMatrix(true);
  41724. // compute the camera position and un-rotate it by the current mesh rotation
  41725. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  41726. this._quaternionToRotationMatrix();
  41727. this._rotMatrix.invertToRef(this._invertMatrix);
  41728. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  41729. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  41730. this._cam_axisZ.normalize();
  41731. // same for camera up vector extracted from the cam view matrix
  41732. var view = this._camera.getViewMatrix(true);
  41733. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  41734. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  41735. this._cam_axisY.normalize();
  41736. this._cam_axisX.normalize();
  41737. }
  41738. }
  41739. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41740. var idx = 0; // current position index in the global array positions32
  41741. var index = 0; // position start index in the global array positions32 of the current particle
  41742. var colidx = 0; // current color index in the global array colors32
  41743. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  41744. var uvidx = 0; // current uv index in the global array uvs32
  41745. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  41746. var pt = 0; // current index in the particle model shape
  41747. if (this.mesh.isFacetDataEnabled) {
  41748. this._computeBoundingBox = true;
  41749. }
  41750. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  41751. if (this._computeBoundingBox) {
  41752. if (start == 0 && end == this.nbParticles - 1) {
  41753. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41754. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41755. }
  41756. else {
  41757. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  41758. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  41759. }
  41760. }
  41761. // particle loop
  41762. index = this.particles[start]._pos;
  41763. var vpos = (index / 3) | 0;
  41764. colorIndex = vpos * 4;
  41765. uvIndex = vpos * 2;
  41766. for (var p = start; p <= end; p++) {
  41767. this._particle = this.particles[p];
  41768. this._shape = this._particle._model._shape;
  41769. this._shapeUV = this._particle._model._shapeUV;
  41770. // call to custom user function to update the particle properties
  41771. this.updateParticle(this._particle);
  41772. // skip the computations for inactive or already invisible particles
  41773. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  41774. // increment indexes for the next particle
  41775. pt = this._shape.length;
  41776. index += pt * 3;
  41777. colorIndex += pt * 4;
  41778. uvIndex += pt * 2;
  41779. continue;
  41780. }
  41781. if (this._particle.isVisible) {
  41782. this._particle._stillInvisible = false; // un-mark permanent invisibility
  41783. // particle rotation matrix
  41784. if (this.billboard) {
  41785. this._particle.rotation.x = 0.0;
  41786. this._particle.rotation.y = 0.0;
  41787. }
  41788. if (this._computeParticleRotation || this.billboard) {
  41789. if (this._particle.rotationQuaternion) {
  41790. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41791. }
  41792. else {
  41793. this._yaw = this._particle.rotation.y;
  41794. this._pitch = this._particle.rotation.x;
  41795. this._roll = this._particle.rotation.z;
  41796. this._quaternionRotationYPR();
  41797. }
  41798. this._quaternionToRotationMatrix();
  41799. }
  41800. // particle vertex loop
  41801. for (pt = 0; pt < this._shape.length; pt++) {
  41802. idx = index + pt * 3;
  41803. colidx = colorIndex + pt * 4;
  41804. uvidx = uvIndex + pt * 2;
  41805. this._vertex.x = this._shape[pt].x;
  41806. this._vertex.y = this._shape[pt].y;
  41807. this._vertex.z = this._shape[pt].z;
  41808. if (this._computeParticleVertex) {
  41809. this.updateParticleVertex(this._particle, this._vertex, pt);
  41810. }
  41811. // positions
  41812. this._vertex.x *= this._particle.scaling.x;
  41813. this._vertex.y *= this._particle.scaling.y;
  41814. this._vertex.z *= this._particle.scaling.z;
  41815. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  41816. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  41817. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  41818. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  41819. 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;
  41820. 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;
  41821. 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;
  41822. if (this._computeBoundingBox) {
  41823. if (this._positions32[idx] < this._minimum.x) {
  41824. this._minimum.x = this._positions32[idx];
  41825. }
  41826. if (this._positions32[idx] > this._maximum.x) {
  41827. this._maximum.x = this._positions32[idx];
  41828. }
  41829. if (this._positions32[idx + 1] < this._minimum.y) {
  41830. this._minimum.y = this._positions32[idx + 1];
  41831. }
  41832. if (this._positions32[idx + 1] > this._maximum.y) {
  41833. this._maximum.y = this._positions32[idx + 1];
  41834. }
  41835. if (this._positions32[idx + 2] < this._minimum.z) {
  41836. this._minimum.z = this._positions32[idx + 2];
  41837. }
  41838. if (this._positions32[idx + 2] > this._maximum.z) {
  41839. this._maximum.z = this._positions32[idx + 2];
  41840. }
  41841. }
  41842. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  41843. if (!this._computeParticleVertex) {
  41844. this._normal.x = this._fixedNormal32[idx];
  41845. this._normal.y = this._fixedNormal32[idx + 1];
  41846. this._normal.z = this._fixedNormal32[idx + 2];
  41847. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]);
  41848. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]);
  41849. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]);
  41850. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41851. 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;
  41852. 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;
  41853. }
  41854. if (this._computeParticleColor) {
  41855. this._colors32[colidx] = this._particle.color.r;
  41856. this._colors32[colidx + 1] = this._particle.color.g;
  41857. this._colors32[colidx + 2] = this._particle.color.b;
  41858. this._colors32[colidx + 3] = this._particle.color.a;
  41859. }
  41860. if (this._computeParticleTexture) {
  41861. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41862. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41863. }
  41864. }
  41865. }
  41866. else {
  41867. this._particle._stillInvisible = true; // mark the particle as invisible
  41868. for (pt = 0; pt < this._shape.length; pt++) {
  41869. idx = index + pt * 3;
  41870. colidx = colorIndex + pt * 4;
  41871. uvidx = uvIndex + pt * 2;
  41872. this._positions32[idx] = 0.0;
  41873. this._positions32[idx + 1] = 0.0;
  41874. this._positions32[idx + 2] = 0.0;
  41875. this._normals32[idx] = 0.0;
  41876. this._normals32[idx + 1] = 0.0;
  41877. this._normals32[idx + 2] = 0.0;
  41878. if (this._computeParticleColor) {
  41879. this._colors32[colidx] = this._particle.color.r;
  41880. this._colors32[colidx + 1] = this._particle.color.g;
  41881. this._colors32[colidx + 2] = this._particle.color.b;
  41882. this._colors32[colidx + 3] = this._particle.color.a;
  41883. }
  41884. if (this._computeParticleTexture) {
  41885. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41886. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41887. }
  41888. }
  41889. }
  41890. // if the particle intersections must be computed : update the bbInfo
  41891. if (this._particlesIntersect) {
  41892. var bInfo = this._particle._boundingInfo;
  41893. var bBox = bInfo.boundingBox;
  41894. var bSphere = bInfo.boundingSphere;
  41895. if (!this._bSphereOnly) {
  41896. // place, scale and rotate the particle bbox within the SPS local system, then update it
  41897. for (var b = 0; b < bBox.vectors.length; b++) {
  41898. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  41899. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  41900. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  41901. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  41902. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  41903. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  41904. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  41905. 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;
  41906. 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;
  41907. 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;
  41908. }
  41909. bBox._update(this.mesh._worldMatrix);
  41910. }
  41911. // place and scale the particle bouding sphere in the SPS local system, then update it
  41912. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  41913. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  41914. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  41915. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  41916. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  41917. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  41918. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  41919. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  41920. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  41921. 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));
  41922. bSphere._update(this.mesh._worldMatrix);
  41923. }
  41924. // increment indexes for the next particle
  41925. index = idx + 3;
  41926. colorIndex = colidx + 4;
  41927. uvIndex = uvidx + 2;
  41928. }
  41929. // if the VBO must be updated
  41930. if (update) {
  41931. if (this._computeParticleColor) {
  41932. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41933. }
  41934. if (this._computeParticleTexture) {
  41935. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41936. }
  41937. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41938. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  41939. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  41940. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  41941. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  41942. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  41943. for (var i = 0; i < this._normals32.length; i++) {
  41944. this._fixedNormal32[i] = this._normals32[i];
  41945. }
  41946. }
  41947. if (!this.mesh.areNormalsFrozen) {
  41948. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41949. }
  41950. }
  41951. }
  41952. if (this._computeBoundingBox) {
  41953. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  41954. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  41955. }
  41956. this.afterUpdateParticles(start, end, update);
  41957. return this;
  41958. };
  41959. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  41960. this._halfroll = this._roll * 0.5;
  41961. this._halfpitch = this._pitch * 0.5;
  41962. this._halfyaw = this._yaw * 0.5;
  41963. this._sinRoll = Math.sin(this._halfroll);
  41964. this._cosRoll = Math.cos(this._halfroll);
  41965. this._sinPitch = Math.sin(this._halfpitch);
  41966. this._cosPitch = Math.cos(this._halfpitch);
  41967. this._sinYaw = Math.sin(this._halfyaw);
  41968. this._cosYaw = Math.cos(this._halfyaw);
  41969. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  41970. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  41971. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  41972. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  41973. };
  41974. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  41975. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  41976. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  41977. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  41978. this._rotMatrix.m[3] = 0;
  41979. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  41980. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  41981. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  41982. this._rotMatrix.m[7] = 0;
  41983. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  41984. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  41985. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  41986. this._rotMatrix.m[11] = 0;
  41987. this._rotMatrix.m[12] = 0;
  41988. this._rotMatrix.m[13] = 0;
  41989. this._rotMatrix.m[14] = 0;
  41990. this._rotMatrix.m[15] = 1.0;
  41991. };
  41992. /**
  41993. * Disposes the SPS.
  41994. * Returns nothing.
  41995. */
  41996. SolidParticleSystem.prototype.dispose = function () {
  41997. this.mesh.dispose();
  41998. this.vars = null;
  41999. // drop references to internal big arrays for the GC
  42000. this._positions = null;
  42001. this._indices = null;
  42002. this._normals = null;
  42003. this._uvs = null;
  42004. this._colors = null;
  42005. this._positions32 = null;
  42006. this._normals32 = null;
  42007. this._fixedNormal32 = null;
  42008. this._uvs32 = null;
  42009. this._colors32 = null;
  42010. this.pickedParticles = null;
  42011. };
  42012. /**
  42013. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42014. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42015. * Returns the SPS.
  42016. */
  42017. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42018. if (!this._isVisibilityBoxLocked) {
  42019. this.mesh.refreshBoundingInfo();
  42020. }
  42021. return this;
  42022. };
  42023. /**
  42024. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42025. * @param size the size (float) of the visibility box
  42026. * note : this doesn't lock the SPS mesh bounding box.
  42027. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42028. */
  42029. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42030. var vis = size / 2;
  42031. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42032. };
  42033. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42034. // getter and setter
  42035. get: function () {
  42036. return this._alwaysVisible;
  42037. },
  42038. /**
  42039. * Sets the SPS as always visible or not
  42040. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42041. */
  42042. set: function (val) {
  42043. this._alwaysVisible = val;
  42044. this.mesh.alwaysSelectAsActiveMesh = val;
  42045. },
  42046. enumerable: true,
  42047. configurable: true
  42048. });
  42049. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42050. get: function () {
  42051. return this._isVisibilityBoxLocked;
  42052. },
  42053. /**
  42054. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42055. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42056. */
  42057. set: function (val) {
  42058. this._isVisibilityBoxLocked = val;
  42059. this.mesh.getBoundingInfo().isLocked = val;
  42060. },
  42061. enumerable: true,
  42062. configurable: true
  42063. });
  42064. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42065. // getters
  42066. get: function () {
  42067. return this._computeParticleRotation;
  42068. },
  42069. // Optimizer setters
  42070. /**
  42071. * Tells to `setParticles()` to compute the particle rotations or not.
  42072. * Default value : true. The SPS is faster when it's set to false.
  42073. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42074. */
  42075. set: function (val) {
  42076. this._computeParticleRotation = val;
  42077. },
  42078. enumerable: true,
  42079. configurable: true
  42080. });
  42081. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42082. get: function () {
  42083. return this._computeParticleColor;
  42084. },
  42085. /**
  42086. * Tells to `setParticles()` to compute the particle colors or not.
  42087. * Default value : true. The SPS is faster when it's set to false.
  42088. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42089. */
  42090. set: function (val) {
  42091. this._computeParticleColor = val;
  42092. },
  42093. enumerable: true,
  42094. configurable: true
  42095. });
  42096. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42097. get: function () {
  42098. return this._computeParticleTexture;
  42099. },
  42100. /**
  42101. * Tells to `setParticles()` to compute the particle textures or not.
  42102. * Default value : true. The SPS is faster when it's set to false.
  42103. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42104. */
  42105. set: function (val) {
  42106. this._computeParticleTexture = val;
  42107. },
  42108. enumerable: true,
  42109. configurable: true
  42110. });
  42111. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42112. get: function () {
  42113. return this._computeParticleVertex;
  42114. },
  42115. /**
  42116. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42117. * Default value : false. The SPS is faster when it's set to false.
  42118. * Note : the particle custom vertex positions aren't stored values.
  42119. */
  42120. set: function (val) {
  42121. this._computeParticleVertex = val;
  42122. },
  42123. enumerable: true,
  42124. configurable: true
  42125. });
  42126. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42127. get: function () {
  42128. return this._computeBoundingBox;
  42129. },
  42130. /**
  42131. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42132. */
  42133. set: function (val) {
  42134. this._computeBoundingBox = val;
  42135. },
  42136. enumerable: true,
  42137. configurable: true
  42138. });
  42139. // =======================================================================
  42140. // Particle behavior logic
  42141. // these following methods may be overwritten by the user to fit his needs
  42142. /**
  42143. * This function does nothing. It may be overwritten to set all the particle first values.
  42144. * The SPS doesn't call this function, you may have to call it by your own.
  42145. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42146. */
  42147. SolidParticleSystem.prototype.initParticles = function () {
  42148. };
  42149. /**
  42150. * This function does nothing. It may be overwritten to recycle a particle.
  42151. * The SPS doesn't call this function, you may have to call it by your own.
  42152. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42153. */
  42154. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42155. return particle;
  42156. };
  42157. /**
  42158. * Updates a particle : this function should be overwritten by the user.
  42159. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42160. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42161. * ex : just set a particle position or velocity and recycle conditions
  42162. */
  42163. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42164. return particle;
  42165. };
  42166. /**
  42167. * Updates a vertex of a particle : it can be overwritten by the user.
  42168. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42169. * @param particle the current particle
  42170. * @param vertex the current index of the current particle
  42171. * @param pt the index of the current vertex in the particle shape
  42172. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  42173. * ex : just set a vertex particle position
  42174. */
  42175. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42176. return vertex;
  42177. };
  42178. /**
  42179. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42180. * This does nothing and may be overwritten by the user.
  42181. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42182. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42183. * @param update the boolean update value actually passed to setParticles()
  42184. */
  42185. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42186. };
  42187. /**
  42188. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42189. * This will be passed three parameters.
  42190. * This does nothing and may be overwritten by the user.
  42191. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42192. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42193. * @param update the boolean update value actually passed to setParticles()
  42194. */
  42195. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42196. };
  42197. return SolidParticleSystem;
  42198. }());
  42199. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42200. })(BABYLON || (BABYLON = {}));
  42201. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  42202. /// <reference path="babylon.mesh.ts" />
  42203. var BABYLON;
  42204. (function (BABYLON) {
  42205. var GroundMesh = (function (_super) {
  42206. __extends(GroundMesh, _super);
  42207. function GroundMesh(name, scene) {
  42208. var _this = _super.call(this, name, scene) || this;
  42209. _this.generateOctree = false;
  42210. _this._worldInverse = new BABYLON.Matrix();
  42211. return _this;
  42212. }
  42213. GroundMesh.prototype.getClassName = function () {
  42214. return "GroundMesh";
  42215. };
  42216. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42217. get: function () {
  42218. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42219. },
  42220. enumerable: true,
  42221. configurable: true
  42222. });
  42223. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42224. get: function () {
  42225. return this._subdivisionsX;
  42226. },
  42227. enumerable: true,
  42228. configurable: true
  42229. });
  42230. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42231. get: function () {
  42232. return this._subdivisionsY;
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42238. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42239. this._subdivisionsX = chunksCount;
  42240. this._subdivisionsY = chunksCount;
  42241. this.subdivide(chunksCount);
  42242. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42243. };
  42244. /**
  42245. * Returns a height (y) value in the Worl system :
  42246. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42247. * Returns the ground y position if (x, z) are outside the ground surface.
  42248. */
  42249. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42250. var world = this.getWorldMatrix();
  42251. var invMat = BABYLON.Tmp.Matrix[5];
  42252. world.invertToRef(invMat);
  42253. var tmpVect = BABYLON.Tmp.Vector3[8];
  42254. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42255. x = tmpVect.x;
  42256. z = tmpVect.z;
  42257. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42258. return this.position.y;
  42259. }
  42260. if (!this._heightQuads || this._heightQuads.length == 0) {
  42261. this._initHeightQuads();
  42262. this._computeHeightQuads();
  42263. }
  42264. var facet = this._getFacetAt(x, z);
  42265. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42266. // return y in the World system
  42267. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42268. return tmpVect.y;
  42269. };
  42270. /**
  42271. * Returns a normalized vector (Vector3) orthogonal to the ground
  42272. * at the ground coordinates (x, z) expressed in the World system.
  42273. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42274. */
  42275. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42276. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42277. this.getNormalAtCoordinatesToRef(x, z, normal);
  42278. return normal;
  42279. };
  42280. /**
  42281. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42282. * at the ground coordinates (x, z) expressed in the World system.
  42283. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42284. * Returns the GroundMesh.
  42285. */
  42286. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42287. var world = this.getWorldMatrix();
  42288. var tmpMat = BABYLON.Tmp.Matrix[5];
  42289. world.invertToRef(tmpMat);
  42290. var tmpVect = BABYLON.Tmp.Vector3[8];
  42291. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42292. x = tmpVect.x;
  42293. z = tmpVect.z;
  42294. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42295. return this;
  42296. }
  42297. if (!this._heightQuads || this._heightQuads.length == 0) {
  42298. this._initHeightQuads();
  42299. this._computeHeightQuads();
  42300. }
  42301. var facet = this._getFacetAt(x, z);
  42302. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42303. return this;
  42304. };
  42305. /**
  42306. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42307. * if the ground has been updated.
  42308. * This can be used in the render loop.
  42309. * Returns the GroundMesh.
  42310. */
  42311. GroundMesh.prototype.updateCoordinateHeights = function () {
  42312. if (!this._heightQuads || this._heightQuads.length == 0) {
  42313. this._initHeightQuads();
  42314. }
  42315. this._computeHeightQuads();
  42316. return this;
  42317. };
  42318. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42319. GroundMesh.prototype._getFacetAt = function (x, z) {
  42320. // retrieve col and row from x, z coordinates in the ground local system
  42321. var subdivisionsX = this._subdivisionsX;
  42322. var subdivisionsY = this._subdivisionsY;
  42323. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42324. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42325. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42326. var facet;
  42327. if (z < quad.slope.x * x + quad.slope.y) {
  42328. facet = quad.facet1;
  42329. }
  42330. else {
  42331. facet = quad.facet2;
  42332. }
  42333. return facet;
  42334. };
  42335. // Creates and populates the heightMap array with "facet" elements :
  42336. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42337. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42338. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42339. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42340. // Returns the GroundMesh.
  42341. GroundMesh.prototype._initHeightQuads = function () {
  42342. var subdivisionsX = this._subdivisionsX;
  42343. var subdivisionsY = this._subdivisionsY;
  42344. this._heightQuads = new Array();
  42345. for (var row = 0; row < subdivisionsY; row++) {
  42346. for (var col = 0; col < subdivisionsX; col++) {
  42347. 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) };
  42348. this._heightQuads[row * subdivisionsX + col] = quad;
  42349. }
  42350. }
  42351. return this;
  42352. };
  42353. // Compute each quad element values and update the the heightMap array :
  42354. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42355. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42356. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42357. // Returns the GroundMesh.
  42358. GroundMesh.prototype._computeHeightQuads = function () {
  42359. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42360. var v1 = BABYLON.Tmp.Vector3[3];
  42361. var v2 = BABYLON.Tmp.Vector3[2];
  42362. var v3 = BABYLON.Tmp.Vector3[1];
  42363. var v4 = BABYLON.Tmp.Vector3[0];
  42364. var v1v2 = BABYLON.Tmp.Vector3[4];
  42365. var v1v3 = BABYLON.Tmp.Vector3[5];
  42366. var v1v4 = BABYLON.Tmp.Vector3[6];
  42367. var norm1 = BABYLON.Tmp.Vector3[7];
  42368. var norm2 = BABYLON.Tmp.Vector3[8];
  42369. var i = 0;
  42370. var j = 0;
  42371. var k = 0;
  42372. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42373. var h = 0;
  42374. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42375. var d2 = 0;
  42376. var subdivisionsX = this._subdivisionsX;
  42377. var subdivisionsY = this._subdivisionsY;
  42378. for (var row = 0; row < subdivisionsY; row++) {
  42379. for (var col = 0; col < subdivisionsX; col++) {
  42380. i = col * 3;
  42381. j = row * (subdivisionsX + 1) * 3;
  42382. k = (row + 1) * (subdivisionsX + 1) * 3;
  42383. v1.x = positions[j + i];
  42384. v1.y = positions[j + i + 1];
  42385. v1.z = positions[j + i + 2];
  42386. v2.x = positions[j + i + 3];
  42387. v2.y = positions[j + i + 4];
  42388. v2.z = positions[j + i + 5];
  42389. v3.x = positions[k + i];
  42390. v3.y = positions[k + i + 1];
  42391. v3.z = positions[k + i + 2];
  42392. v4.x = positions[k + i + 3];
  42393. v4.y = positions[k + i + 4];
  42394. v4.z = positions[k + i + 5];
  42395. // 2D slope V1V4
  42396. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42397. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42398. // facet equations :
  42399. // we compute each facet normal vector
  42400. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42401. // we compute the value d by applying the equation to v1 which belongs to the plane
  42402. // then we store the facet equation in a Vector4
  42403. v2.subtractToRef(v1, v1v2);
  42404. v3.subtractToRef(v1, v1v3);
  42405. v4.subtractToRef(v1, v1v4);
  42406. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42407. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42408. norm1.normalize();
  42409. norm2.normalize();
  42410. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42411. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42412. var quad = this._heightQuads[row * subdivisionsX + col];
  42413. quad.slope.copyFromFloats(cd, h);
  42414. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42415. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42416. }
  42417. }
  42418. return this;
  42419. };
  42420. GroundMesh.prototype.serialize = function (serializationObject) {
  42421. _super.prototype.serialize.call(this, serializationObject);
  42422. serializationObject.subdivisionsX = this._subdivisionsX;
  42423. serializationObject.subdivisionsY = this._subdivisionsY;
  42424. serializationObject.minX = this._minX;
  42425. serializationObject.maxX = this._maxX;
  42426. serializationObject.minZ = this._minZ;
  42427. serializationObject.maxZ = this._maxZ;
  42428. serializationObject.width = this._width;
  42429. serializationObject.height = this._height;
  42430. };
  42431. GroundMesh.Parse = function (parsedMesh, scene) {
  42432. var result = new GroundMesh(parsedMesh.name, scene);
  42433. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42434. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42435. result._minX = parsedMesh.minX;
  42436. result._maxX = parsedMesh.maxX;
  42437. result._minZ = parsedMesh.minZ;
  42438. result._maxZ = parsedMesh.maxZ;
  42439. result._width = parsedMesh.width;
  42440. result._height = parsedMesh.height;
  42441. return result;
  42442. };
  42443. return GroundMesh;
  42444. }(BABYLON.Mesh));
  42445. BABYLON.GroundMesh = GroundMesh;
  42446. })(BABYLON || (BABYLON = {}));
  42447. //# sourceMappingURL=babylon.groundMesh.js.map
  42448. var BABYLON;
  42449. (function (BABYLON) {
  42450. /**
  42451. * Creates an instance based on a source mesh.
  42452. */
  42453. var InstancedMesh = (function (_super) {
  42454. __extends(InstancedMesh, _super);
  42455. function InstancedMesh(name, source) {
  42456. var _this = _super.call(this, name, source.getScene()) || this;
  42457. source.instances.push(_this);
  42458. _this._sourceMesh = source;
  42459. _this.position.copyFrom(source.position);
  42460. _this.rotation.copyFrom(source.rotation);
  42461. _this.scaling.copyFrom(source.scaling);
  42462. if (source.rotationQuaternion) {
  42463. _this.rotationQuaternion = source.rotationQuaternion.clone();
  42464. }
  42465. _this.infiniteDistance = source.infiniteDistance;
  42466. _this.setPivotMatrix(source.getPivotMatrix());
  42467. _this.refreshBoundingInfo();
  42468. _this._syncSubMeshes();
  42469. return _this;
  42470. }
  42471. /**
  42472. * Returns the string "InstancedMesh".
  42473. */
  42474. InstancedMesh.prototype.getClassName = function () {
  42475. return "InstancedMesh";
  42476. };
  42477. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  42478. // Methods
  42479. get: function () {
  42480. return this._sourceMesh.receiveShadows;
  42481. },
  42482. enumerable: true,
  42483. configurable: true
  42484. });
  42485. Object.defineProperty(InstancedMesh.prototype, "material", {
  42486. get: function () {
  42487. return this._sourceMesh.material;
  42488. },
  42489. enumerable: true,
  42490. configurable: true
  42491. });
  42492. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  42493. get: function () {
  42494. return this._sourceMesh.visibility;
  42495. },
  42496. enumerable: true,
  42497. configurable: true
  42498. });
  42499. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  42500. get: function () {
  42501. return this._sourceMesh.skeleton;
  42502. },
  42503. enumerable: true,
  42504. configurable: true
  42505. });
  42506. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  42507. get: function () {
  42508. return this._sourceMesh.renderingGroupId;
  42509. },
  42510. enumerable: true,
  42511. configurable: true
  42512. });
  42513. /**
  42514. * Returns the total number of vertices (integer).
  42515. */
  42516. InstancedMesh.prototype.getTotalVertices = function () {
  42517. return this._sourceMesh.getTotalVertices();
  42518. };
  42519. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  42520. get: function () {
  42521. return this._sourceMesh;
  42522. },
  42523. enumerable: true,
  42524. configurable: true
  42525. });
  42526. /**
  42527. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  42528. */
  42529. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  42530. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  42531. };
  42532. /**
  42533. * Sets the vertex data of the mesh geometry for the requested `kind`.
  42534. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  42535. * The `data` are either a numeric array either a Float32Array.
  42536. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  42537. * 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).
  42538. * Note that a new underlying VertexBuffer object is created each call.
  42539. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  42540. *
  42541. * Possible `kind` values :
  42542. * - BABYLON.VertexBuffer.PositionKind
  42543. * - BABYLON.VertexBuffer.UVKind
  42544. * - BABYLON.VertexBuffer.UV2Kind
  42545. * - BABYLON.VertexBuffer.UV3Kind
  42546. * - BABYLON.VertexBuffer.UV4Kind
  42547. * - BABYLON.VertexBuffer.UV5Kind
  42548. * - BABYLON.VertexBuffer.UV6Kind
  42549. * - BABYLON.VertexBuffer.ColorKind
  42550. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42551. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42552. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42553. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42554. *
  42555. * Returns the Mesh.
  42556. */
  42557. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42558. if (this.sourceMesh) {
  42559. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  42560. }
  42561. return this.sourceMesh;
  42562. };
  42563. /**
  42564. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  42565. * If the mesh has no geometry, it is simply returned as it is.
  42566. * The `data` are either a numeric array either a Float32Array.
  42567. * No new underlying VertexBuffer object is created.
  42568. * 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.
  42569. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  42570. *
  42571. * Possible `kind` values :
  42572. * - BABYLON.VertexBuffer.PositionKind
  42573. * - BABYLON.VertexBuffer.UVKind
  42574. * - BABYLON.VertexBuffer.UV2Kind
  42575. * - BABYLON.VertexBuffer.UV3Kind
  42576. * - BABYLON.VertexBuffer.UV4Kind
  42577. * - BABYLON.VertexBuffer.UV5Kind
  42578. * - BABYLON.VertexBuffer.UV6Kind
  42579. * - BABYLON.VertexBuffer.ColorKind
  42580. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42581. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42582. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42583. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42584. *
  42585. * Returns the Mesh.
  42586. */
  42587. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  42588. if (this.sourceMesh) {
  42589. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  42590. }
  42591. return this.sourceMesh;
  42592. };
  42593. /**
  42594. * Sets the mesh indices.
  42595. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  42596. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  42597. * This method creates a new index buffer each call.
  42598. * Returns the Mesh.
  42599. */
  42600. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  42601. if (this.sourceMesh) {
  42602. this.sourceMesh.setIndices(indices, totalVertices);
  42603. }
  42604. return this.sourceMesh;
  42605. };
  42606. /**
  42607. * Boolean : True if the mesh owns the requested kind of data.
  42608. */
  42609. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  42610. return this._sourceMesh.isVerticesDataPresent(kind);
  42611. };
  42612. /**
  42613. * Returns an array of indices (IndicesArray).
  42614. */
  42615. InstancedMesh.prototype.getIndices = function () {
  42616. return this._sourceMesh.getIndices();
  42617. };
  42618. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  42619. get: function () {
  42620. return this._sourceMesh._positions;
  42621. },
  42622. enumerable: true,
  42623. configurable: true
  42624. });
  42625. /**
  42626. * Sets a new updated BoundingInfo to the mesh.
  42627. * Returns the mesh.
  42628. */
  42629. InstancedMesh.prototype.refreshBoundingInfo = function () {
  42630. var meshBB = this._sourceMesh.getBoundingInfo();
  42631. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  42632. this._updateBoundingInfo();
  42633. return this;
  42634. };
  42635. InstancedMesh.prototype._preActivate = function () {
  42636. if (this._currentLOD) {
  42637. this._currentLOD._preActivate();
  42638. }
  42639. return this;
  42640. };
  42641. InstancedMesh.prototype._activate = function (renderId) {
  42642. if (this._currentLOD) {
  42643. this._currentLOD._registerInstanceForRenderId(this, renderId);
  42644. }
  42645. return this;
  42646. };
  42647. /**
  42648. * Returns the current associated LOD AbstractMesh.
  42649. */
  42650. InstancedMesh.prototype.getLOD = function (camera) {
  42651. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  42652. if (this._currentLOD === this.sourceMesh) {
  42653. return this;
  42654. }
  42655. return this._currentLOD;
  42656. };
  42657. InstancedMesh.prototype._syncSubMeshes = function () {
  42658. this.releaseSubMeshes();
  42659. if (this._sourceMesh.subMeshes) {
  42660. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  42661. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  42662. }
  42663. }
  42664. return this;
  42665. };
  42666. InstancedMesh.prototype._generatePointsArray = function () {
  42667. return this._sourceMesh._generatePointsArray();
  42668. };
  42669. /**
  42670. * Creates a new InstancedMesh from the current mesh.
  42671. * - name (string) : the cloned mesh name
  42672. * - newParent (optional Node) : the optional Node to parent the clone to.
  42673. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  42674. *
  42675. * Returns the clone.
  42676. */
  42677. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42678. var result = this._sourceMesh.createInstance(name);
  42679. // Deep copy
  42680. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  42681. // Bounding info
  42682. this.refreshBoundingInfo();
  42683. // Parent
  42684. if (newParent) {
  42685. result.parent = newParent;
  42686. }
  42687. if (!doNotCloneChildren) {
  42688. // Children
  42689. for (var index = 0; index < this.getScene().meshes.length; index++) {
  42690. var mesh = this.getScene().meshes[index];
  42691. if (mesh.parent === this) {
  42692. mesh.clone(mesh.name, result);
  42693. }
  42694. }
  42695. }
  42696. result.computeWorldMatrix(true);
  42697. return result;
  42698. };
  42699. /**
  42700. * Disposes the InstancedMesh.
  42701. * Returns nothing.
  42702. */
  42703. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  42704. // Remove from mesh
  42705. var index = this._sourceMesh.instances.indexOf(this);
  42706. this._sourceMesh.instances.splice(index, 1);
  42707. _super.prototype.dispose.call(this, doNotRecurse);
  42708. };
  42709. return InstancedMesh;
  42710. }(BABYLON.AbstractMesh));
  42711. BABYLON.InstancedMesh = InstancedMesh;
  42712. })(BABYLON || (BABYLON = {}));
  42713. //# sourceMappingURL=babylon.instancedMesh.js.map
  42714. /// <reference path="babylon.mesh.ts" />
  42715. var BABYLON;
  42716. (function (BABYLON) {
  42717. var LinesMesh = (function (_super) {
  42718. __extends(LinesMesh, _super);
  42719. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  42720. if (parent === void 0) { parent = null; }
  42721. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42722. _this.useVertexColor = useVertexColor;
  42723. _this.color = new BABYLON.Color3(1, 1, 1);
  42724. _this.alpha = 1;
  42725. if (source) {
  42726. _this.color = source.color.clone();
  42727. _this.alpha = source.alpha;
  42728. _this.useVertexColor = source.useVertexColor;
  42729. }
  42730. _this._intersectionThreshold = 0.1;
  42731. var options = {
  42732. attributes: [BABYLON.VertexBuffer.PositionKind],
  42733. uniforms: ["world", "viewProjection"],
  42734. needAlphaBlending: false,
  42735. };
  42736. if (!useVertexColor) {
  42737. options.uniforms.push("color");
  42738. options.needAlphaBlending = true;
  42739. }
  42740. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  42741. return _this;
  42742. }
  42743. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42744. /**
  42745. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42746. * This margin is expressed in world space coordinates, so its value may vary.
  42747. * Default value is 0.1
  42748. * @returns the intersection Threshold value.
  42749. */
  42750. get: function () {
  42751. return this._intersectionThreshold;
  42752. },
  42753. /**
  42754. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42755. * This margin is expressed in world space coordinates, so its value may vary.
  42756. * @param value the new threshold to apply
  42757. */
  42758. set: function (value) {
  42759. if (this._intersectionThreshold === value) {
  42760. return;
  42761. }
  42762. this._intersectionThreshold = value;
  42763. if (this.geometry) {
  42764. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42765. }
  42766. },
  42767. enumerable: true,
  42768. configurable: true
  42769. });
  42770. /**
  42771. * Returns the string "LineMesh"
  42772. */
  42773. LinesMesh.prototype.getClassName = function () {
  42774. return "LinesMesh";
  42775. };
  42776. Object.defineProperty(LinesMesh.prototype, "material", {
  42777. get: function () {
  42778. return this._colorShader;
  42779. },
  42780. enumerable: true,
  42781. configurable: true
  42782. });
  42783. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42784. get: function () {
  42785. return false;
  42786. },
  42787. enumerable: true,
  42788. configurable: true
  42789. });
  42790. LinesMesh.prototype.createInstance = function (name) {
  42791. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42792. return null;
  42793. };
  42794. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42795. // VBOs
  42796. this._geometry._bind(this._colorShader.getEffect());
  42797. // Color
  42798. if (!this.useVertexColor) {
  42799. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42800. }
  42801. return this;
  42802. };
  42803. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42804. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42805. return this;
  42806. }
  42807. var engine = this.getScene().getEngine();
  42808. // Draw order
  42809. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42810. return this;
  42811. };
  42812. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42813. this._colorShader.dispose();
  42814. _super.prototype.dispose.call(this, doNotRecurse);
  42815. };
  42816. /**
  42817. * Returns a new LineMesh object cloned from the current one.
  42818. */
  42819. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42820. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42821. };
  42822. return LinesMesh;
  42823. }(BABYLON.Mesh));
  42824. BABYLON.LinesMesh = LinesMesh;
  42825. })(BABYLON || (BABYLON = {}));
  42826. //# sourceMappingURL=babylon.linesMesh.js.map
  42827. var BABYLON;
  42828. (function (BABYLON) {
  42829. var ShaderMaterial = (function (_super) {
  42830. __extends(ShaderMaterial, _super);
  42831. function ShaderMaterial(name, scene, shaderPath, options) {
  42832. var _this = _super.call(this, name, scene) || this;
  42833. _this._textures = {};
  42834. _this._textureArrays = {};
  42835. _this._floats = {};
  42836. _this._floatsArrays = {};
  42837. _this._colors3 = {};
  42838. _this._colors3Arrays = {};
  42839. _this._colors4 = {};
  42840. _this._vectors2 = {};
  42841. _this._vectors3 = {};
  42842. _this._vectors4 = {};
  42843. _this._matrices = {};
  42844. _this._matrices3x3 = {};
  42845. _this._matrices2x2 = {};
  42846. _this._vectors3Arrays = {};
  42847. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  42848. _this._shaderPath = shaderPath;
  42849. options.needAlphaBlending = options.needAlphaBlending || false;
  42850. options.needAlphaTesting = options.needAlphaTesting || false;
  42851. options.attributes = options.attributes || ["position", "normal", "uv"];
  42852. options.uniforms = options.uniforms || ["worldViewProjection"];
  42853. options.uniformBuffers = options.uniformBuffers || [];
  42854. options.samplers = options.samplers || [];
  42855. options.defines = options.defines || [];
  42856. _this._options = options;
  42857. return _this;
  42858. }
  42859. ShaderMaterial.prototype.getClassName = function () {
  42860. return "ShaderMaterial";
  42861. };
  42862. ShaderMaterial.prototype.needAlphaBlending = function () {
  42863. return this._options.needAlphaBlending;
  42864. };
  42865. ShaderMaterial.prototype.needAlphaTesting = function () {
  42866. return this._options.needAlphaTesting;
  42867. };
  42868. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  42869. if (this._options.uniforms.indexOf(uniformName) === -1) {
  42870. this._options.uniforms.push(uniformName);
  42871. }
  42872. };
  42873. ShaderMaterial.prototype.setTexture = function (name, texture) {
  42874. if (this._options.samplers.indexOf(name) === -1) {
  42875. this._options.samplers.push(name);
  42876. }
  42877. this._textures[name] = texture;
  42878. return this;
  42879. };
  42880. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  42881. if (this._options.samplers.indexOf(name) === -1) {
  42882. this._options.samplers.push(name);
  42883. }
  42884. this._checkUniform(name);
  42885. this._textureArrays[name] = textures;
  42886. return this;
  42887. };
  42888. ShaderMaterial.prototype.setFloat = function (name, value) {
  42889. this._checkUniform(name);
  42890. this._floats[name] = value;
  42891. return this;
  42892. };
  42893. ShaderMaterial.prototype.setFloats = function (name, value) {
  42894. this._checkUniform(name);
  42895. this._floatsArrays[name] = value;
  42896. return this;
  42897. };
  42898. ShaderMaterial.prototype.setColor3 = function (name, value) {
  42899. this._checkUniform(name);
  42900. this._colors3[name] = value;
  42901. return this;
  42902. };
  42903. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  42904. this._checkUniform(name);
  42905. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  42906. color.toArray(arr, arr.length);
  42907. return arr;
  42908. }, []);
  42909. return this;
  42910. };
  42911. ShaderMaterial.prototype.setColor4 = function (name, value) {
  42912. this._checkUniform(name);
  42913. this._colors4[name] = value;
  42914. return this;
  42915. };
  42916. ShaderMaterial.prototype.setVector2 = function (name, value) {
  42917. this._checkUniform(name);
  42918. this._vectors2[name] = value;
  42919. return this;
  42920. };
  42921. ShaderMaterial.prototype.setVector3 = function (name, value) {
  42922. this._checkUniform(name);
  42923. this._vectors3[name] = value;
  42924. return this;
  42925. };
  42926. ShaderMaterial.prototype.setVector4 = function (name, value) {
  42927. this._checkUniform(name);
  42928. this._vectors4[name] = value;
  42929. return this;
  42930. };
  42931. ShaderMaterial.prototype.setMatrix = function (name, value) {
  42932. this._checkUniform(name);
  42933. this._matrices[name] = value;
  42934. return this;
  42935. };
  42936. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  42937. this._checkUniform(name);
  42938. this._matrices3x3[name] = value;
  42939. return this;
  42940. };
  42941. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  42942. this._checkUniform(name);
  42943. this._matrices2x2[name] = value;
  42944. return this;
  42945. };
  42946. ShaderMaterial.prototype.setArray3 = function (name, value) {
  42947. this._checkUniform(name);
  42948. this._vectors3Arrays[name] = value;
  42949. return this;
  42950. };
  42951. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  42952. if (!mesh) {
  42953. return true;
  42954. }
  42955. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  42956. return false;
  42957. }
  42958. return false;
  42959. };
  42960. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  42961. var scene = this.getScene();
  42962. var engine = scene.getEngine();
  42963. if (!this.checkReadyOnEveryCall) {
  42964. if (this._renderId === scene.getRenderId()) {
  42965. if (this._checkCache(scene, mesh, useInstances)) {
  42966. return true;
  42967. }
  42968. }
  42969. }
  42970. // Instances
  42971. var defines = [];
  42972. var attribs = [];
  42973. var fallbacks = new BABYLON.EffectFallbacks();
  42974. if (useInstances) {
  42975. defines.push("#define INSTANCES");
  42976. }
  42977. for (var index = 0; index < this._options.defines.length; index++) {
  42978. defines.push(this._options.defines[index]);
  42979. }
  42980. for (var index = 0; index < this._options.attributes.length; index++) {
  42981. attribs.push(this._options.attributes[index]);
  42982. }
  42983. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  42984. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42985. defines.push("#define VERTEXCOLOR");
  42986. }
  42987. // Bones
  42988. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  42989. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42990. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42991. if (mesh.numBoneInfluencers > 4) {
  42992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42994. }
  42995. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42996. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42997. fallbacks.addCPUSkinningFallback(0, mesh);
  42998. if (this._options.uniforms.indexOf("mBones") === -1) {
  42999. this._options.uniforms.push("mBones");
  43000. }
  43001. }
  43002. else {
  43003. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43004. }
  43005. // Textures
  43006. for (var name in this._textures) {
  43007. if (!this._textures[name].isReady()) {
  43008. return false;
  43009. }
  43010. }
  43011. // Alpha test
  43012. if (engine.getAlphaTesting()) {
  43013. defines.push("#define ALPHATEST");
  43014. }
  43015. var previousEffect = this._effect;
  43016. var join = defines.join("\n");
  43017. this._effect = engine.createEffect(this._shaderPath, {
  43018. attributes: attribs,
  43019. uniformsNames: this._options.uniforms,
  43020. uniformBuffersNames: this._options.uniformBuffers,
  43021. samplers: this._options.samplers,
  43022. defines: join,
  43023. fallbacks: fallbacks,
  43024. onCompiled: this.onCompiled,
  43025. onError: this.onError
  43026. }, engine);
  43027. if (!this._effect.isReady()) {
  43028. return false;
  43029. }
  43030. if (previousEffect !== this._effect) {
  43031. scene.resetCachedMaterial();
  43032. }
  43033. this._renderId = scene.getRenderId();
  43034. return true;
  43035. };
  43036. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43037. var scene = this.getScene();
  43038. if (this._options.uniforms.indexOf("world") !== -1) {
  43039. this._effect.setMatrix("world", world);
  43040. }
  43041. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43042. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43043. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43044. }
  43045. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43046. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43047. }
  43048. };
  43049. ShaderMaterial.prototype.bind = function (world, mesh) {
  43050. // Std values
  43051. this.bindOnlyWorldMatrix(world);
  43052. if (this.getScene().getCachedMaterial() !== this) {
  43053. if (this._options.uniforms.indexOf("view") !== -1) {
  43054. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43055. }
  43056. if (this._options.uniforms.indexOf("projection") !== -1) {
  43057. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43058. }
  43059. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43060. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43061. }
  43062. // Bones
  43063. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43064. var name;
  43065. // Texture
  43066. for (name in this._textures) {
  43067. this._effect.setTexture(name, this._textures[name]);
  43068. }
  43069. // Texture arrays
  43070. for (name in this._textureArrays) {
  43071. this._effect.setTextureArray(name, this._textureArrays[name]);
  43072. }
  43073. // Float
  43074. for (name in this._floats) {
  43075. this._effect.setFloat(name, this._floats[name]);
  43076. }
  43077. // Float s
  43078. for (name in this._floatsArrays) {
  43079. this._effect.setArray(name, this._floatsArrays[name]);
  43080. }
  43081. // Color3
  43082. for (name in this._colors3) {
  43083. this._effect.setColor3(name, this._colors3[name]);
  43084. }
  43085. for (name in this._colors3Arrays) {
  43086. this._effect.setArray3(name, this._colors3Arrays[name]);
  43087. }
  43088. // Color4
  43089. for (name in this._colors4) {
  43090. var color = this._colors4[name];
  43091. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43092. }
  43093. // Vector2
  43094. for (name in this._vectors2) {
  43095. this._effect.setVector2(name, this._vectors2[name]);
  43096. }
  43097. // Vector3
  43098. for (name in this._vectors3) {
  43099. this._effect.setVector3(name, this._vectors3[name]);
  43100. }
  43101. // Vector4
  43102. for (name in this._vectors4) {
  43103. this._effect.setVector4(name, this._vectors4[name]);
  43104. }
  43105. // Matrix
  43106. for (name in this._matrices) {
  43107. this._effect.setMatrix(name, this._matrices[name]);
  43108. }
  43109. // Matrix 3x3
  43110. for (name in this._matrices3x3) {
  43111. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43112. }
  43113. // Matrix 2x2
  43114. for (name in this._matrices2x2) {
  43115. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43116. }
  43117. // Vector3Array
  43118. for (name in this._vectors3Arrays) {
  43119. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43120. }
  43121. }
  43122. this._afterBind(mesh);
  43123. };
  43124. ShaderMaterial.prototype.getActiveTextures = function () {
  43125. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43126. for (var name in this._textures) {
  43127. activeTextures.push(this._textures[name]);
  43128. }
  43129. for (var name in this._textureArrays) {
  43130. var array = this._textureArrays[name];
  43131. for (var index = 0; index < array.length; index++) {
  43132. activeTextures.push(array[index]);
  43133. }
  43134. }
  43135. return activeTextures;
  43136. };
  43137. ShaderMaterial.prototype.hasTexture = function (texture) {
  43138. if (_super.prototype.hasTexture.call(this, texture)) {
  43139. return true;
  43140. }
  43141. for (var name in this._textures) {
  43142. if (this._textures[name] === texture) {
  43143. return true;
  43144. }
  43145. }
  43146. for (var name in this._textureArrays) {
  43147. var array = this._textureArrays[name];
  43148. for (var index = 0; index < array.length; index++) {
  43149. if (array[index] === texture) {
  43150. return true;
  43151. }
  43152. }
  43153. }
  43154. return false;
  43155. };
  43156. ShaderMaterial.prototype.clone = function (name) {
  43157. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43158. return newShaderMaterial;
  43159. };
  43160. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43161. if (forceDisposeTextures) {
  43162. var name;
  43163. for (name in this._textures) {
  43164. this._textures[name].dispose();
  43165. }
  43166. for (name in this._textureArrays) {
  43167. var array = this._textureArrays[name];
  43168. for (var index = 0; index < array.length; index++) {
  43169. array[index].dispose();
  43170. }
  43171. }
  43172. }
  43173. this._textures = {};
  43174. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43175. };
  43176. ShaderMaterial.prototype.serialize = function () {
  43177. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43178. serializationObject.customType = "BABYLON.ShaderMaterial";
  43179. serializationObject.options = this._options;
  43180. serializationObject.shaderPath = this._shaderPath;
  43181. var name;
  43182. // Texture
  43183. serializationObject.textures = {};
  43184. for (name in this._textures) {
  43185. serializationObject.textures[name] = this._textures[name].serialize();
  43186. }
  43187. // Texture arrays
  43188. serializationObject.textureArrays = {};
  43189. for (name in this._textureArrays) {
  43190. serializationObject.textureArrays[name] = [];
  43191. var array = this._textureArrays[name];
  43192. for (var index = 0; index < array.length; index++) {
  43193. serializationObject.textureArrays[name].push(array[index].serialize());
  43194. }
  43195. }
  43196. // Float
  43197. serializationObject.floats = {};
  43198. for (name in this._floats) {
  43199. serializationObject.floats[name] = this._floats[name];
  43200. }
  43201. // Float s
  43202. serializationObject.floatArrays = {};
  43203. for (name in this._floatsArrays) {
  43204. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43205. }
  43206. // Color3
  43207. serializationObject.colors3 = {};
  43208. for (name in this._colors3) {
  43209. serializationObject.colors3[name] = this._colors3[name].asArray();
  43210. }
  43211. // Color3 array
  43212. serializationObject.colors3Arrays = {};
  43213. for (name in this._colors3Arrays) {
  43214. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  43215. }
  43216. // Color4
  43217. serializationObject.colors4 = {};
  43218. for (name in this._colors4) {
  43219. serializationObject.colors4[name] = this._colors4[name].asArray();
  43220. }
  43221. // Vector2
  43222. serializationObject.vectors2 = {};
  43223. for (name in this._vectors2) {
  43224. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43225. }
  43226. // Vector3
  43227. serializationObject.vectors3 = {};
  43228. for (name in this._vectors3) {
  43229. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43230. }
  43231. // Vector4
  43232. serializationObject.vectors4 = {};
  43233. for (name in this._vectors4) {
  43234. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43235. }
  43236. // Matrix
  43237. serializationObject.matrices = {};
  43238. for (name in this._matrices) {
  43239. serializationObject.matrices[name] = this._matrices[name].asArray();
  43240. }
  43241. // Matrix 3x3
  43242. serializationObject.matrices3x3 = {};
  43243. for (name in this._matrices3x3) {
  43244. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43245. }
  43246. // Matrix 2x2
  43247. serializationObject.matrices2x2 = {};
  43248. for (name in this._matrices2x2) {
  43249. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43250. }
  43251. // Vector3Array
  43252. serializationObject.vectors3Arrays = {};
  43253. for (name in this._vectors3Arrays) {
  43254. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43255. }
  43256. return serializationObject;
  43257. };
  43258. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43259. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43260. var name;
  43261. // Texture
  43262. for (name in source.textures) {
  43263. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43264. }
  43265. // Texture arrays
  43266. for (name in source.textureArrays) {
  43267. var array = source.textureArrays[name];
  43268. var textureArray = new Array();
  43269. for (var index = 0; index < array.length; index++) {
  43270. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43271. }
  43272. material.setTextureArray(name, textureArray);
  43273. }
  43274. // Float
  43275. for (name in source.floats) {
  43276. material.setFloat(name, source.floats[name]);
  43277. }
  43278. // Float s
  43279. for (name in source.floatsArrays) {
  43280. material.setFloats(name, source.floatsArrays[name]);
  43281. }
  43282. // Color3
  43283. for (name in source.colors3) {
  43284. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43285. }
  43286. // Color3 arrays
  43287. for (name in source.colors3Arrays) {
  43288. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  43289. if (i % 3 === 0) {
  43290. arr.push([num]);
  43291. }
  43292. else {
  43293. arr[arr.length - 1].push(num);
  43294. }
  43295. return arr;
  43296. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  43297. material.setColor3Array(name, colors);
  43298. }
  43299. // Color4
  43300. for (name in source.colors4) {
  43301. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43302. }
  43303. // Vector2
  43304. for (name in source.vectors2) {
  43305. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43306. }
  43307. // Vector3
  43308. for (name in source.vectors3) {
  43309. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43310. }
  43311. // Vector4
  43312. for (name in source.vectors4) {
  43313. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43314. }
  43315. // Matrix
  43316. for (name in source.matrices) {
  43317. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43318. }
  43319. // Matrix 3x3
  43320. for (name in source.matrices3x3) {
  43321. material.setMatrix3x3(name, source.matrices3x3[name]);
  43322. }
  43323. // Matrix 2x2
  43324. for (name in source.matrices2x2) {
  43325. material.setMatrix2x2(name, source.matrices2x2[name]);
  43326. }
  43327. // Vector3Array
  43328. for (name in source.vectors3Arrays) {
  43329. material.setArray3(name, source.vectors3Arrays[name]);
  43330. }
  43331. return material;
  43332. };
  43333. return ShaderMaterial;
  43334. }(BABYLON.Material));
  43335. BABYLON.ShaderMaterial = ShaderMaterial;
  43336. })(BABYLON || (BABYLON = {}));
  43337. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43338. var BABYLON;
  43339. (function (BABYLON) {
  43340. var MeshBuilder = (function () {
  43341. function MeshBuilder() {
  43342. }
  43343. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  43344. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  43345. return BABYLON.Mesh.DOUBLESIDE;
  43346. }
  43347. if (orientation === undefined || orientation === null) {
  43348. return BABYLON.Mesh.FRONTSIDE;
  43349. }
  43350. return orientation;
  43351. };
  43352. /**
  43353. * Creates a box mesh.
  43354. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  43355. * The parameter `size` sets the size (float) of each box side (default 1).
  43356. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  43357. * 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).
  43358. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43359. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43360. * 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).
  43361. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43363. */
  43364. MeshBuilder.CreateBox = function (name, options, scene) {
  43365. var box = new BABYLON.Mesh(name, scene);
  43366. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43367. box.sideOrientation = options.sideOrientation;
  43368. var vertexData = BABYLON.VertexData.CreateBox(options);
  43369. vertexData.applyToMesh(box, options.updatable);
  43370. return box;
  43371. };
  43372. /**
  43373. * Creates a sphere mesh.
  43374. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  43375. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  43376. * 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`).
  43377. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  43378. * 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
  43379. * 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).
  43380. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43381. * 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).
  43382. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43384. */
  43385. MeshBuilder.CreateSphere = function (name, options, scene) {
  43386. var sphere = new BABYLON.Mesh(name, scene);
  43387. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43388. sphere.sideOrientation = options.sideOrientation;
  43389. var vertexData = BABYLON.VertexData.CreateSphere(options);
  43390. vertexData.applyToMesh(sphere, options.updatable);
  43391. return sphere;
  43392. };
  43393. /**
  43394. * Creates a plane polygonal mesh. By default, this is a disc.
  43395. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  43396. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  43397. * 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.
  43398. * 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
  43399. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43400. * 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).
  43401. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43402. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43403. */
  43404. MeshBuilder.CreateDisc = function (name, options, scene) {
  43405. var disc = new BABYLON.Mesh(name, scene);
  43406. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43407. disc.sideOrientation = options.sideOrientation;
  43408. var vertexData = BABYLON.VertexData.CreateDisc(options);
  43409. vertexData.applyToMesh(disc, options.updatable);
  43410. return disc;
  43411. };
  43412. /**
  43413. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  43414. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  43415. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  43416. * 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`).
  43417. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  43418. * 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.
  43419. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43420. * 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).
  43421. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43423. */
  43424. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  43425. var sphere = new BABYLON.Mesh(name, scene);
  43426. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43427. sphere.sideOrientation = options.sideOrientation;
  43428. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  43429. vertexData.applyToMesh(sphere, options.updatable);
  43430. return sphere;
  43431. };
  43432. ;
  43433. /**
  43434. * Creates a ribbon mesh.
  43435. * 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.
  43436. *
  43437. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  43438. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  43439. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  43440. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  43441. * 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.
  43442. * 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.
  43443. * 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
  43444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43445. * 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).
  43446. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43447. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43448. * 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.
  43449. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  43450. * 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
  43451. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  43452. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  43453. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43454. */
  43455. MeshBuilder.CreateRibbon = function (name, options, scene) {
  43456. var pathArray = options.pathArray;
  43457. var closeArray = options.closeArray;
  43458. var closePath = options.closePath;
  43459. var offset = options.offset;
  43460. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43461. var instance = options.instance;
  43462. var updatable = options.updatable;
  43463. if (instance) {
  43464. // positionFunction : ribbon case
  43465. // only pathArray and sideOrientation parameters are taken into account for positions update
  43466. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  43467. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  43468. var positionFunction = function (positions) {
  43469. var minlg = pathArray[0].length;
  43470. var i = 0;
  43471. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  43472. for (var si = 1; si <= ns; si++) {
  43473. for (var p = 0; p < pathArray.length; p++) {
  43474. var path = pathArray[p];
  43475. var l = path.length;
  43476. minlg = (minlg < l) ? minlg : l;
  43477. var j = 0;
  43478. while (j < minlg) {
  43479. positions[i] = path[j].x;
  43480. positions[i + 1] = path[j].y;
  43481. positions[i + 2] = path[j].z;
  43482. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  43483. BABYLON.Tmp.Vector3[0].x = path[j].x;
  43484. }
  43485. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  43486. BABYLON.Tmp.Vector3[1].x = path[j].x;
  43487. }
  43488. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  43489. BABYLON.Tmp.Vector3[0].y = path[j].y;
  43490. }
  43491. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  43492. BABYLON.Tmp.Vector3[1].y = path[j].y;
  43493. }
  43494. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  43495. BABYLON.Tmp.Vector3[0].z = path[j].z;
  43496. }
  43497. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  43498. BABYLON.Tmp.Vector3[1].z = path[j].z;
  43499. }
  43500. j++;
  43501. i += 3;
  43502. }
  43503. if (instance._closePath) {
  43504. positions[i] = path[0].x;
  43505. positions[i + 1] = path[0].y;
  43506. positions[i + 2] = path[0].z;
  43507. i += 3;
  43508. }
  43509. }
  43510. }
  43511. };
  43512. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43513. positionFunction(positions);
  43514. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  43515. instance._boundingInfo.update(instance._worldMatrix);
  43516. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  43517. if (options.colors) {
  43518. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43519. for (var c = 0; c < options.colors.length; c++) {
  43520. colors[c * 4] = options.colors[c].r;
  43521. colors[c * 4 + 1] = options.colors[c].g;
  43522. colors[c * 4 + 2] = options.colors[c].b;
  43523. colors[c * 4 + 3] = options.colors[c].a;
  43524. }
  43525. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  43526. }
  43527. if (options.uvs) {
  43528. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43529. for (var i = 0; i < options.uvs.length; i++) {
  43530. uvs[i * 2] = options.uvs[i].x;
  43531. uvs[i * 2 + 1] = options.uvs[i].y;
  43532. }
  43533. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  43534. }
  43535. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  43536. var indices = instance.getIndices();
  43537. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43538. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  43539. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  43540. if (instance._closePath) {
  43541. var indexFirst = 0;
  43542. var indexLast = 0;
  43543. for (var p = 0; p < pathArray.length; p++) {
  43544. indexFirst = instance._idx[p] * 3;
  43545. if (p + 1 < pathArray.length) {
  43546. indexLast = (instance._idx[p + 1] - 1) * 3;
  43547. }
  43548. else {
  43549. indexLast = normals.length - 3;
  43550. }
  43551. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  43552. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  43553. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  43554. normals[indexLast] = normals[indexFirst];
  43555. normals[indexLast + 1] = normals[indexFirst + 1];
  43556. normals[indexLast + 2] = normals[indexFirst + 2];
  43557. }
  43558. }
  43559. if (!(instance.areNormalsFrozen)) {
  43560. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  43561. }
  43562. }
  43563. return instance;
  43564. }
  43565. else {
  43566. var ribbon = new BABYLON.Mesh(name, scene);
  43567. ribbon.sideOrientation = sideOrientation;
  43568. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  43569. if (closePath) {
  43570. ribbon._idx = vertexData._idx;
  43571. }
  43572. ribbon._closePath = closePath;
  43573. ribbon._closeArray = closeArray;
  43574. vertexData.applyToMesh(ribbon, updatable);
  43575. return ribbon;
  43576. }
  43577. };
  43578. /**
  43579. * Creates a cylinder or a cone mesh.
  43580. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  43581. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  43582. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  43583. * 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.
  43584. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  43585. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  43586. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  43587. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  43588. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  43589. * 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).
  43590. * 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
  43591. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  43592. * 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
  43593. * 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.
  43594. * If `enclose` is false, a ring surface is one element.
  43595. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  43596. * 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
  43597. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43598. * 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).
  43599. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43600. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43601. */
  43602. MeshBuilder.CreateCylinder = function (name, options, scene) {
  43603. var cylinder = new BABYLON.Mesh(name, scene);
  43604. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43605. cylinder.sideOrientation = options.sideOrientation;
  43606. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  43607. vertexData.applyToMesh(cylinder, options.updatable);
  43608. return cylinder;
  43609. };
  43610. /**
  43611. * Creates a torus mesh.
  43612. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  43613. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  43614. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  43615. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  43616. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43617. * 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).
  43618. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43619. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43620. */
  43621. MeshBuilder.CreateTorus = function (name, options, scene) {
  43622. var torus = new BABYLON.Mesh(name, scene);
  43623. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43624. torus.sideOrientation = options.sideOrientation;
  43625. var vertexData = BABYLON.VertexData.CreateTorus(options);
  43626. vertexData.applyToMesh(torus, options.updatable);
  43627. return torus;
  43628. };
  43629. /**
  43630. * Creates a torus knot mesh.
  43631. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  43632. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  43633. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  43634. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  43635. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  43636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43637. * 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).
  43638. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43640. */
  43641. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  43642. var torusKnot = new BABYLON.Mesh(name, scene);
  43643. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43644. torusKnot.sideOrientation = options.sideOrientation;
  43645. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  43646. vertexData.applyToMesh(torusKnot, options.updatable);
  43647. return torusKnot;
  43648. };
  43649. /**
  43650. * Creates a line system mesh.
  43651. * A line system is a pool of many lines gathered in a single mesh.
  43652. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  43653. * 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.
  43654. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  43655. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  43656. * 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
  43657. * 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
  43658. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  43659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43660. */
  43661. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  43662. var instance = options.instance;
  43663. var lines = options.lines;
  43664. if (instance) {
  43665. var positionFunction = function (positions) {
  43666. var i = 0;
  43667. for (var l = 0; l < lines.length; l++) {
  43668. var points = lines[l];
  43669. for (var p = 0; p < points.length; p++) {
  43670. positions[i] = points[p].x;
  43671. positions[i + 1] = points[p].y;
  43672. positions[i + 2] = points[p].z;
  43673. i += 3;
  43674. }
  43675. }
  43676. };
  43677. instance.updateMeshPositions(positionFunction, false);
  43678. return instance;
  43679. }
  43680. // line system creation
  43681. var lineSystem = new BABYLON.LinesMesh(name, scene);
  43682. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  43683. vertexData.applyToMesh(lineSystem, options.updatable);
  43684. return lineSystem;
  43685. };
  43686. /**
  43687. * Creates a line mesh.
  43688. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  43689. * 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.
  43690. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43691. * The parameter `points` is an array successive Vector3.
  43692. * 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
  43693. * When updating an instance, remember that only point positions can change, not the number of points.
  43694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43695. */
  43696. MeshBuilder.CreateLines = function (name, options, scene) {
  43697. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  43698. return lines;
  43699. };
  43700. /**
  43701. * Creates a dashed line mesh.
  43702. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  43703. * 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.
  43704. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43705. * The parameter `points` is an array successive Vector3.
  43706. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  43707. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  43708. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  43709. * 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
  43710. * When updating an instance, remember that only point positions can change, not the number of points.
  43711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43712. */
  43713. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  43714. var points = options.points;
  43715. var instance = options.instance;
  43716. var gapSize = options.gapSize;
  43717. var dashNb = options.dashNb;
  43718. var dashSize = options.dashSize;
  43719. if (instance) {
  43720. var positionFunction = function (positions) {
  43721. var curvect = BABYLON.Vector3.Zero();
  43722. var nbSeg = positions.length / 6;
  43723. var lg = 0;
  43724. var nb = 0;
  43725. var shft = 0;
  43726. var dashshft = 0;
  43727. var curshft = 0;
  43728. var p = 0;
  43729. var i = 0;
  43730. var j = 0;
  43731. for (i = 0; i < points.length - 1; i++) {
  43732. points[i + 1].subtractToRef(points[i], curvect);
  43733. lg += curvect.length();
  43734. }
  43735. shft = lg / nbSeg;
  43736. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  43737. for (i = 0; i < points.length - 1; i++) {
  43738. points[i + 1].subtractToRef(points[i], curvect);
  43739. nb = Math.floor(curvect.length() / shft);
  43740. curvect.normalize();
  43741. j = 0;
  43742. while (j < nb && p < positions.length) {
  43743. curshft = shft * j;
  43744. positions[p] = points[i].x + curshft * curvect.x;
  43745. positions[p + 1] = points[i].y + curshft * curvect.y;
  43746. positions[p + 2] = points[i].z + curshft * curvect.z;
  43747. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  43748. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  43749. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  43750. p += 6;
  43751. j++;
  43752. }
  43753. }
  43754. while (p < positions.length) {
  43755. positions[p] = points[i].x;
  43756. positions[p + 1] = points[i].y;
  43757. positions[p + 2] = points[i].z;
  43758. p += 3;
  43759. }
  43760. };
  43761. instance.updateMeshPositions(positionFunction, false);
  43762. return instance;
  43763. }
  43764. // dashed lines creation
  43765. var dashedLines = new BABYLON.LinesMesh(name, scene);
  43766. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  43767. vertexData.applyToMesh(dashedLines, options.updatable);
  43768. dashedLines.dashSize = dashSize;
  43769. dashedLines.gapSize = gapSize;
  43770. return dashedLines;
  43771. };
  43772. /**
  43773. * Creates an extruded shape mesh.
  43774. * 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.
  43775. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  43776. *
  43777. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43778. * 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
  43779. * extruded along the Z axis.
  43780. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43781. * 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.
  43782. * The parameter `scale` (float, default 1) is the value to scale the shape.
  43783. * 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
  43784. * 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
  43785. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43787. * 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).
  43788. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43789. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43790. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43791. */
  43792. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  43793. var path = options.path;
  43794. var shape = options.shape;
  43795. var scale = options.scale || 1;
  43796. var rotation = options.rotation || 0;
  43797. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43798. var updatable = options.updatable;
  43799. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43800. var instance = options.instance;
  43801. var invertUV = options.invertUV || false;
  43802. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43803. };
  43804. /**
  43805. * Creates an custom extruded shape mesh.
  43806. * 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.
  43807. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  43808. *
  43809. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43810. * 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
  43811. * extruded along the Z axis.
  43812. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43813. * 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
  43814. * and the distance of this point from the begining of the path :
  43815. * ```javascript
  43816. * var rotationFunction = function(i, distance) {
  43817. * // do things
  43818. * return rotationValue; }
  43819. * ```
  43820. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  43821. * 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
  43822. * and the distance of this point from the begining of the path :
  43823. * ```javascript
  43824. * var scaleFunction = function(i, distance) {
  43825. * // do things
  43826. * return scaleValue;}
  43827. * ```
  43828. * It must returns a float value that will be the scale value applied to the shape on each path point.
  43829. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  43830. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  43831. * 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
  43832. * 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
  43833. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43834. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43835. * 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).
  43836. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43837. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43839. */
  43840. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  43841. var path = options.path;
  43842. var shape = options.shape;
  43843. var scaleFunction = options.scaleFunction || (function () { return 1; });
  43844. var rotationFunction = options.rotationFunction || (function () { return 0; });
  43845. var ribbonCloseArray = options.ribbonCloseArray || false;
  43846. var ribbonClosePath = options.ribbonClosePath || false;
  43847. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43848. var updatable = options.updatable;
  43849. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43850. var instance = options.instance;
  43851. var invertUV = options.invertUV || false;
  43852. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43853. };
  43854. /**
  43855. * Creates lathe mesh.
  43856. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  43857. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  43858. *
  43859. * 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
  43860. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  43861. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  43862. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  43863. * 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.
  43864. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  43865. * 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
  43866. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43867. * 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).
  43868. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43869. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43870. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43871. */
  43872. MeshBuilder.CreateLathe = function (name, options, scene) {
  43873. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  43874. var closed = (options.closed === undefined) ? true : options.closed;
  43875. var shape = options.shape;
  43876. var radius = options.radius || 1;
  43877. var tessellation = options.tessellation || 64;
  43878. var updatable = options.updatable;
  43879. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43880. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  43881. var pi2 = Math.PI * 2;
  43882. var paths = new Array();
  43883. var invertUV = options.invertUV || false;
  43884. var i = 0;
  43885. var p = 0;
  43886. var step = pi2 / tessellation * arc;
  43887. var rotated;
  43888. var path = new Array();
  43889. ;
  43890. for (i = 0; i <= tessellation; i++) {
  43891. var path = [];
  43892. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  43893. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  43894. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  43895. }
  43896. for (p = 0; p < shape.length; p++) {
  43897. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  43898. path.push(rotated);
  43899. }
  43900. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  43901. 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));
  43902. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  43903. }
  43904. paths.push(path);
  43905. }
  43906. // lathe ribbon
  43907. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43908. return lathe;
  43909. };
  43910. /**
  43911. * Creates a plane mesh.
  43912. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43913. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  43914. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  43915. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  43916. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43917. * 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).
  43918. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43920. */
  43921. MeshBuilder.CreatePlane = function (name, options, scene) {
  43922. var plane = new BABYLON.Mesh(name, scene);
  43923. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43924. plane.sideOrientation = options.sideOrientation;
  43925. var vertexData = BABYLON.VertexData.CreatePlane(options);
  43926. vertexData.applyToMesh(plane, options.updatable);
  43927. if (options.sourcePlane) {
  43928. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  43929. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  43930. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  43931. plane.rotate(vectorProduct, product);
  43932. }
  43933. return plane;
  43934. };
  43935. /**
  43936. * Creates a ground mesh.
  43937. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43938. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  43939. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  43940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43941. */
  43942. MeshBuilder.CreateGround = function (name, options, scene) {
  43943. var ground = new BABYLON.GroundMesh(name, scene);
  43944. ground._setReady(false);
  43945. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  43946. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  43947. ground._width = options.width || 1;
  43948. ground._height = options.height || 1;
  43949. ground._maxX = ground._width / 2;
  43950. ground._maxZ = ground._height / 2;
  43951. ground._minX = -ground._maxX;
  43952. ground._minZ = -ground._maxZ;
  43953. var vertexData = BABYLON.VertexData.CreateGround(options);
  43954. vertexData.applyToMesh(ground, options.updatable);
  43955. ground._setReady(true);
  43956. return ground;
  43957. };
  43958. /**
  43959. * Creates a tiled ground mesh.
  43960. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  43961. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  43962. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  43963. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  43964. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  43965. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  43966. * numbers of subdivisions on the ground width and height of each tile.
  43967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43968. */
  43969. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  43970. var tiledGround = new BABYLON.Mesh(name, scene);
  43971. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  43972. vertexData.applyToMesh(tiledGround, options.updatable);
  43973. return tiledGround;
  43974. };
  43975. /**
  43976. * Creates a ground mesh from a height map.
  43977. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  43978. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  43979. * The parameter `url` sets the URL of the height map image resource.
  43980. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  43981. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  43982. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  43983. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  43984. * 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.
  43985. * 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).
  43986. * This function is passed the newly built mesh :
  43987. * ```javascript
  43988. * function(mesh) { // do things
  43989. * return; }
  43990. * ```
  43991. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43992. */
  43993. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  43994. var width = options.width || 10.0;
  43995. var height = options.height || 10.0;
  43996. var subdivisions = options.subdivisions || 1 | 0;
  43997. var minHeight = options.minHeight || 0.0;
  43998. var maxHeight = options.maxHeight || 10.0;
  43999. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  44000. var updatable = options.updatable;
  44001. var onReady = options.onReady;
  44002. var ground = new BABYLON.GroundMesh(name, scene);
  44003. ground._subdivisionsX = subdivisions;
  44004. ground._subdivisionsY = subdivisions;
  44005. ground._width = width;
  44006. ground._height = height;
  44007. ground._maxX = ground._width / 2.0;
  44008. ground._maxZ = ground._height / 2.0;
  44009. ground._minX = -ground._maxX;
  44010. ground._minZ = -ground._maxZ;
  44011. ground._setReady(false);
  44012. var onload = function (img) {
  44013. // Getting height map data
  44014. var canvas = document.createElement("canvas");
  44015. var context = canvas.getContext("2d");
  44016. var bufferWidth = img.width;
  44017. var bufferHeight = img.height;
  44018. canvas.width = bufferWidth;
  44019. canvas.height = bufferHeight;
  44020. context.drawImage(img, 0, 0);
  44021. // Create VertexData from map data
  44022. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  44023. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  44024. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  44025. width: width, height: height,
  44026. subdivisions: subdivisions,
  44027. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  44028. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  44029. });
  44030. vertexData.applyToMesh(ground, updatable);
  44031. ground._setReady(true);
  44032. //execute ready callback, if set
  44033. if (onReady) {
  44034. onReady(ground);
  44035. }
  44036. };
  44037. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  44038. return ground;
  44039. };
  44040. /**
  44041. * Creates a polygon mesh.
  44042. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  44043. * 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.
  44044. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44046. * 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).
  44047. * Remember you can only change the shape positions, not their number when updating a polygon.
  44048. */
  44049. MeshBuilder.CreatePolygon = function (name, options, scene) {
  44050. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44051. var shape = options.shape;
  44052. var holes = options.holes || [];
  44053. var depth = options.depth || 0;
  44054. var contours = [];
  44055. var hole = [];
  44056. for (var i = 0; i < shape.length; i++) {
  44057. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  44058. }
  44059. var epsilon = 0.00000001;
  44060. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  44061. contours.pop();
  44062. }
  44063. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  44064. for (var hNb = 0; hNb < holes.length; hNb++) {
  44065. hole = [];
  44066. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  44067. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  44068. }
  44069. polygonTriangulation.addHole(hole);
  44070. }
  44071. var polygon = polygonTriangulation.build(options.updatable, depth);
  44072. polygon.sideOrientation = options.sideOrientation;
  44073. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  44074. vertexData.applyToMesh(polygon, options.updatable);
  44075. return polygon;
  44076. };
  44077. ;
  44078. /**
  44079. * Creates an extruded polygon mesh, with depth in the Y direction.
  44080. * 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).
  44081. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  44082. */
  44083. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  44084. return MeshBuilder.CreatePolygon(name, options, scene);
  44085. };
  44086. ;
  44087. /**
  44088. * Creates a tube mesh.
  44089. * 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.
  44090. *
  44091. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  44092. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  44093. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  44094. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  44095. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  44096. * 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.
  44097. * It must return a radius value (positive float) :
  44098. * ```javascript
  44099. * var radiusFunction = function(i, distance) {
  44100. * // do things
  44101. * return radius; }
  44102. * ```
  44103. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  44104. * 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
  44105. * 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
  44106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44107. * 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).
  44108. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44109. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44111. */
  44112. MeshBuilder.CreateTube = function (name, options, scene) {
  44113. var path = options.path;
  44114. var radius = options.radius || 1.0;
  44115. var tessellation = options.tessellation || 64 | 0;
  44116. var radiusFunction = options.radiusFunction;
  44117. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44118. var invertUV = options.invertUV || false;
  44119. var updatable = options.updatable;
  44120. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44121. var instance = options.instance;
  44122. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  44123. // tube geometry
  44124. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  44125. var tangents = path3D.getTangents();
  44126. var normals = path3D.getNormals();
  44127. var distances = path3D.getDistances();
  44128. var pi2 = Math.PI * 2;
  44129. var step = pi2 / tessellation * arc;
  44130. var returnRadius = function () { return radius; };
  44131. var radiusFunctionFinal = radiusFunction || returnRadius;
  44132. var circlePath;
  44133. var rad;
  44134. var normal;
  44135. var rotated;
  44136. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44137. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44138. for (var i = 0; i < path.length; i++) {
  44139. rad = radiusFunctionFinal(i, distances[i]); // current radius
  44140. circlePath = Array(); // current circle array
  44141. normal = normals[i]; // current normal
  44142. for (var t = 0; t < tessellation; t++) {
  44143. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  44144. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  44145. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  44146. rotated.scaleInPlace(rad).addInPlace(path[i]);
  44147. circlePath[t] = rotated;
  44148. }
  44149. circlePaths[index] = circlePath;
  44150. index++;
  44151. }
  44152. // cap
  44153. var capPath = function (nbPoints, pathIndex) {
  44154. var pointCap = Array();
  44155. for (var i = 0; i < nbPoints; i++) {
  44156. pointCap.push(path[pathIndex]);
  44157. }
  44158. return pointCap;
  44159. };
  44160. switch (cap) {
  44161. case BABYLON.Mesh.NO_CAP:
  44162. break;
  44163. case BABYLON.Mesh.CAP_START:
  44164. circlePaths[0] = capPath(tessellation, 0);
  44165. circlePaths[1] = circlePaths[2].slice(0);
  44166. break;
  44167. case BABYLON.Mesh.CAP_END:
  44168. circlePaths[index] = circlePaths[index - 1].slice(0);
  44169. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44170. break;
  44171. case BABYLON.Mesh.CAP_ALL:
  44172. circlePaths[0] = capPath(tessellation, 0);
  44173. circlePaths[1] = circlePaths[2].slice(0);
  44174. circlePaths[index] = circlePaths[index - 1].slice(0);
  44175. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44176. break;
  44177. default:
  44178. break;
  44179. }
  44180. return circlePaths;
  44181. };
  44182. var path3D;
  44183. var pathArray;
  44184. if (instance) {
  44185. var arc = options.arc || instance.arc;
  44186. path3D = (instance.path3D).update(path);
  44187. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  44188. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  44189. instance.path3D = path3D;
  44190. instance.pathArray = pathArray;
  44191. instance.arc = arc;
  44192. return instance;
  44193. }
  44194. // tube creation
  44195. path3D = new BABYLON.Path3D(path);
  44196. var newPathArray = new Array();
  44197. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44198. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  44199. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44200. tube.pathArray = pathArray;
  44201. tube.path3D = path3D;
  44202. tube.tessellation = tessellation;
  44203. tube.cap = cap;
  44204. tube.arc = options.arc;
  44205. return tube;
  44206. };
  44207. /**
  44208. * Creates a polyhedron mesh.
  44209. *
  44210. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  44211. * 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
  44212. * to choose the wanted type.
  44213. * The parameter `size` (positive float, default 1) sets the polygon size.
  44214. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  44215. * 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`.
  44216. * 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
  44217. * 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)`).
  44218. * 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
  44219. * 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.
  44220. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44221. * 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).
  44222. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44223. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44224. */
  44225. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  44226. var polyhedron = new BABYLON.Mesh(name, scene);
  44227. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44228. polyhedron.sideOrientation = options.sideOrientation;
  44229. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  44230. vertexData.applyToMesh(polyhedron, options.updatable);
  44231. return polyhedron;
  44232. };
  44233. /**
  44234. * Creates a decal mesh.
  44235. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  44236. * 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.
  44237. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  44238. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  44239. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  44240. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  44241. */
  44242. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  44243. var indices = sourceMesh.getIndices();
  44244. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44245. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44246. var position = options.position || BABYLON.Vector3.Zero();
  44247. var normal = options.normal || BABYLON.Vector3.Up();
  44248. var size = options.size || BABYLON.Vector3.One();
  44249. var angle = options.angle || 0;
  44250. // Getting correct rotation
  44251. if (!normal) {
  44252. var target = new BABYLON.Vector3(0, 0, 1);
  44253. var camera = sourceMesh.getScene().activeCamera;
  44254. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  44255. normal = camera.globalPosition.subtract(cameraWorldTarget);
  44256. }
  44257. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  44258. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  44259. var pitch = Math.atan2(normal.y, len);
  44260. // Matrix
  44261. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  44262. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  44263. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  44264. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  44265. var vertexData = new BABYLON.VertexData();
  44266. vertexData.indices = [];
  44267. vertexData.positions = [];
  44268. vertexData.normals = [];
  44269. vertexData.uvs = [];
  44270. var currentVertexDataIndex = 0;
  44271. var extractDecalVector3 = function (indexId) {
  44272. var vertexId = indices[indexId];
  44273. var result = new BABYLON.PositionNormalVertex();
  44274. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  44275. // Send vector to decal local world
  44276. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  44277. // Get normal
  44278. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  44279. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  44280. return result;
  44281. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  44282. var clip = function (vertices, axis) {
  44283. if (vertices.length === 0) {
  44284. return vertices;
  44285. }
  44286. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  44287. var clipVertices = function (v0, v1) {
  44288. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  44289. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  44290. };
  44291. var result = new Array();
  44292. for (var index = 0; index < vertices.length; index += 3) {
  44293. var v1Out;
  44294. var v2Out;
  44295. var v3Out;
  44296. var total = 0;
  44297. var nV1, nV2, nV3, nV4;
  44298. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  44299. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  44300. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  44301. v1Out = d1 > 0;
  44302. v2Out = d2 > 0;
  44303. v3Out = d3 > 0;
  44304. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  44305. switch (total) {
  44306. case 0:
  44307. result.push(vertices[index]);
  44308. result.push(vertices[index + 1]);
  44309. result.push(vertices[index + 2]);
  44310. break;
  44311. case 1:
  44312. if (v1Out) {
  44313. nV1 = vertices[index + 1];
  44314. nV2 = vertices[index + 2];
  44315. nV3 = clipVertices(vertices[index], nV1);
  44316. nV4 = clipVertices(vertices[index], nV2);
  44317. }
  44318. if (v2Out) {
  44319. nV1 = vertices[index];
  44320. nV2 = vertices[index + 2];
  44321. nV3 = clipVertices(vertices[index + 1], nV1);
  44322. nV4 = clipVertices(vertices[index + 1], nV2);
  44323. result.push(nV3);
  44324. result.push(nV2.clone());
  44325. result.push(nV1.clone());
  44326. result.push(nV2.clone());
  44327. result.push(nV3.clone());
  44328. result.push(nV4);
  44329. break;
  44330. }
  44331. if (v3Out) {
  44332. nV1 = vertices[index];
  44333. nV2 = vertices[index + 1];
  44334. nV3 = clipVertices(vertices[index + 2], nV1);
  44335. nV4 = clipVertices(vertices[index + 2], nV2);
  44336. }
  44337. result.push(nV1.clone());
  44338. result.push(nV2.clone());
  44339. result.push(nV3);
  44340. result.push(nV4);
  44341. result.push(nV3.clone());
  44342. result.push(nV2.clone());
  44343. break;
  44344. case 2:
  44345. if (!v1Out) {
  44346. nV1 = vertices[index].clone();
  44347. nV2 = clipVertices(nV1, vertices[index + 1]);
  44348. nV3 = clipVertices(nV1, vertices[index + 2]);
  44349. result.push(nV1);
  44350. result.push(nV2);
  44351. result.push(nV3);
  44352. }
  44353. if (!v2Out) {
  44354. nV1 = vertices[index + 1].clone();
  44355. nV2 = clipVertices(nV1, vertices[index + 2]);
  44356. nV3 = clipVertices(nV1, vertices[index]);
  44357. result.push(nV1);
  44358. result.push(nV2);
  44359. result.push(nV3);
  44360. }
  44361. if (!v3Out) {
  44362. nV1 = vertices[index + 2].clone();
  44363. nV2 = clipVertices(nV1, vertices[index]);
  44364. nV3 = clipVertices(nV1, vertices[index + 1]);
  44365. result.push(nV1);
  44366. result.push(nV2);
  44367. result.push(nV3);
  44368. }
  44369. break;
  44370. case 3:
  44371. break;
  44372. }
  44373. }
  44374. return result;
  44375. };
  44376. for (var index = 0; index < indices.length; index += 3) {
  44377. var faceVertices = new Array();
  44378. faceVertices.push(extractDecalVector3(index));
  44379. faceVertices.push(extractDecalVector3(index + 1));
  44380. faceVertices.push(extractDecalVector3(index + 2));
  44381. // Clip
  44382. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  44383. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  44384. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  44385. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  44386. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  44387. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  44388. if (faceVertices.length === 0) {
  44389. continue;
  44390. }
  44391. // Add UVs and get back to world
  44392. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  44393. var vertex = faceVertices[vIndex];
  44394. //TODO check for Int32Array | Uint32Array | Uint16Array
  44395. vertexData.indices.push(currentVertexDataIndex);
  44396. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  44397. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  44398. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  44399. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  44400. currentVertexDataIndex++;
  44401. }
  44402. }
  44403. // Return mesh
  44404. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  44405. vertexData.applyToMesh(decal);
  44406. decal.position = position.clone();
  44407. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  44408. return decal;
  44409. };
  44410. // Privates
  44411. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  44412. // extrusion geometry
  44413. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  44414. var tangents = path3D.getTangents();
  44415. var normals = path3D.getNormals();
  44416. var binormals = path3D.getBinormals();
  44417. var distances = path3D.getDistances();
  44418. var angle = 0;
  44419. var returnScale = function () { return scale; };
  44420. var returnRotation = function () { return rotation; };
  44421. var rotate = custom ? rotateFunction : returnRotation;
  44422. var scl = custom ? scaleFunction : returnScale;
  44423. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44424. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44425. for (var i = 0; i < curve.length; i++) {
  44426. var shapePath = new Array();
  44427. var angleStep = rotate(i, distances[i]);
  44428. var scaleRatio = scl(i, distances[i]);
  44429. for (var p = 0; p < shape.length; p++) {
  44430. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  44431. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  44432. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  44433. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  44434. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  44435. shapePath[p] = rotated;
  44436. }
  44437. shapePaths[index] = shapePath;
  44438. angle += angleStep;
  44439. index++;
  44440. }
  44441. // cap
  44442. var capPath = function (shapePath) {
  44443. var pointCap = Array();
  44444. var barycenter = BABYLON.Vector3.Zero();
  44445. var i;
  44446. for (i = 0; i < shapePath.length; i++) {
  44447. barycenter.addInPlace(shapePath[i]);
  44448. }
  44449. barycenter.scaleInPlace(1.0 / shapePath.length);
  44450. for (i = 0; i < shapePath.length; i++) {
  44451. pointCap.push(barycenter);
  44452. }
  44453. return pointCap;
  44454. };
  44455. switch (cap) {
  44456. case BABYLON.Mesh.NO_CAP:
  44457. break;
  44458. case BABYLON.Mesh.CAP_START:
  44459. shapePaths[0] = capPath(shapePaths[2]);
  44460. shapePaths[1] = shapePaths[2];
  44461. break;
  44462. case BABYLON.Mesh.CAP_END:
  44463. shapePaths[index] = shapePaths[index - 1];
  44464. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44465. break;
  44466. case BABYLON.Mesh.CAP_ALL:
  44467. shapePaths[0] = capPath(shapePaths[2]);
  44468. shapePaths[1] = shapePaths[2];
  44469. shapePaths[index] = shapePaths[index - 1];
  44470. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44471. break;
  44472. default:
  44473. break;
  44474. }
  44475. return shapePaths;
  44476. };
  44477. var path3D;
  44478. var pathArray;
  44479. if (instance) {
  44480. path3D = (instance.path3D).update(curve);
  44481. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  44482. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  44483. return instance;
  44484. }
  44485. // extruded shape creation
  44486. path3D = new BABYLON.Path3D(curve);
  44487. var newShapePaths = new Array();
  44488. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44489. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  44490. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  44491. extrudedGeneric.pathArray = pathArray;
  44492. extrudedGeneric.path3D = path3D;
  44493. extrudedGeneric.cap = cap;
  44494. return extrudedGeneric;
  44495. };
  44496. return MeshBuilder;
  44497. }());
  44498. BABYLON.MeshBuilder = MeshBuilder;
  44499. })(BABYLON || (BABYLON = {}));
  44500. //# sourceMappingURL=babylon.meshBuilder.js.map
  44501. var BABYLON;
  44502. (function (BABYLON) {
  44503. var AudioEngine = (function () {
  44504. function AudioEngine() {
  44505. this._audioContext = null;
  44506. this._audioContextInitialized = false;
  44507. this.canUseWebAudio = false;
  44508. this.WarnedWebAudioUnsupported = false;
  44509. this.unlocked = false;
  44510. this.isMP3supported = false;
  44511. this.isOGGsupported = false;
  44512. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  44513. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  44514. this.canUseWebAudio = true;
  44515. }
  44516. var audioElem = document.createElement('audio');
  44517. try {
  44518. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  44519. this.isMP3supported = true;
  44520. }
  44521. }
  44522. catch (e) {
  44523. // protect error during capability check.
  44524. }
  44525. try {
  44526. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  44527. this.isOGGsupported = true;
  44528. }
  44529. }
  44530. catch (e) {
  44531. // protect error during capability check.
  44532. }
  44533. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  44534. this._unlockiOSaudio();
  44535. }
  44536. else {
  44537. this.unlocked = true;
  44538. }
  44539. }
  44540. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  44541. get: function () {
  44542. if (!this._audioContextInitialized) {
  44543. this._initializeAudioContext();
  44544. }
  44545. return this._audioContext;
  44546. },
  44547. enumerable: true,
  44548. configurable: true
  44549. });
  44550. AudioEngine.prototype._unlockiOSaudio = function () {
  44551. var _this = this;
  44552. var unlockaudio = function () {
  44553. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  44554. var source = _this.audioContext.createBufferSource();
  44555. source.buffer = buffer;
  44556. source.connect(_this.audioContext.destination);
  44557. source.start(0);
  44558. setTimeout(function () {
  44559. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  44560. _this.unlocked = true;
  44561. window.removeEventListener('touchend', unlockaudio, false);
  44562. if (_this.onAudioUnlocked) {
  44563. _this.onAudioUnlocked();
  44564. }
  44565. }
  44566. }, 0);
  44567. };
  44568. window.addEventListener('touchend', unlockaudio, false);
  44569. };
  44570. AudioEngine.prototype._initializeAudioContext = function () {
  44571. try {
  44572. if (this.canUseWebAudio) {
  44573. this._audioContext = new AudioContext();
  44574. // create a global volume gain node
  44575. this.masterGain = this._audioContext.createGain();
  44576. this.masterGain.gain.value = 1;
  44577. this.masterGain.connect(this._audioContext.destination);
  44578. this._audioContextInitialized = true;
  44579. }
  44580. }
  44581. catch (e) {
  44582. this.canUseWebAudio = false;
  44583. BABYLON.Tools.Error("Web Audio: " + e.message);
  44584. }
  44585. };
  44586. AudioEngine.prototype.dispose = function () {
  44587. if (this.canUseWebAudio && this._audioContextInitialized) {
  44588. if (this._connectedAnalyser) {
  44589. this._connectedAnalyser.stopDebugCanvas();
  44590. this._connectedAnalyser.dispose();
  44591. this.masterGain.disconnect();
  44592. this.masterGain.connect(this._audioContext.destination);
  44593. this._connectedAnalyser = null;
  44594. }
  44595. this.masterGain.gain.value = 1;
  44596. }
  44597. this.WarnedWebAudioUnsupported = false;
  44598. };
  44599. AudioEngine.prototype.getGlobalVolume = function () {
  44600. if (this.canUseWebAudio && this._audioContextInitialized) {
  44601. return this.masterGain.gain.value;
  44602. }
  44603. else {
  44604. return -1;
  44605. }
  44606. };
  44607. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  44608. if (this.canUseWebAudio && this._audioContextInitialized) {
  44609. this.masterGain.gain.value = newVolume;
  44610. }
  44611. };
  44612. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  44613. if (this._connectedAnalyser) {
  44614. this._connectedAnalyser.stopDebugCanvas();
  44615. }
  44616. if (this.canUseWebAudio && this._audioContextInitialized) {
  44617. this._connectedAnalyser = analyser;
  44618. this.masterGain.disconnect();
  44619. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  44620. }
  44621. };
  44622. return AudioEngine;
  44623. }());
  44624. BABYLON.AudioEngine = AudioEngine;
  44625. })(BABYLON || (BABYLON = {}));
  44626. //# sourceMappingURL=babylon.audioEngine.js.map
  44627. var BABYLON;
  44628. (function (BABYLON) {
  44629. var Sound = (function () {
  44630. /**
  44631. * Create a sound and attach it to a scene
  44632. * @param name Name of your sound
  44633. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  44634. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  44635. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  44636. */
  44637. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  44638. var _this = this;
  44639. this.autoplay = false;
  44640. this.loop = false;
  44641. this.useCustomAttenuation = false;
  44642. this.spatialSound = false;
  44643. this.refDistance = 1;
  44644. this.rolloffFactor = 1;
  44645. this.maxDistance = 100;
  44646. this.distanceModel = "linear";
  44647. this._panningModel = "equalpower";
  44648. this._playbackRate = 1;
  44649. this._streaming = false;
  44650. this._startTime = 0;
  44651. this._startOffset = 0;
  44652. this._position = BABYLON.Vector3.Zero();
  44653. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  44654. this._volume = 1;
  44655. this._isLoaded = false;
  44656. this._isReadyToPlay = false;
  44657. this.isPlaying = false;
  44658. this.isPaused = false;
  44659. this._isDirectional = false;
  44660. // Used if you'd like to create a directional sound.
  44661. // If not set, the sound will be omnidirectional
  44662. this._coneInnerAngle = 360;
  44663. this._coneOuterAngle = 360;
  44664. this._coneOuterGain = 0;
  44665. this._isOutputConnected = false;
  44666. this._urlType = "Unknown";
  44667. this.name = name;
  44668. this._scene = scene;
  44669. this._readyToPlayCallback = readyToPlayCallback;
  44670. // Default custom attenuation function is a linear attenuation
  44671. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  44672. if (currentDistance < maxDistance) {
  44673. return currentVolume * (1 - currentDistance / maxDistance);
  44674. }
  44675. else {
  44676. return 0;
  44677. }
  44678. };
  44679. if (options) {
  44680. this.autoplay = options.autoplay || false;
  44681. this.loop = options.loop || false;
  44682. // if volume === 0, we need another way to check this option
  44683. if (options.volume !== undefined) {
  44684. this._volume = options.volume;
  44685. }
  44686. this.spatialSound = options.spatialSound || false;
  44687. this.maxDistance = options.maxDistance || 100;
  44688. this.useCustomAttenuation = options.useCustomAttenuation || false;
  44689. this.rolloffFactor = options.rolloffFactor || 1;
  44690. this.refDistance = options.refDistance || 1;
  44691. this.distanceModel = options.distanceModel || "linear";
  44692. this._playbackRate = options.playbackRate || 1;
  44693. this._streaming = options.streaming || false;
  44694. }
  44695. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44696. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  44697. this._soundGain.gain.value = this._volume;
  44698. this._inputAudioNode = this._soundGain;
  44699. this._ouputAudioNode = this._soundGain;
  44700. if (this.spatialSound) {
  44701. this._createSpatialParameters();
  44702. }
  44703. this._scene.mainSoundTrack.AddSound(this);
  44704. var validParameter = true;
  44705. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  44706. if (urlOrArrayBuffer) {
  44707. if (typeof (urlOrArrayBuffer) === "string")
  44708. this._urlType = "String";
  44709. if (Array.isArray(urlOrArrayBuffer))
  44710. this._urlType = "Array";
  44711. if (urlOrArrayBuffer instanceof ArrayBuffer)
  44712. this._urlType = "ArrayBuffer";
  44713. var urls = [];
  44714. var codecSupportedFound = false;
  44715. switch (this._urlType) {
  44716. case "ArrayBuffer":
  44717. if (urlOrArrayBuffer.byteLength > 0) {
  44718. codecSupportedFound = true;
  44719. this._soundLoaded(urlOrArrayBuffer);
  44720. }
  44721. break;
  44722. case "String":
  44723. urls.push(urlOrArrayBuffer);
  44724. case "Array":
  44725. if (urls.length === 0)
  44726. urls = urlOrArrayBuffer;
  44727. // If we found a supported format, we load it immediately and stop the loop
  44728. for (var i = 0; i < urls.length; i++) {
  44729. var url = urls[i];
  44730. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  44731. codecSupportedFound = true;
  44732. }
  44733. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  44734. codecSupportedFound = true;
  44735. }
  44736. if (url.indexOf(".wav", url.length - 4) !== -1) {
  44737. codecSupportedFound = true;
  44738. }
  44739. if (url.indexOf("blob:") !== -1) {
  44740. codecSupportedFound = true;
  44741. }
  44742. if (codecSupportedFound) {
  44743. // Loading sound using XHR2
  44744. if (!this._streaming) {
  44745. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  44746. }
  44747. else {
  44748. this._htmlAudioElement = new Audio(url);
  44749. this._htmlAudioElement.controls = false;
  44750. this._htmlAudioElement.loop = this.loop;
  44751. this._htmlAudioElement.crossOrigin = "anonymous";
  44752. this._htmlAudioElement.preload = "auto";
  44753. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  44754. _this._isReadyToPlay = true;
  44755. if (_this.autoplay) {
  44756. _this.play();
  44757. }
  44758. if (_this._readyToPlayCallback) {
  44759. _this._readyToPlayCallback();
  44760. }
  44761. });
  44762. document.body.appendChild(this._htmlAudioElement);
  44763. }
  44764. break;
  44765. }
  44766. }
  44767. break;
  44768. default:
  44769. validParameter = false;
  44770. break;
  44771. }
  44772. if (!validParameter) {
  44773. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  44774. }
  44775. else {
  44776. if (!codecSupportedFound) {
  44777. this._isReadyToPlay = true;
  44778. // Simulating a ready to play event to avoid breaking code path
  44779. if (this._readyToPlayCallback) {
  44780. window.setTimeout(function () {
  44781. _this._readyToPlayCallback();
  44782. }, 1000);
  44783. }
  44784. }
  44785. }
  44786. }
  44787. }
  44788. else {
  44789. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  44790. this._scene.mainSoundTrack.AddSound(this);
  44791. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  44792. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  44793. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  44794. }
  44795. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  44796. if (this._readyToPlayCallback) {
  44797. window.setTimeout(function () {
  44798. _this._readyToPlayCallback();
  44799. }, 1000);
  44800. }
  44801. }
  44802. }
  44803. Sound.prototype.dispose = function () {
  44804. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  44805. if (this.isPlaying) {
  44806. this.stop();
  44807. }
  44808. this._isReadyToPlay = false;
  44809. if (this.soundTrackId === -1) {
  44810. this._scene.mainSoundTrack.RemoveSound(this);
  44811. }
  44812. else {
  44813. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  44814. }
  44815. if (this._soundGain) {
  44816. this._soundGain.disconnect();
  44817. this._soundGain = null;
  44818. }
  44819. if (this._soundPanner) {
  44820. this._soundPanner.disconnect();
  44821. this._soundPanner = null;
  44822. }
  44823. if (this._soundSource) {
  44824. this._soundSource.disconnect();
  44825. this._soundSource = null;
  44826. }
  44827. this._audioBuffer = null;
  44828. if (this._htmlAudioElement) {
  44829. this._htmlAudioElement.pause();
  44830. this._htmlAudioElement.src = "";
  44831. document.body.removeChild(this._htmlAudioElement);
  44832. }
  44833. if (this._connectedMesh) {
  44834. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44835. this._connectedMesh = null;
  44836. }
  44837. }
  44838. };
  44839. Sound.prototype.isReady = function () {
  44840. return this._isReadyToPlay;
  44841. };
  44842. Sound.prototype._soundLoaded = function (audioData) {
  44843. var _this = this;
  44844. this._isLoaded = true;
  44845. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  44846. _this._audioBuffer = buffer;
  44847. _this._isReadyToPlay = true;
  44848. if (_this.autoplay) {
  44849. _this.play();
  44850. }
  44851. if (_this._readyToPlayCallback) {
  44852. _this._readyToPlayCallback();
  44853. }
  44854. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  44855. };
  44856. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  44857. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44858. this._audioBuffer = audioBuffer;
  44859. this._isReadyToPlay = true;
  44860. }
  44861. };
  44862. Sound.prototype.updateOptions = function (options) {
  44863. if (options) {
  44864. this.loop = options.loop || this.loop;
  44865. this.maxDistance = options.maxDistance || this.maxDistance;
  44866. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  44867. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  44868. this.refDistance = options.refDistance || this.refDistance;
  44869. this.distanceModel = options.distanceModel || this.distanceModel;
  44870. this._playbackRate = options.playbackRate || this._playbackRate;
  44871. this._updateSpatialParameters();
  44872. if (this.isPlaying) {
  44873. if (this._streaming) {
  44874. this._htmlAudioElement.playbackRate = this._playbackRate;
  44875. }
  44876. else {
  44877. this._soundSource.playbackRate.value = this._playbackRate;
  44878. }
  44879. }
  44880. }
  44881. };
  44882. Sound.prototype._createSpatialParameters = function () {
  44883. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44884. if (this._scene.headphone) {
  44885. this._panningModel = "HRTF";
  44886. }
  44887. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  44888. this._updateSpatialParameters();
  44889. this._soundPanner.connect(this._ouputAudioNode);
  44890. this._inputAudioNode = this._soundPanner;
  44891. }
  44892. };
  44893. Sound.prototype._updateSpatialParameters = function () {
  44894. if (this.spatialSound) {
  44895. if (this.useCustomAttenuation) {
  44896. // Tricks to disable in a way embedded Web Audio attenuation
  44897. this._soundPanner.distanceModel = "linear";
  44898. this._soundPanner.maxDistance = Number.MAX_VALUE;
  44899. this._soundPanner.refDistance = 1;
  44900. this._soundPanner.rolloffFactor = 1;
  44901. this._soundPanner.panningModel = this._panningModel;
  44902. }
  44903. else {
  44904. this._soundPanner.distanceModel = this.distanceModel;
  44905. this._soundPanner.maxDistance = this.maxDistance;
  44906. this._soundPanner.refDistance = this.refDistance;
  44907. this._soundPanner.rolloffFactor = this.rolloffFactor;
  44908. this._soundPanner.panningModel = this._panningModel;
  44909. }
  44910. }
  44911. };
  44912. Sound.prototype.switchPanningModelToHRTF = function () {
  44913. this._panningModel = "HRTF";
  44914. this._switchPanningModel();
  44915. };
  44916. Sound.prototype.switchPanningModelToEqualPower = function () {
  44917. this._panningModel = "equalpower";
  44918. this._switchPanningModel();
  44919. };
  44920. Sound.prototype._switchPanningModel = function () {
  44921. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44922. this._soundPanner.panningModel = this._panningModel;
  44923. }
  44924. };
  44925. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  44926. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44927. if (this._isOutputConnected) {
  44928. this._ouputAudioNode.disconnect();
  44929. }
  44930. this._ouputAudioNode.connect(soundTrackAudioNode);
  44931. this._isOutputConnected = true;
  44932. }
  44933. };
  44934. /**
  44935. * Transform this sound into a directional source
  44936. * @param coneInnerAngle Size of the inner cone in degree
  44937. * @param coneOuterAngle Size of the outer cone in degree
  44938. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  44939. */
  44940. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  44941. if (coneOuterAngle < coneInnerAngle) {
  44942. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  44943. return;
  44944. }
  44945. this._coneInnerAngle = coneInnerAngle;
  44946. this._coneOuterAngle = coneOuterAngle;
  44947. this._coneOuterGain = coneOuterGain;
  44948. this._isDirectional = true;
  44949. if (this.isPlaying && this.loop) {
  44950. this.stop();
  44951. this.play();
  44952. }
  44953. };
  44954. Sound.prototype.setPosition = function (newPosition) {
  44955. this._position = newPosition;
  44956. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44957. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44958. }
  44959. };
  44960. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  44961. this._localDirection = newLocalDirection;
  44962. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  44963. this._updateDirection();
  44964. }
  44965. };
  44966. Sound.prototype._updateDirection = function () {
  44967. var mat = this._connectedMesh.getWorldMatrix();
  44968. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  44969. direction.normalize();
  44970. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  44971. };
  44972. Sound.prototype.updateDistanceFromListener = function () {
  44973. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  44974. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  44975. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  44976. }
  44977. };
  44978. Sound.prototype.setAttenuationFunction = function (callback) {
  44979. this._customAttenuationFunction = callback;
  44980. };
  44981. /**
  44982. * Play the sound
  44983. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  44984. * @param offset (optional) Start the sound setting it at a specific time
  44985. */
  44986. Sound.prototype.play = function (time, offset) {
  44987. var _this = this;
  44988. if (this._isReadyToPlay && this._scene.audioEnabled) {
  44989. try {
  44990. if (this._startOffset < 0) {
  44991. time = -this._startOffset;
  44992. this._startOffset = 0;
  44993. }
  44994. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44995. if (!this._soundSource || !this._streamingSource) {
  44996. if (this.spatialSound) {
  44997. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44998. if (this._isDirectional) {
  44999. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  45000. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  45001. this._soundPanner.coneOuterGain = this._coneOuterGain;
  45002. if (this._connectedMesh) {
  45003. this._updateDirection();
  45004. }
  45005. else {
  45006. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  45007. }
  45008. }
  45009. }
  45010. }
  45011. if (this._streaming) {
  45012. if (!this._streamingSource) {
  45013. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  45014. this._htmlAudioElement.onended = function () { _this._onended(); };
  45015. this._htmlAudioElement.playbackRate = this._playbackRate;
  45016. }
  45017. this._streamingSource.disconnect();
  45018. this._streamingSource.connect(this._inputAudioNode);
  45019. this._htmlAudioElement.play();
  45020. }
  45021. else {
  45022. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  45023. this._soundSource.buffer = this._audioBuffer;
  45024. this._soundSource.connect(this._inputAudioNode);
  45025. this._soundSource.loop = this.loop;
  45026. this._soundSource.playbackRate.value = this._playbackRate;
  45027. this._soundSource.onended = function () { _this._onended(); };
  45028. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  45029. }
  45030. this._startTime = startTime;
  45031. this.isPlaying = true;
  45032. this.isPaused = false;
  45033. }
  45034. catch (ex) {
  45035. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  45036. }
  45037. }
  45038. };
  45039. Sound.prototype._onended = function () {
  45040. this.isPlaying = false;
  45041. if (this.onended) {
  45042. this.onended();
  45043. }
  45044. };
  45045. /**
  45046. * Stop the sound
  45047. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  45048. */
  45049. Sound.prototype.stop = function (time) {
  45050. if (this.isPlaying) {
  45051. if (this._streaming) {
  45052. this._htmlAudioElement.pause();
  45053. // Test needed for Firefox or it will generate an Invalid State Error
  45054. if (this._htmlAudioElement.currentTime > 0) {
  45055. this._htmlAudioElement.currentTime = 0;
  45056. }
  45057. }
  45058. else {
  45059. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45060. this._soundSource.stop(stopTime);
  45061. this._soundSource.onended = null;
  45062. if (!this.isPaused) {
  45063. this._startOffset = 0;
  45064. }
  45065. }
  45066. this.isPlaying = false;
  45067. }
  45068. };
  45069. Sound.prototype.pause = function () {
  45070. if (this.isPlaying) {
  45071. this.isPaused = true;
  45072. if (this._streaming) {
  45073. this._htmlAudioElement.pause();
  45074. }
  45075. else {
  45076. this.stop(0);
  45077. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  45078. }
  45079. }
  45080. };
  45081. Sound.prototype.setVolume = function (newVolume, time) {
  45082. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45083. if (time) {
  45084. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  45085. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  45086. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  45087. }
  45088. else {
  45089. this._soundGain.gain.value = newVolume;
  45090. }
  45091. }
  45092. this._volume = newVolume;
  45093. };
  45094. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  45095. this._playbackRate = newPlaybackRate;
  45096. if (this.isPlaying) {
  45097. if (this._streaming) {
  45098. this._htmlAudioElement.playbackRate = this._playbackRate;
  45099. }
  45100. else {
  45101. this._soundSource.playbackRate.value = this._playbackRate;
  45102. }
  45103. }
  45104. };
  45105. Sound.prototype.getVolume = function () {
  45106. return this._volume;
  45107. };
  45108. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  45109. var _this = this;
  45110. if (this._connectedMesh) {
  45111. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45112. this._registerFunc = null;
  45113. }
  45114. this._connectedMesh = meshToConnectTo;
  45115. if (!this.spatialSound) {
  45116. this.spatialSound = true;
  45117. this._createSpatialParameters();
  45118. if (this.isPlaying && this.loop) {
  45119. this.stop();
  45120. this.play();
  45121. }
  45122. }
  45123. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  45124. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  45125. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  45126. };
  45127. Sound.prototype.detachFromMesh = function () {
  45128. if (this._connectedMesh) {
  45129. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45130. this._registerFunc = null;
  45131. this._connectedMesh = null;
  45132. }
  45133. };
  45134. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  45135. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  45136. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  45137. this._updateDirection();
  45138. }
  45139. };
  45140. Sound.prototype.clone = function () {
  45141. var _this = this;
  45142. if (!this._streaming) {
  45143. var setBufferAndRun = function () {
  45144. if (_this._isReadyToPlay) {
  45145. clonedSound._audioBuffer = _this.getAudioBuffer();
  45146. clonedSound._isReadyToPlay = true;
  45147. if (clonedSound.autoplay) {
  45148. clonedSound.play();
  45149. }
  45150. }
  45151. else {
  45152. window.setTimeout(setBufferAndRun, 300);
  45153. }
  45154. };
  45155. var currentOptions = {
  45156. autoplay: this.autoplay, loop: this.loop,
  45157. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  45158. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  45159. refDistance: this.refDistance, distanceModel: this.distanceModel
  45160. };
  45161. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  45162. if (this.useCustomAttenuation) {
  45163. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  45164. }
  45165. clonedSound.setPosition(this._position);
  45166. clonedSound.setPlaybackRate(this._playbackRate);
  45167. setBufferAndRun();
  45168. return clonedSound;
  45169. }
  45170. else {
  45171. return null;
  45172. }
  45173. };
  45174. Sound.prototype.getAudioBuffer = function () {
  45175. return this._audioBuffer;
  45176. };
  45177. Sound.prototype.serialize = function () {
  45178. var serializationObject = {
  45179. name: this.name,
  45180. url: this.name,
  45181. autoplay: this.autoplay,
  45182. loop: this.loop,
  45183. volume: this._volume,
  45184. spatialSound: this.spatialSound,
  45185. maxDistance: this.maxDistance,
  45186. rolloffFactor: this.rolloffFactor,
  45187. refDistance: this.refDistance,
  45188. distanceModel: this.distanceModel,
  45189. playbackRate: this._playbackRate,
  45190. panningModel: this._panningModel,
  45191. soundTrackId: this.soundTrackId
  45192. };
  45193. if (this.spatialSound) {
  45194. if (this._connectedMesh)
  45195. serializationObject.connectedMeshId = this._connectedMesh.id;
  45196. serializationObject.position = this._position.asArray();
  45197. serializationObject.refDistance = this.refDistance;
  45198. serializationObject.distanceModel = this.distanceModel;
  45199. serializationObject.isDirectional = this._isDirectional;
  45200. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  45201. serializationObject.coneInnerAngle = this._coneInnerAngle;
  45202. serializationObject.coneOuterAngle = this._coneOuterAngle;
  45203. serializationObject.coneOuterGain = this._coneOuterGain;
  45204. }
  45205. return serializationObject;
  45206. };
  45207. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  45208. var soundName = parsedSound.name;
  45209. var soundUrl;
  45210. if (parsedSound.url) {
  45211. soundUrl = rootUrl + parsedSound.url;
  45212. }
  45213. else {
  45214. soundUrl = rootUrl + soundName;
  45215. }
  45216. var options = {
  45217. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  45218. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  45219. rolloffFactor: parsedSound.rolloffFactor,
  45220. refDistance: parsedSound.refDistance,
  45221. distanceModel: parsedSound.distanceModel,
  45222. playbackRate: parsedSound.playbackRate
  45223. };
  45224. var newSound;
  45225. if (!sourceSound) {
  45226. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  45227. scene._addPendingData(newSound);
  45228. }
  45229. else {
  45230. var setBufferAndRun = function () {
  45231. if (sourceSound._isReadyToPlay) {
  45232. newSound._audioBuffer = sourceSound.getAudioBuffer();
  45233. newSound._isReadyToPlay = true;
  45234. if (newSound.autoplay) {
  45235. newSound.play();
  45236. }
  45237. }
  45238. else {
  45239. window.setTimeout(setBufferAndRun, 300);
  45240. }
  45241. };
  45242. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  45243. setBufferAndRun();
  45244. }
  45245. if (parsedSound.position) {
  45246. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  45247. newSound.setPosition(soundPosition);
  45248. }
  45249. if (parsedSound.isDirectional) {
  45250. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  45251. if (parsedSound.localDirectionToMesh) {
  45252. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  45253. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  45254. }
  45255. }
  45256. if (parsedSound.connectedMeshId) {
  45257. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  45258. if (connectedMesh) {
  45259. newSound.attachToMesh(connectedMesh);
  45260. }
  45261. }
  45262. return newSound;
  45263. };
  45264. return Sound;
  45265. }());
  45266. BABYLON.Sound = Sound;
  45267. })(BABYLON || (BABYLON = {}));
  45268. //# sourceMappingURL=babylon.sound.js.map
  45269. var BABYLON;
  45270. (function (BABYLON) {
  45271. var SoundTrack = (function () {
  45272. function SoundTrack(scene, options) {
  45273. this.id = -1;
  45274. this._isMainTrack = false;
  45275. this._isInitialized = false;
  45276. this._scene = scene;
  45277. this.soundCollection = new Array();
  45278. this._options = options;
  45279. if (!this._isMainTrack) {
  45280. this._scene.soundTracks.push(this);
  45281. this.id = this._scene.soundTracks.length - 1;
  45282. }
  45283. }
  45284. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  45285. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45286. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  45287. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  45288. if (this._options) {
  45289. if (this._options.volume) {
  45290. this._outputAudioNode.gain.value = this._options.volume;
  45291. }
  45292. if (this._options.mainTrack) {
  45293. this._isMainTrack = this._options.mainTrack;
  45294. }
  45295. }
  45296. this._isInitialized = true;
  45297. }
  45298. };
  45299. SoundTrack.prototype.dispose = function () {
  45300. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45301. if (this._connectedAnalyser) {
  45302. this._connectedAnalyser.stopDebugCanvas();
  45303. }
  45304. while (this.soundCollection.length) {
  45305. this.soundCollection[0].dispose();
  45306. }
  45307. if (this._outputAudioNode) {
  45308. this._outputAudioNode.disconnect();
  45309. }
  45310. this._outputAudioNode = null;
  45311. }
  45312. };
  45313. SoundTrack.prototype.AddSound = function (sound) {
  45314. if (!this._isInitialized) {
  45315. this._initializeSoundTrackAudioGraph();
  45316. }
  45317. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45318. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  45319. }
  45320. if (sound.soundTrackId) {
  45321. if (sound.soundTrackId === -1) {
  45322. this._scene.mainSoundTrack.RemoveSound(sound);
  45323. }
  45324. else {
  45325. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  45326. }
  45327. }
  45328. this.soundCollection.push(sound);
  45329. sound.soundTrackId = this.id;
  45330. };
  45331. SoundTrack.prototype.RemoveSound = function (sound) {
  45332. var index = this.soundCollection.indexOf(sound);
  45333. if (index !== -1) {
  45334. this.soundCollection.splice(index, 1);
  45335. }
  45336. };
  45337. SoundTrack.prototype.setVolume = function (newVolume) {
  45338. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45339. this._outputAudioNode.gain.value = newVolume;
  45340. }
  45341. };
  45342. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  45343. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45344. for (var i = 0; i < this.soundCollection.length; i++) {
  45345. this.soundCollection[i].switchPanningModelToHRTF();
  45346. }
  45347. }
  45348. };
  45349. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  45350. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45351. for (var i = 0; i < this.soundCollection.length; i++) {
  45352. this.soundCollection[i].switchPanningModelToEqualPower();
  45353. }
  45354. }
  45355. };
  45356. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  45357. if (this._connectedAnalyser) {
  45358. this._connectedAnalyser.stopDebugCanvas();
  45359. }
  45360. this._connectedAnalyser = analyser;
  45361. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45362. this._outputAudioNode.disconnect();
  45363. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  45364. }
  45365. };
  45366. return SoundTrack;
  45367. }());
  45368. BABYLON.SoundTrack = SoundTrack;
  45369. })(BABYLON || (BABYLON = {}));
  45370. //# sourceMappingURL=babylon.soundtrack.js.map
  45371. var BABYLON;
  45372. (function (BABYLON) {
  45373. var Analyser = (function () {
  45374. function Analyser(scene) {
  45375. this.SMOOTHING = 0.75;
  45376. this.FFT_SIZE = 512;
  45377. this.BARGRAPHAMPLITUDE = 256;
  45378. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45379. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45380. this._scene = scene;
  45381. this._audioEngine = BABYLON.Engine.audioEngine;
  45382. if (this._audioEngine.canUseWebAudio) {
  45383. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45384. this._webAudioAnalyser.minDecibels = -140;
  45385. this._webAudioAnalyser.maxDecibels = 0;
  45386. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45387. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45388. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45389. }
  45390. }
  45391. Analyser.prototype.getFrequencyBinCount = function () {
  45392. if (this._audioEngine.canUseWebAudio) {
  45393. return this._webAudioAnalyser.frequencyBinCount;
  45394. }
  45395. else {
  45396. return 0;
  45397. }
  45398. };
  45399. Analyser.prototype.getByteFrequencyData = function () {
  45400. if (this._audioEngine.canUseWebAudio) {
  45401. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45402. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45403. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45404. }
  45405. return this._byteFreqs;
  45406. };
  45407. Analyser.prototype.getByteTimeDomainData = function () {
  45408. if (this._audioEngine.canUseWebAudio) {
  45409. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45410. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45411. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45412. }
  45413. return this._byteTime;
  45414. };
  45415. Analyser.prototype.getFloatFrequencyData = function () {
  45416. if (this._audioEngine.canUseWebAudio) {
  45417. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45418. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45419. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45420. }
  45421. return this._floatFreqs;
  45422. };
  45423. Analyser.prototype.drawDebugCanvas = function () {
  45424. var _this = this;
  45425. if (this._audioEngine.canUseWebAudio) {
  45426. if (!this._debugCanvas) {
  45427. this._debugCanvas = document.createElement("canvas");
  45428. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45429. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45430. this._debugCanvas.style.position = "absolute";
  45431. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45432. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45433. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45434. document.body.appendChild(this._debugCanvas);
  45435. this._registerFunc = function () {
  45436. _this.drawDebugCanvas();
  45437. };
  45438. this._scene.registerBeforeRender(this._registerFunc);
  45439. }
  45440. if (this._registerFunc) {
  45441. var workingArray = this.getByteFrequencyData();
  45442. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45443. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45444. // Draw the frequency domain chart.
  45445. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45446. var value = workingArray[i];
  45447. var percent = value / this.BARGRAPHAMPLITUDE;
  45448. var height = this.DEBUGCANVASSIZE.height * percent;
  45449. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45450. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45451. var hue = i / this.getFrequencyBinCount() * 360;
  45452. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45453. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45454. }
  45455. }
  45456. }
  45457. };
  45458. Analyser.prototype.stopDebugCanvas = function () {
  45459. if (this._debugCanvas) {
  45460. this._scene.unregisterBeforeRender(this._registerFunc);
  45461. this._registerFunc = null;
  45462. document.body.removeChild(this._debugCanvas);
  45463. this._debugCanvas = null;
  45464. this._debugCanvasContext = null;
  45465. }
  45466. };
  45467. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45468. if (this._audioEngine.canUseWebAudio) {
  45469. inputAudioNode.connect(this._webAudioAnalyser);
  45470. this._webAudioAnalyser.connect(outputAudioNode);
  45471. }
  45472. };
  45473. Analyser.prototype.dispose = function () {
  45474. if (this._audioEngine.canUseWebAudio) {
  45475. this._webAudioAnalyser.disconnect();
  45476. }
  45477. };
  45478. return Analyser;
  45479. }());
  45480. BABYLON.Analyser = Analyser;
  45481. })(BABYLON || (BABYLON = {}));
  45482. //# sourceMappingURL=babylon.analyser.js.map
  45483. var BABYLON;
  45484. (function (BABYLON) {
  45485. var CubeTexture = (function (_super) {
  45486. __extends(CubeTexture, _super);
  45487. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  45488. if (onLoad === void 0) { onLoad = null; }
  45489. if (onError === void 0) { onError = null; }
  45490. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45491. if (prefiltered === void 0) { prefiltered = false; }
  45492. if (forcedExtension === void 0) { forcedExtension = null; }
  45493. var _this = _super.call(this, scene) || this;
  45494. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  45495. _this.name = rootUrl;
  45496. _this.url = rootUrl;
  45497. _this._noMipmap = noMipmap;
  45498. _this.hasAlpha = false;
  45499. _this._format = format;
  45500. _this._prefiltered = prefiltered;
  45501. _this.isCube = true;
  45502. _this._textureMatrix = BABYLON.Matrix.Identity();
  45503. if (prefiltered) {
  45504. _this.gammaSpace = false;
  45505. }
  45506. if (!rootUrl && !files) {
  45507. return _this;
  45508. }
  45509. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  45510. if (!files) {
  45511. if (!extensions) {
  45512. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  45513. }
  45514. files = [];
  45515. for (var index = 0; index < extensions.length; index++) {
  45516. files.push(rootUrl + extensions[index]);
  45517. }
  45518. _this._extensions = extensions;
  45519. }
  45520. _this._files = files;
  45521. if (!_this._texture) {
  45522. if (!scene.useDelayedTextureLoading) {
  45523. if (prefiltered) {
  45524. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  45525. }
  45526. else {
  45527. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  45528. }
  45529. }
  45530. else {
  45531. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  45532. }
  45533. }
  45534. else if (onLoad) {
  45535. if (_this._texture.isReady) {
  45536. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  45537. }
  45538. else {
  45539. _this._texture.onLoadedObservable.add(onLoad);
  45540. }
  45541. }
  45542. return _this;
  45543. }
  45544. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  45545. return new CubeTexture("", scene, null, noMipmap, files);
  45546. };
  45547. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  45548. if (forcedExtension === void 0) { forcedExtension = null; }
  45549. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  45550. };
  45551. // Methods
  45552. CubeTexture.prototype.delayLoad = function () {
  45553. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45554. return;
  45555. }
  45556. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45557. this._texture = this._getFromCache(this.url, this._noMipmap);
  45558. if (!this._texture) {
  45559. if (this._prefiltered) {
  45560. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  45561. }
  45562. else {
  45563. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  45564. }
  45565. }
  45566. };
  45567. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  45568. return this._textureMatrix;
  45569. };
  45570. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  45571. this._textureMatrix = value;
  45572. };
  45573. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45574. var texture = BABYLON.SerializationHelper.Parse(function () {
  45575. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  45576. }, parsedTexture, scene);
  45577. // Animations
  45578. if (parsedTexture.animations) {
  45579. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  45580. var parsedAnimation = parsedTexture.animations[animationIndex];
  45581. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45582. }
  45583. }
  45584. return texture;
  45585. };
  45586. CubeTexture.prototype.clone = function () {
  45587. var _this = this;
  45588. return BABYLON.SerializationHelper.Clone(function () {
  45589. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  45590. }, this);
  45591. };
  45592. return CubeTexture;
  45593. }(BABYLON.BaseTexture));
  45594. BABYLON.CubeTexture = CubeTexture;
  45595. })(BABYLON || (BABYLON = {}));
  45596. //# sourceMappingURL=babylon.cubeTexture.js.map
  45597. var BABYLON;
  45598. (function (BABYLON) {
  45599. var RenderTargetTexture = (function (_super) {
  45600. __extends(RenderTargetTexture, _super);
  45601. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  45602. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  45603. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45604. if (isCube === void 0) { isCube = false; }
  45605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45606. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45607. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  45608. if (isMulti === void 0) { isMulti = false; }
  45609. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  45610. _this.isCube = isCube;
  45611. /**
  45612. * Use this list to define the list of mesh you want to render.
  45613. */
  45614. _this.renderList = new Array();
  45615. _this.renderParticles = true;
  45616. _this.renderSprites = false;
  45617. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  45618. _this.ignoreCameraViewport = false;
  45619. // Events
  45620. /**
  45621. * An event triggered when the texture is unbind.
  45622. * @type {BABYLON.Observable}
  45623. */
  45624. _this.onBeforeBindObservable = new BABYLON.Observable();
  45625. /**
  45626. * An event triggered when the texture is unbind.
  45627. * @type {BABYLON.Observable}
  45628. */
  45629. _this.onAfterUnbindObservable = new BABYLON.Observable();
  45630. /**
  45631. * An event triggered before rendering the texture
  45632. * @type {BABYLON.Observable}
  45633. */
  45634. _this.onBeforeRenderObservable = new BABYLON.Observable();
  45635. /**
  45636. * An event triggered after rendering the texture
  45637. * @type {BABYLON.Observable}
  45638. */
  45639. _this.onAfterRenderObservable = new BABYLON.Observable();
  45640. /**
  45641. * An event triggered after the texture clear
  45642. * @type {BABYLON.Observable}
  45643. */
  45644. _this.onClearObservable = new BABYLON.Observable();
  45645. _this._currentRefreshId = -1;
  45646. _this._refreshRate = 1;
  45647. _this._samples = 1;
  45648. scene = _this.getScene();
  45649. _this.name = name;
  45650. _this.isRenderTarget = true;
  45651. _this._size = size;
  45652. _this._generateMipMaps = generateMipMaps;
  45653. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  45654. // Rendering groups
  45655. _this._renderingManager = new BABYLON.RenderingManager(scene);
  45656. if (isMulti) {
  45657. return _this;
  45658. }
  45659. _this._renderTargetOptions = {
  45660. generateMipMaps: generateMipMaps,
  45661. type: type,
  45662. samplingMode: samplingMode,
  45663. generateDepthBuffer: generateDepthBuffer,
  45664. generateStencilBuffer: generateStencilBuffer
  45665. };
  45666. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  45667. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45668. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45669. }
  45670. if (isCube) {
  45671. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  45672. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  45673. _this._textureMatrix = BABYLON.Matrix.Identity();
  45674. }
  45675. else {
  45676. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  45677. }
  45678. return _this;
  45679. }
  45680. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  45681. get: function () {
  45682. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  45683. },
  45684. enumerable: true,
  45685. configurable: true
  45686. });
  45687. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  45688. get: function () {
  45689. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  45690. },
  45691. enumerable: true,
  45692. configurable: true
  45693. });
  45694. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  45695. get: function () {
  45696. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  45697. },
  45698. enumerable: true,
  45699. configurable: true
  45700. });
  45701. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  45702. set: function (callback) {
  45703. if (this._onAfterUnbindObserver) {
  45704. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  45705. }
  45706. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  45707. },
  45708. enumerable: true,
  45709. configurable: true
  45710. });
  45711. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  45712. set: function (callback) {
  45713. if (this._onBeforeRenderObserver) {
  45714. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45715. }
  45716. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45717. },
  45718. enumerable: true,
  45719. configurable: true
  45720. });
  45721. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  45722. set: function (callback) {
  45723. if (this._onAfterRenderObserver) {
  45724. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45725. }
  45726. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45727. },
  45728. enumerable: true,
  45729. configurable: true
  45730. });
  45731. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  45732. set: function (callback) {
  45733. if (this._onClearObserver) {
  45734. this.onClearObservable.remove(this._onClearObserver);
  45735. }
  45736. this._onClearObserver = this.onClearObservable.add(callback);
  45737. },
  45738. enumerable: true,
  45739. configurable: true
  45740. });
  45741. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  45742. get: function () {
  45743. return this._renderTargetOptions;
  45744. },
  45745. enumerable: true,
  45746. configurable: true
  45747. });
  45748. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  45749. get: function () {
  45750. return this._samples;
  45751. },
  45752. set: function (value) {
  45753. if (this._samples === value) {
  45754. return;
  45755. }
  45756. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  45757. },
  45758. enumerable: true,
  45759. configurable: true
  45760. });
  45761. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  45762. this._currentRefreshId = -1;
  45763. };
  45764. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  45765. get: function () {
  45766. return this._refreshRate;
  45767. },
  45768. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  45769. set: function (value) {
  45770. this._refreshRate = value;
  45771. this.resetRefreshCounter();
  45772. },
  45773. enumerable: true,
  45774. configurable: true
  45775. });
  45776. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  45777. if (!this._postProcessManager) {
  45778. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  45779. this._postProcesses = new Array();
  45780. }
  45781. this._postProcesses.push(postProcess);
  45782. this._postProcesses[0].autoClear = false;
  45783. };
  45784. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  45785. if (!this._postProcesses) {
  45786. return;
  45787. }
  45788. if (dispose) {
  45789. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  45790. var postProcess = _a[_i];
  45791. postProcess.dispose();
  45792. postProcess = null;
  45793. }
  45794. }
  45795. this._postProcesses = [];
  45796. };
  45797. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  45798. if (!this._postProcesses) {
  45799. return;
  45800. }
  45801. var index = this._postProcesses.indexOf(postProcess);
  45802. if (index === -1) {
  45803. return;
  45804. }
  45805. this._postProcesses.splice(index, 1);
  45806. if (this._postProcesses.length > 0) {
  45807. this._postProcesses[0].autoClear = false;
  45808. }
  45809. };
  45810. RenderTargetTexture.prototype._shouldRender = function () {
  45811. if (this._currentRefreshId === -1) {
  45812. this._currentRefreshId = 1;
  45813. return true;
  45814. }
  45815. if (this.refreshRate === this._currentRefreshId) {
  45816. this._currentRefreshId = 1;
  45817. return true;
  45818. }
  45819. this._currentRefreshId++;
  45820. return false;
  45821. };
  45822. RenderTargetTexture.prototype.getRenderSize = function () {
  45823. return this._size;
  45824. };
  45825. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  45826. get: function () {
  45827. return true;
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. RenderTargetTexture.prototype.scale = function (ratio) {
  45833. var newSize = this._size * ratio;
  45834. this.resize(newSize);
  45835. };
  45836. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  45837. if (this.isCube) {
  45838. return this._textureMatrix;
  45839. }
  45840. return _super.prototype.getReflectionTextureMatrix.call(this);
  45841. };
  45842. RenderTargetTexture.prototype.resize = function (size) {
  45843. this.releaseInternalTexture();
  45844. if (this.isCube) {
  45845. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  45846. }
  45847. else {
  45848. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  45849. }
  45850. };
  45851. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  45852. var scene = this.getScene();
  45853. var engine = scene.getEngine();
  45854. if (this.useCameraPostProcesses !== undefined) {
  45855. useCameraPostProcess = this.useCameraPostProcesses;
  45856. }
  45857. if (this._waitingRenderList) {
  45858. this.renderList = [];
  45859. for (var index = 0; index < this._waitingRenderList.length; index++) {
  45860. var id = this._waitingRenderList[index];
  45861. this.renderList.push(scene.getMeshByID(id));
  45862. }
  45863. delete this._waitingRenderList;
  45864. }
  45865. // Is predicate defined?
  45866. if (this.renderListPredicate) {
  45867. this.renderList.splice(0); // Clear previous renderList
  45868. var sceneMeshes = this.getScene().meshes;
  45869. for (var index = 0; index < sceneMeshes.length; index++) {
  45870. var mesh = sceneMeshes[index];
  45871. if (this.renderListPredicate(mesh)) {
  45872. this.renderList.push(mesh);
  45873. }
  45874. }
  45875. }
  45876. if (this.renderList && this.renderList.length === 0) {
  45877. return;
  45878. }
  45879. this.onBeforeBindObservable.notifyObservers(this);
  45880. // Set custom projection.
  45881. // Needs to be before binding to prevent changing the aspect ratio.
  45882. var camera;
  45883. if (this.activeCamera) {
  45884. camera = this.activeCamera;
  45885. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  45886. if (this.activeCamera !== scene.activeCamera) {
  45887. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  45888. }
  45889. }
  45890. else {
  45891. camera = scene.activeCamera;
  45892. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  45893. }
  45894. // Prepare renderingManager
  45895. this._renderingManager.reset();
  45896. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  45897. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  45898. var sceneRenderId = scene.getRenderId();
  45899. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  45900. var mesh = currentRenderList[meshIndex];
  45901. if (mesh) {
  45902. if (!mesh.isReady()) {
  45903. // Reset _currentRefreshId
  45904. this.resetRefreshCounter();
  45905. continue;
  45906. }
  45907. mesh._preActivateForIntermediateRendering(sceneRenderId);
  45908. var isMasked = void 0;
  45909. if (!this.renderList) {
  45910. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  45911. }
  45912. else {
  45913. isMasked = false;
  45914. }
  45915. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  45916. mesh._activate(sceneRenderId);
  45917. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  45918. var subMesh = mesh.subMeshes[subIndex];
  45919. scene._activeIndices.addCount(subMesh.indexCount, false);
  45920. this._renderingManager.dispatch(subMesh);
  45921. }
  45922. }
  45923. }
  45924. }
  45925. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  45926. var particleSystem = scene.particleSystems[particleIndex];
  45927. var emitter = particleSystem.emitter;
  45928. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  45929. continue;
  45930. }
  45931. if (currentRenderList.indexOf(emitter) >= 0) {
  45932. this._renderingManager.dispatchParticles(particleSystem);
  45933. }
  45934. }
  45935. if (this.isCube) {
  45936. for (var face = 0; face < 6; face++) {
  45937. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45938. scene.incrementRenderId();
  45939. scene.resetCachedMaterial();
  45940. }
  45941. }
  45942. else {
  45943. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45944. }
  45945. this.onAfterUnbindObservable.notifyObservers(this);
  45946. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  45947. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  45948. }
  45949. engine.setViewport(scene.activeCamera.viewport);
  45950. scene.resetCachedMaterial();
  45951. };
  45952. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  45953. var _this = this;
  45954. var scene = this.getScene();
  45955. var engine = scene.getEngine();
  45956. // Bind
  45957. if (this._postProcessManager) {
  45958. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  45959. }
  45960. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  45961. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  45962. }
  45963. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  45964. // Clear
  45965. if (this.onClearObservable.hasObservers()) {
  45966. this.onClearObservable.notifyObservers(engine);
  45967. }
  45968. else {
  45969. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  45970. }
  45971. if (!this._doNotChangeAspectRatio) {
  45972. scene.updateTransformMatrix(true);
  45973. }
  45974. // Render
  45975. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  45976. if (this._postProcessManager) {
  45977. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  45978. }
  45979. else if (useCameraPostProcess) {
  45980. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  45981. }
  45982. if (!this._doNotChangeAspectRatio) {
  45983. scene.updateTransformMatrix(true);
  45984. }
  45985. // Dump ?
  45986. if (dumpForDebug) {
  45987. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  45988. }
  45989. // Unbind
  45990. if (!this.isCube || faceIndex === 5) {
  45991. if (this.isCube) {
  45992. if (faceIndex === 5) {
  45993. engine.generateMipMapsForCubemap(this._texture);
  45994. }
  45995. }
  45996. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  45997. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  45998. });
  45999. }
  46000. else {
  46001. this.onAfterRenderObservable.notifyObservers(faceIndex);
  46002. }
  46003. };
  46004. /**
  46005. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  46006. * This allowed control for front to back rendering or reversly depending of the special needs.
  46007. *
  46008. * @param renderingGroupId The rendering group id corresponding to its index
  46009. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  46010. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  46011. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  46012. */
  46013. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  46014. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  46015. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  46016. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  46017. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  46018. };
  46019. /**
  46020. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  46021. *
  46022. * @param renderingGroupId The rendering group id corresponding to its index
  46023. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  46024. */
  46025. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  46026. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  46027. };
  46028. RenderTargetTexture.prototype.clone = function () {
  46029. var textureSize = this.getSize();
  46030. 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);
  46031. // Base texture
  46032. newTexture.hasAlpha = this.hasAlpha;
  46033. newTexture.level = this.level;
  46034. // RenderTarget Texture
  46035. newTexture.coordinatesMode = this.coordinatesMode;
  46036. newTexture.renderList = this.renderList.slice(0);
  46037. return newTexture;
  46038. };
  46039. RenderTargetTexture.prototype.serialize = function () {
  46040. if (!this.name) {
  46041. return null;
  46042. }
  46043. var serializationObject = _super.prototype.serialize.call(this);
  46044. serializationObject.renderTargetSize = this.getRenderSize();
  46045. serializationObject.renderList = [];
  46046. for (var index = 0; index < this.renderList.length; index++) {
  46047. serializationObject.renderList.push(this.renderList[index].id);
  46048. }
  46049. return serializationObject;
  46050. };
  46051. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  46052. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  46053. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  46054. };
  46055. RenderTargetTexture.prototype.dispose = function () {
  46056. if (this._postProcessManager) {
  46057. this._postProcessManager.dispose();
  46058. this._postProcessManager = null;
  46059. }
  46060. this.clearPostProcesses(true);
  46061. this.renderList = null;
  46062. // Remove from custom render targets
  46063. var scene = this.getScene();
  46064. var index = scene.customRenderTargets.indexOf(this);
  46065. if (index >= 0) {
  46066. scene.customRenderTargets.splice(index, 1);
  46067. }
  46068. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  46069. var camera = _a[_i];
  46070. index = camera.customRenderTargets.indexOf(this);
  46071. if (index >= 0) {
  46072. camera.customRenderTargets.splice(index, 1);
  46073. }
  46074. }
  46075. _super.prototype.dispose.call(this);
  46076. };
  46077. RenderTargetTexture.prototype._rebuild = function () {
  46078. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  46079. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  46080. }
  46081. if (this._postProcessManager) {
  46082. this._postProcessManager._rebuild();
  46083. }
  46084. };
  46085. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  46086. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  46087. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  46088. return RenderTargetTexture;
  46089. }(BABYLON.Texture));
  46090. BABYLON.RenderTargetTexture = RenderTargetTexture;
  46091. })(BABYLON || (BABYLON = {}));
  46092. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  46093. var BABYLON;
  46094. (function (BABYLON) {
  46095. ;
  46096. var MultiRenderTarget = (function (_super) {
  46097. __extends(MultiRenderTarget, _super);
  46098. function MultiRenderTarget(name, size, count, scene, options) {
  46099. var _this = this;
  46100. options = options || {};
  46101. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  46102. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  46103. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  46104. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  46105. if (!_this.isSupported) {
  46106. _this.dispose();
  46107. return;
  46108. }
  46109. var types = [];
  46110. var samplingModes = [];
  46111. for (var i = 0; i < count; i++) {
  46112. if (options.types && options.types[i]) {
  46113. types.push(options.types[i]);
  46114. }
  46115. else {
  46116. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  46117. }
  46118. if (options.samplingModes && options.samplingModes[i]) {
  46119. samplingModes.push(options.samplingModes[i]);
  46120. }
  46121. else {
  46122. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46123. }
  46124. }
  46125. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  46126. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  46127. _this._count = count;
  46128. _this._size = size;
  46129. _this._multiRenderTargetOptions = {
  46130. samplingModes: samplingModes,
  46131. generateMipMaps: generateMipMaps,
  46132. generateDepthBuffer: generateDepthBuffer,
  46133. generateStencilBuffer: generateStencilBuffer,
  46134. generateDepthTexture: generateDepthTexture,
  46135. types: types,
  46136. textureCount: count
  46137. };
  46138. _this._createInternalTextures();
  46139. _this._createTextures();
  46140. return _this;
  46141. }
  46142. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  46143. get: function () {
  46144. var engine = this.getScene().getEngine();
  46145. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  46146. },
  46147. enumerable: true,
  46148. configurable: true
  46149. });
  46150. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  46151. get: function () {
  46152. return this._textures;
  46153. },
  46154. enumerable: true,
  46155. configurable: true
  46156. });
  46157. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  46158. get: function () {
  46159. return this._textures[this._textures.length - 1];
  46160. },
  46161. enumerable: true,
  46162. configurable: true
  46163. });
  46164. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  46165. set: function (wrap) {
  46166. if (this._textures) {
  46167. for (var i = 0; i < this._textures.length; i++) {
  46168. this._textures[i].wrapU = wrap;
  46169. }
  46170. }
  46171. },
  46172. enumerable: true,
  46173. configurable: true
  46174. });
  46175. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  46176. set: function (wrap) {
  46177. if (this._textures) {
  46178. for (var i = 0; i < this._textures.length; i++) {
  46179. this._textures[i].wrapV = wrap;
  46180. }
  46181. }
  46182. },
  46183. enumerable: true,
  46184. configurable: true
  46185. });
  46186. MultiRenderTarget.prototype._rebuild = function () {
  46187. this.releaseInternalTextures();
  46188. this._createInternalTextures();
  46189. for (var i = 0; i < this._internalTextures.length; i++) {
  46190. var texture = this._textures[i];
  46191. texture._texture = this._internalTextures[i];
  46192. }
  46193. // Keeps references to frame buffer and stencil/depth buffer
  46194. this._texture = this._internalTextures[0];
  46195. };
  46196. MultiRenderTarget.prototype._createInternalTextures = function () {
  46197. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  46198. };
  46199. MultiRenderTarget.prototype._createTextures = function () {
  46200. this._textures = [];
  46201. for (var i = 0; i < this._internalTextures.length; i++) {
  46202. var texture = new BABYLON.Texture(null, this.getScene());
  46203. texture._texture = this._internalTextures[i];
  46204. this._textures.push(texture);
  46205. }
  46206. // Keeps references to frame buffer and stencil/depth buffer
  46207. this._texture = this._internalTextures[0];
  46208. };
  46209. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  46210. get: function () {
  46211. return this._samples;
  46212. },
  46213. set: function (value) {
  46214. if (this._samples === value) {
  46215. return;
  46216. }
  46217. for (var i = 0; i < this._internalTextures.length; i++) {
  46218. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  46219. }
  46220. },
  46221. enumerable: true,
  46222. configurable: true
  46223. });
  46224. MultiRenderTarget.prototype.resize = function (size) {
  46225. this.releaseInternalTextures();
  46226. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  46227. this._createInternalTextures();
  46228. };
  46229. MultiRenderTarget.prototype.dispose = function () {
  46230. this.releaseInternalTextures();
  46231. _super.prototype.dispose.call(this);
  46232. };
  46233. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  46234. if (!this._internalTextures) {
  46235. return;
  46236. }
  46237. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  46238. if (this._internalTextures[i] !== undefined) {
  46239. this._internalTextures[i].dispose();
  46240. this._internalTextures.splice(i, 1);
  46241. }
  46242. }
  46243. };
  46244. return MultiRenderTarget;
  46245. }(BABYLON.RenderTargetTexture));
  46246. BABYLON.MultiRenderTarget = MultiRenderTarget;
  46247. })(BABYLON || (BABYLON = {}));
  46248. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  46249. /// <reference path="babylon.renderTargetTexture.ts" />
  46250. var BABYLON;
  46251. (function (BABYLON) {
  46252. var MirrorTexture = (function (_super) {
  46253. __extends(MirrorTexture, _super);
  46254. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  46255. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46256. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46257. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46258. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  46259. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  46260. _this._transformMatrix = BABYLON.Matrix.Zero();
  46261. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  46262. _this._blurKernelX = 0;
  46263. _this._blurKernelY = 0;
  46264. _this._blurRatio = 1.0;
  46265. _this.ignoreCameraViewport = true;
  46266. _this.onBeforeRenderObservable.add(function () {
  46267. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  46268. _this._savedViewMatrix = scene.getViewMatrix();
  46269. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  46270. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  46271. scene.clipPlane = _this.mirrorPlane;
  46272. scene.getEngine().cullBackFaces = false;
  46273. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  46274. });
  46275. _this.onAfterRenderObservable.add(function () {
  46276. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  46277. scene.getEngine().cullBackFaces = true;
  46278. scene._mirroredCameraPosition = null;
  46279. delete scene.clipPlane;
  46280. });
  46281. return _this;
  46282. }
  46283. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  46284. get: function () {
  46285. return this._blurRatio;
  46286. },
  46287. set: function (value) {
  46288. if (this._blurRatio === value) {
  46289. return;
  46290. }
  46291. this._blurRatio = value;
  46292. this._preparePostProcesses();
  46293. },
  46294. enumerable: true,
  46295. configurable: true
  46296. });
  46297. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  46298. set: function (value) {
  46299. this.blurKernelX = value;
  46300. this.blurKernelY = value;
  46301. },
  46302. enumerable: true,
  46303. configurable: true
  46304. });
  46305. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  46306. get: function () {
  46307. return this._blurKernelX;
  46308. },
  46309. set: function (value) {
  46310. if (this._blurKernelX === value) {
  46311. return;
  46312. }
  46313. this._blurKernelX = value;
  46314. this._preparePostProcesses();
  46315. },
  46316. enumerable: true,
  46317. configurable: true
  46318. });
  46319. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  46320. get: function () {
  46321. return this._blurKernelY;
  46322. },
  46323. set: function (value) {
  46324. if (this._blurKernelY === value) {
  46325. return;
  46326. }
  46327. this._blurKernelY = value;
  46328. this._preparePostProcesses();
  46329. },
  46330. enumerable: true,
  46331. configurable: true
  46332. });
  46333. MirrorTexture.prototype._preparePostProcesses = function () {
  46334. this.clearPostProcesses(true);
  46335. if (this._blurKernelX && this._blurKernelY) {
  46336. var engine = this.getScene().getEngine();
  46337. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46338. 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);
  46339. this._blurX.autoClear = false;
  46340. if (this._blurRatio === 1 && this.samples < 2) {
  46341. this._blurX.outputTexture = this._texture;
  46342. }
  46343. else {
  46344. this._blurX.alwaysForcePOT = true;
  46345. }
  46346. 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);
  46347. this._blurY.autoClear = false;
  46348. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  46349. this.addPostProcess(this._blurX);
  46350. this.addPostProcess(this._blurY);
  46351. }
  46352. };
  46353. MirrorTexture.prototype.clone = function () {
  46354. var textureSize = this.getSize();
  46355. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  46356. // Base texture
  46357. newTexture.hasAlpha = this.hasAlpha;
  46358. newTexture.level = this.level;
  46359. // Mirror Texture
  46360. newTexture.mirrorPlane = this.mirrorPlane.clone();
  46361. newTexture.renderList = this.renderList.slice(0);
  46362. return newTexture;
  46363. };
  46364. MirrorTexture.prototype.serialize = function () {
  46365. if (!this.name) {
  46366. return null;
  46367. }
  46368. var serializationObject = _super.prototype.serialize.call(this);
  46369. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  46370. return serializationObject;
  46371. };
  46372. return MirrorTexture;
  46373. }(BABYLON.RenderTargetTexture));
  46374. BABYLON.MirrorTexture = MirrorTexture;
  46375. })(BABYLON || (BABYLON = {}));
  46376. //# sourceMappingURL=babylon.mirrorTexture.js.map
  46377. /// <reference path="babylon.renderTargetTexture.ts" />
  46378. var BABYLON;
  46379. (function (BABYLON) {
  46380. /**
  46381. * Creates a refraction texture used by refraction channel of the standard material.
  46382. * @param name the texture name
  46383. * @param size size of the underlying texture
  46384. * @param scene root scene
  46385. */
  46386. var RefractionTexture = (function (_super) {
  46387. __extends(RefractionTexture, _super);
  46388. function RefractionTexture(name, size, scene, generateMipMaps) {
  46389. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  46390. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  46391. _this.depth = 2.0;
  46392. _this.onBeforeRenderObservable.add(function () {
  46393. scene.clipPlane = _this.refractionPlane;
  46394. });
  46395. _this.onAfterRenderObservable.add(function () {
  46396. delete scene.clipPlane;
  46397. });
  46398. return _this;
  46399. }
  46400. RefractionTexture.prototype.clone = function () {
  46401. var textureSize = this.getSize();
  46402. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  46403. // Base texture
  46404. newTexture.hasAlpha = this.hasAlpha;
  46405. newTexture.level = this.level;
  46406. // Refraction Texture
  46407. newTexture.refractionPlane = this.refractionPlane.clone();
  46408. newTexture.renderList = this.renderList.slice(0);
  46409. newTexture.depth = this.depth;
  46410. return newTexture;
  46411. };
  46412. RefractionTexture.prototype.serialize = function () {
  46413. if (!this.name) {
  46414. return null;
  46415. }
  46416. var serializationObject = _super.prototype.serialize.call(this);
  46417. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  46418. serializationObject.depth = this.depth;
  46419. return serializationObject;
  46420. };
  46421. return RefractionTexture;
  46422. }(BABYLON.RenderTargetTexture));
  46423. BABYLON.RefractionTexture = RefractionTexture;
  46424. })(BABYLON || (BABYLON = {}));
  46425. //# sourceMappingURL=babylon.refractionTexture.js.map
  46426. /// <reference path="babylon.texture.ts" />
  46427. var BABYLON;
  46428. (function (BABYLON) {
  46429. var DynamicTexture = (function (_super) {
  46430. __extends(DynamicTexture, _super);
  46431. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  46432. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46433. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  46434. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  46435. _this.name = name;
  46436. var engine = _this.getScene().getEngine();
  46437. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46438. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46439. _this._generateMipMaps = generateMipMaps;
  46440. if (options.getContext) {
  46441. _this._canvas = options;
  46442. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46443. }
  46444. else {
  46445. _this._canvas = document.createElement("canvas");
  46446. if (options.width) {
  46447. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46448. }
  46449. else {
  46450. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  46451. }
  46452. }
  46453. var textureSize = _this.getSize();
  46454. _this._canvas.width = textureSize.width;
  46455. _this._canvas.height = textureSize.height;
  46456. _this._context = _this._canvas.getContext("2d");
  46457. return _this;
  46458. }
  46459. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  46460. get: function () {
  46461. return true;
  46462. },
  46463. enumerable: true,
  46464. configurable: true
  46465. });
  46466. DynamicTexture.prototype._recreate = function (textureSize) {
  46467. this._canvas.width = textureSize.width;
  46468. this._canvas.height = textureSize.height;
  46469. this.releaseInternalTexture();
  46470. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  46471. };
  46472. DynamicTexture.prototype.scale = function (ratio) {
  46473. var textureSize = this.getSize();
  46474. textureSize.width *= ratio;
  46475. textureSize.height *= ratio;
  46476. this._recreate(textureSize);
  46477. };
  46478. DynamicTexture.prototype.scaleTo = function (width, height) {
  46479. var textureSize = this.getSize();
  46480. textureSize.width = width;
  46481. textureSize.height = height;
  46482. this._recreate(textureSize);
  46483. };
  46484. DynamicTexture.prototype.getContext = function () {
  46485. return this._context;
  46486. };
  46487. DynamicTexture.prototype.clear = function () {
  46488. var size = this.getSize();
  46489. this._context.fillRect(0, 0, size.width, size.height);
  46490. };
  46491. DynamicTexture.prototype.update = function (invertY) {
  46492. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  46493. };
  46494. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  46495. if (update === void 0) { update = true; }
  46496. var size = this.getSize();
  46497. if (clearColor) {
  46498. this._context.fillStyle = clearColor;
  46499. this._context.fillRect(0, 0, size.width, size.height);
  46500. }
  46501. this._context.font = font;
  46502. if (x === null || x === undefined) {
  46503. var textSize = this._context.measureText(text);
  46504. x = (size.width - textSize.width) / 2;
  46505. }
  46506. if (y === null || y === undefined) {
  46507. var fontSize = parseInt((font.replace(/\D/g, '')));
  46508. ;
  46509. y = (size.height / 2) + (fontSize / 3.65);
  46510. }
  46511. this._context.fillStyle = color;
  46512. this._context.fillText(text, x, y);
  46513. if (update) {
  46514. this.update(invertY);
  46515. }
  46516. };
  46517. DynamicTexture.prototype.clone = function () {
  46518. var textureSize = this.getSize();
  46519. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  46520. // Base texture
  46521. newTexture.hasAlpha = this.hasAlpha;
  46522. newTexture.level = this.level;
  46523. // Dynamic Texture
  46524. newTexture.wrapU = this.wrapU;
  46525. newTexture.wrapV = this.wrapV;
  46526. return newTexture;
  46527. };
  46528. DynamicTexture.prototype._rebuild = function () {
  46529. this.update();
  46530. };
  46531. return DynamicTexture;
  46532. }(BABYLON.Texture));
  46533. BABYLON.DynamicTexture = DynamicTexture;
  46534. })(BABYLON || (BABYLON = {}));
  46535. //# sourceMappingURL=babylon.dynamicTexture.js.map
  46536. var BABYLON;
  46537. (function (BABYLON) {
  46538. var VideoTexture = (function (_super) {
  46539. __extends(VideoTexture, _super);
  46540. /**
  46541. * Creates a video texture.
  46542. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  46543. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  46544. * @param {BABYLON.Scene} scene is obviously the current scene.
  46545. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  46546. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  46547. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  46548. */
  46549. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  46550. if (generateMipMaps === void 0) { generateMipMaps = false; }
  46551. if (invertY === void 0) { invertY = false; }
  46552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46553. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46554. _this._autoLaunch = true;
  46555. var urls;
  46556. _this.name = name;
  46557. if (urlsOrVideo instanceof HTMLVideoElement) {
  46558. _this.video = urlsOrVideo;
  46559. }
  46560. else {
  46561. urls = urlsOrVideo;
  46562. _this.video = document.createElement("video");
  46563. _this.video.autoplay = false;
  46564. _this.video.loop = true;
  46565. }
  46566. _this._generateMipMaps = generateMipMaps;
  46567. _this._samplingMode = samplingMode;
  46568. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  46569. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46570. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46571. }
  46572. else {
  46573. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46574. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46575. _this._generateMipMaps = false;
  46576. }
  46577. if (urls) {
  46578. _this.video.addEventListener("canplay", function () {
  46579. _this._createTexture();
  46580. });
  46581. urls.forEach(function (url) {
  46582. var source = document.createElement("source");
  46583. source.src = url;
  46584. _this.video.appendChild(source);
  46585. });
  46586. }
  46587. else {
  46588. _this._createTexture();
  46589. }
  46590. _this._lastUpdate = BABYLON.Tools.Now;
  46591. return _this;
  46592. }
  46593. VideoTexture.prototype.__setTextureReady = function () {
  46594. this._texture.isReady = true;
  46595. };
  46596. VideoTexture.prototype._createTexture = function () {
  46597. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  46598. if (this._autoLaunch) {
  46599. this._autoLaunch = false;
  46600. this.video.play();
  46601. }
  46602. this._setTextureReady = this.__setTextureReady.bind(this);
  46603. this.video.addEventListener("playing", this._setTextureReady);
  46604. };
  46605. VideoTexture.prototype._rebuild = function () {
  46606. this.update();
  46607. };
  46608. VideoTexture.prototype.update = function () {
  46609. var now = BABYLON.Tools.Now;
  46610. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  46611. return false;
  46612. }
  46613. this._lastUpdate = now;
  46614. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  46615. return true;
  46616. };
  46617. VideoTexture.prototype.dispose = function () {
  46618. _super.prototype.dispose.call(this);
  46619. this.video.removeEventListener("playing", this._setTextureReady);
  46620. };
  46621. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  46622. var video = document.createElement("video");
  46623. var constraintsDeviceId;
  46624. if (constraints && constraints.deviceId) {
  46625. constraintsDeviceId = {
  46626. exact: constraints.deviceId
  46627. };
  46628. }
  46629. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  46630. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  46631. if (navigator.getUserMedia) {
  46632. navigator.getUserMedia({
  46633. video: {
  46634. deviceId: constraintsDeviceId,
  46635. width: {
  46636. min: (constraints && constraints.minWidth) || 256,
  46637. max: (constraints && constraints.maxWidth) || 640
  46638. },
  46639. height: {
  46640. min: (constraints && constraints.minHeight) || 256,
  46641. max: (constraints && constraints.maxHeight) || 480
  46642. }
  46643. }
  46644. }, function (stream) {
  46645. if (video.mozSrcObject !== undefined) {
  46646. video.mozSrcObject = stream;
  46647. }
  46648. else {
  46649. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  46650. }
  46651. video.play();
  46652. if (onReady) {
  46653. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  46654. }
  46655. }, function (e) {
  46656. BABYLON.Tools.Error(e.name);
  46657. });
  46658. }
  46659. };
  46660. return VideoTexture;
  46661. }(BABYLON.Texture));
  46662. BABYLON.VideoTexture = VideoTexture;
  46663. })(BABYLON || (BABYLON = {}));
  46664. //# sourceMappingURL=babylon.videoTexture.js.map
  46665. var BABYLON;
  46666. (function (BABYLON) {
  46667. var RawTexture = (function (_super) {
  46668. __extends(RawTexture, _super);
  46669. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  46670. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46671. if (invertY === void 0) { invertY = false; }
  46672. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46673. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46674. _this.format = format;
  46675. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  46676. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46677. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46678. return _this;
  46679. }
  46680. RawTexture.prototype.update = function (data) {
  46681. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  46682. };
  46683. // Statics
  46684. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46685. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46686. if (invertY === void 0) { invertY = false; }
  46687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46688. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  46689. };
  46690. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46691. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46692. if (invertY === void 0) { invertY = false; }
  46693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46694. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46695. };
  46696. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46697. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46698. if (invertY === void 0) { invertY = false; }
  46699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46700. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46701. };
  46702. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46703. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46704. if (invertY === void 0) { invertY = false; }
  46705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46706. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  46707. };
  46708. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46709. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46710. if (invertY === void 0) { invertY = false; }
  46711. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46712. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  46713. };
  46714. return RawTexture;
  46715. }(BABYLON.Texture));
  46716. BABYLON.RawTexture = RawTexture;
  46717. })(BABYLON || (BABYLON = {}));
  46718. //# sourceMappingURL=babylon.rawTexture.js.map
  46719. var BABYLON;
  46720. (function (BABYLON) {
  46721. var PostProcess = (function () {
  46722. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  46723. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  46724. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46725. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  46726. if (blockCompilation === void 0) { blockCompilation = false; }
  46727. this.name = name;
  46728. this.width = -1;
  46729. this.height = -1;
  46730. this.autoClear = true;
  46731. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  46732. /*
  46733. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  46734. Can only be used on a single postprocess or on the last one of a chain.
  46735. */
  46736. this.enablePixelPerfectMode = false;
  46737. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  46738. this.alwaysForcePOT = false;
  46739. this.samples = 1;
  46740. this.adaptScaleToCurrentViewport = false;
  46741. this._reusable = false;
  46742. this._textures = new BABYLON.SmartArray(2);
  46743. this._currentRenderTextureInd = 0;
  46744. this._scaleRatio = new BABYLON.Vector2(1, 1);
  46745. this._texelSize = BABYLON.Vector2.Zero();
  46746. // Events
  46747. /**
  46748. * An event triggered when the postprocess is activated.
  46749. * @type {BABYLON.Observable}
  46750. */
  46751. this.onActivateObservable = new BABYLON.Observable();
  46752. /**
  46753. * An event triggered when the postprocess changes its size.
  46754. * @type {BABYLON.Observable}
  46755. */
  46756. this.onSizeChangedObservable = new BABYLON.Observable();
  46757. /**
  46758. * An event triggered when the postprocess applies its effect.
  46759. * @type {BABYLON.Observable}
  46760. */
  46761. this.onApplyObservable = new BABYLON.Observable();
  46762. /**
  46763. * An event triggered before rendering the postprocess
  46764. * @type {BABYLON.Observable}
  46765. */
  46766. this.onBeforeRenderObservable = new BABYLON.Observable();
  46767. /**
  46768. * An event triggered after rendering the postprocess
  46769. * @type {BABYLON.Observable}
  46770. */
  46771. this.onAfterRenderObservable = new BABYLON.Observable();
  46772. if (camera != null) {
  46773. this._camera = camera;
  46774. this._scene = camera.getScene();
  46775. camera.attachPostProcess(this);
  46776. this._engine = this._scene.getEngine();
  46777. this._scene.postProcesses.push(this);
  46778. }
  46779. else {
  46780. this._engine = engine;
  46781. this._engine.postProcesses.push(this);
  46782. }
  46783. this._options = options;
  46784. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  46785. this._reusable = reusable || false;
  46786. this._textureType = textureType;
  46787. this._samplers = samplers || [];
  46788. this._samplers.push("textureSampler");
  46789. this._fragmentUrl = fragmentUrl;
  46790. this._vertexUrl = vertexUrl;
  46791. this._parameters = parameters || [];
  46792. this._parameters.push("scale");
  46793. this._indexParameters = indexParameters;
  46794. if (!blockCompilation) {
  46795. this.updateEffect(defines);
  46796. }
  46797. }
  46798. Object.defineProperty(PostProcess.prototype, "onActivate", {
  46799. set: function (callback) {
  46800. if (this._onActivateObserver) {
  46801. this.onActivateObservable.remove(this._onActivateObserver);
  46802. }
  46803. this._onActivateObserver = this.onActivateObservable.add(callback);
  46804. },
  46805. enumerable: true,
  46806. configurable: true
  46807. });
  46808. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  46809. set: function (callback) {
  46810. if (this._onSizeChangedObserver) {
  46811. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  46812. }
  46813. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  46814. },
  46815. enumerable: true,
  46816. configurable: true
  46817. });
  46818. Object.defineProperty(PostProcess.prototype, "onApply", {
  46819. set: function (callback) {
  46820. if (this._onApplyObserver) {
  46821. this.onApplyObservable.remove(this._onApplyObserver);
  46822. }
  46823. this._onApplyObserver = this.onApplyObservable.add(callback);
  46824. },
  46825. enumerable: true,
  46826. configurable: true
  46827. });
  46828. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  46829. set: function (callback) {
  46830. if (this._onBeforeRenderObserver) {
  46831. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  46832. }
  46833. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  46834. },
  46835. enumerable: true,
  46836. configurable: true
  46837. });
  46838. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  46839. set: function (callback) {
  46840. if (this._onAfterRenderObserver) {
  46841. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  46842. }
  46843. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  46844. },
  46845. enumerable: true,
  46846. configurable: true
  46847. });
  46848. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  46849. get: function () {
  46850. return this._textures.data[this._currentRenderTextureInd];
  46851. },
  46852. set: function (value) {
  46853. this._forcedOutputTexture = value;
  46854. },
  46855. enumerable: true,
  46856. configurable: true
  46857. });
  46858. PostProcess.prototype.getCamera = function () {
  46859. return this._camera;
  46860. };
  46861. Object.defineProperty(PostProcess.prototype, "texelSize", {
  46862. get: function () {
  46863. if (this._shareOutputWithPostProcess) {
  46864. return this._shareOutputWithPostProcess.texelSize;
  46865. }
  46866. if (this._forcedOutputTexture) {
  46867. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  46868. }
  46869. return this._texelSize;
  46870. },
  46871. enumerable: true,
  46872. configurable: true
  46873. });
  46874. PostProcess.prototype.getEngine = function () {
  46875. return this._engine;
  46876. };
  46877. PostProcess.prototype.getEffect = function () {
  46878. return this._effect;
  46879. };
  46880. PostProcess.prototype.shareOutputWith = function (postProcess) {
  46881. this._disposeTextures();
  46882. this._shareOutputWithPostProcess = postProcess;
  46883. return this;
  46884. };
  46885. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  46886. 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);
  46887. };
  46888. PostProcess.prototype.isReusable = function () {
  46889. return this._reusable;
  46890. };
  46891. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  46892. PostProcess.prototype.markTextureDirty = function () {
  46893. this.width = -1;
  46894. };
  46895. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  46896. var _this = this;
  46897. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  46898. camera = camera || this._camera;
  46899. var scene = camera.getScene();
  46900. var engine = scene.getEngine();
  46901. var maxSize = engine.getCaps().maxTextureSize;
  46902. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  46903. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  46904. var desiredWidth = (this._options.width || requiredWidth);
  46905. var desiredHeight = this._options.height || requiredHeight;
  46906. if (this.adaptScaleToCurrentViewport) {
  46907. var currentViewport = engine.currentViewport;
  46908. if (currentViewport) {
  46909. desiredWidth *= currentViewport.width;
  46910. desiredHeight *= currentViewport.height;
  46911. }
  46912. }
  46913. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  46914. if (!this._options.width) {
  46915. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  46916. }
  46917. if (!this._options.height) {
  46918. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  46919. }
  46920. }
  46921. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  46922. if (this._textures.length > 0) {
  46923. for (var i = 0; i < this._textures.length; i++) {
  46924. this._engine._releaseTexture(this._textures.data[i]);
  46925. }
  46926. this._textures.reset();
  46927. }
  46928. this.width = desiredWidth;
  46929. this.height = desiredHeight;
  46930. var textureSize = { width: this.width, height: this.height };
  46931. var textureOptions = {
  46932. generateMipMaps: false,
  46933. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  46934. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  46935. samplingMode: this.renderTargetSamplingMode,
  46936. type: this._textureType
  46937. };
  46938. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  46939. if (this._reusable) {
  46940. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  46941. }
  46942. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  46943. this.onSizeChangedObservable.notifyObservers(this);
  46944. }
  46945. this._textures.forEach(function (texture) {
  46946. if (texture.samples !== _this.samples) {
  46947. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  46948. }
  46949. });
  46950. }
  46951. var target;
  46952. if (this._shareOutputWithPostProcess) {
  46953. target = this._shareOutputWithPostProcess.outputTexture;
  46954. }
  46955. else if (this._forcedOutputTexture) {
  46956. target = this._forcedOutputTexture;
  46957. this.width = this._forcedOutputTexture.width;
  46958. this.height = this._forcedOutputTexture.height;
  46959. }
  46960. else {
  46961. target = this.outputTexture;
  46962. }
  46963. if (this.enablePixelPerfectMode) {
  46964. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  46965. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  46966. }
  46967. else {
  46968. this._scaleRatio.copyFromFloats(1, 1);
  46969. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  46970. }
  46971. this.onActivateObservable.notifyObservers(camera);
  46972. // Clear
  46973. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  46974. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  46975. }
  46976. if (this._reusable) {
  46977. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  46978. }
  46979. };
  46980. Object.defineProperty(PostProcess.prototype, "isSupported", {
  46981. get: function () {
  46982. return this._effect.isSupported;
  46983. },
  46984. enumerable: true,
  46985. configurable: true
  46986. });
  46987. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  46988. get: function () {
  46989. if (this._shareOutputWithPostProcess) {
  46990. return this._shareOutputWithPostProcess.aspectRatio;
  46991. }
  46992. if (this._forcedOutputTexture) {
  46993. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  46994. }
  46995. return this.width / this.height;
  46996. },
  46997. enumerable: true,
  46998. configurable: true
  46999. });
  47000. PostProcess.prototype.apply = function () {
  47001. // Check
  47002. if (!this._effect || !this._effect.isReady())
  47003. return null;
  47004. // States
  47005. this._engine.enableEffect(this._effect);
  47006. this._engine.setState(false);
  47007. this._engine.setDepthBuffer(false);
  47008. this._engine.setDepthWrite(false);
  47009. // Alpha
  47010. this._engine.setAlphaMode(this.alphaMode);
  47011. if (this.alphaConstants) {
  47012. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  47013. }
  47014. // Texture
  47015. var source;
  47016. if (this._shareOutputWithPostProcess) {
  47017. source = this._shareOutputWithPostProcess.outputTexture;
  47018. }
  47019. else if (this._forcedOutputTexture) {
  47020. source = this._forcedOutputTexture;
  47021. }
  47022. else {
  47023. source = this.outputTexture;
  47024. }
  47025. this._effect._bindTexture("textureSampler", source);
  47026. // Parameters
  47027. this._effect.setVector2("scale", this._scaleRatio);
  47028. this.onApplyObservable.notifyObservers(this._effect);
  47029. return this._effect;
  47030. };
  47031. PostProcess.prototype._disposeTextures = function () {
  47032. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  47033. return;
  47034. }
  47035. if (this._textures.length > 0) {
  47036. for (var i = 0; i < this._textures.length; i++) {
  47037. this._engine._releaseTexture(this._textures.data[i]);
  47038. }
  47039. }
  47040. this._textures.dispose();
  47041. };
  47042. PostProcess.prototype.dispose = function (camera) {
  47043. camera = camera || this._camera;
  47044. this._disposeTextures();
  47045. if (this._scene) {
  47046. var index_1 = this._scene.postProcesses.indexOf(this);
  47047. if (index_1 !== -1) {
  47048. this._scene.postProcesses.splice(index_1, 1);
  47049. }
  47050. }
  47051. else {
  47052. var index_2 = this._engine.postProcesses.indexOf(this);
  47053. if (index_2 !== -1) {
  47054. this._engine.postProcesses.splice(index_2, 1);
  47055. }
  47056. }
  47057. if (!camera) {
  47058. return;
  47059. }
  47060. camera.detachPostProcess(this);
  47061. var index = camera._postProcesses.indexOf(this);
  47062. if (index === 0 && camera._postProcesses.length > 0) {
  47063. this._camera._postProcesses[0].markTextureDirty();
  47064. }
  47065. this.onActivateObservable.clear();
  47066. this.onAfterRenderObservable.clear();
  47067. this.onApplyObservable.clear();
  47068. this.onBeforeRenderObservable.clear();
  47069. this.onSizeChangedObservable.clear();
  47070. };
  47071. return PostProcess;
  47072. }());
  47073. BABYLON.PostProcess = PostProcess;
  47074. })(BABYLON || (BABYLON = {}));
  47075. //# sourceMappingURL=babylon.postProcess.js.map
  47076. var BABYLON;
  47077. (function (BABYLON) {
  47078. var PassPostProcess = (function (_super) {
  47079. __extends(PassPostProcess, _super);
  47080. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  47081. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47082. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  47083. }
  47084. return PassPostProcess;
  47085. }(BABYLON.PostProcess));
  47086. BABYLON.PassPostProcess = PassPostProcess;
  47087. })(BABYLON || (BABYLON = {}));
  47088. //# sourceMappingURL=babylon.passPostProcess.js.map
  47089. var BABYLON;
  47090. (function (BABYLON) {
  47091. var ShadowGenerator = (function () {
  47092. /**
  47093. * Creates a ShadowGenerator object.
  47094. * A ShadowGenerator is the required tool to use the shadows.
  47095. * Each light casting shadows needs to use its own ShadowGenerator.
  47096. * Required parameters :
  47097. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  47098. * - `light`: the light object generating the shadows.
  47099. * - `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.
  47100. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  47101. */
  47102. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  47103. // Members
  47104. this._bias = 0.00005;
  47105. this._blurBoxOffset = 1;
  47106. this._blurScale = 2;
  47107. this._blurKernel = 1;
  47108. this._useKernelBlur = false;
  47109. this._filter = ShadowGenerator.FILTER_NONE;
  47110. this._darkness = 0;
  47111. this._transparencyShadow = false;
  47112. /**
  47113. * Controls the extent to which the shadows fade out at the edge of the frustum
  47114. * Used only by directionals and spots
  47115. */
  47116. this.frustumEdgeFalloff = 0;
  47117. this.forceBackFacesOnly = false;
  47118. this._lightDirection = BABYLON.Vector3.Zero();
  47119. this._viewMatrix = BABYLON.Matrix.Zero();
  47120. this._projectionMatrix = BABYLON.Matrix.Zero();
  47121. this._transformMatrix = BABYLON.Matrix.Zero();
  47122. this._worldViewProjection = BABYLON.Matrix.Zero();
  47123. this._currentFaceIndex = 0;
  47124. this._currentFaceIndexCache = 0;
  47125. this._isCube = false;
  47126. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  47127. this._mapSize = mapSize;
  47128. this._light = light;
  47129. this._scene = light.getScene();
  47130. light._shadowGenerator = this;
  47131. // Texture type fallback from float to int if not supported.
  47132. var caps = this._scene.getEngine().getCaps();
  47133. if (!useFullFloatFirst) {
  47134. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47135. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47136. }
  47137. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47138. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47139. }
  47140. else {
  47141. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47142. }
  47143. }
  47144. else {
  47145. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47146. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47147. }
  47148. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47149. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47150. }
  47151. else {
  47152. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47153. }
  47154. }
  47155. this._initializeGenerator();
  47156. }
  47157. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  47158. // Static
  47159. get: function () {
  47160. return ShadowGenerator._FILTER_NONE;
  47161. },
  47162. enumerable: true,
  47163. configurable: true
  47164. });
  47165. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  47166. get: function () {
  47167. return ShadowGenerator._FILTER_POISSONSAMPLING;
  47168. },
  47169. enumerable: true,
  47170. configurable: true
  47171. });
  47172. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  47173. get: function () {
  47174. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  47175. },
  47176. enumerable: true,
  47177. configurable: true
  47178. });
  47179. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  47180. get: function () {
  47181. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  47182. },
  47183. enumerable: true,
  47184. configurable: true
  47185. });
  47186. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  47187. get: function () {
  47188. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47189. },
  47190. enumerable: true,
  47191. configurable: true
  47192. });
  47193. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  47194. get: function () {
  47195. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47196. },
  47197. enumerable: true,
  47198. configurable: true
  47199. });
  47200. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  47201. get: function () {
  47202. return this._bias;
  47203. },
  47204. set: function (bias) {
  47205. this._bias = bias;
  47206. },
  47207. enumerable: true,
  47208. configurable: true
  47209. });
  47210. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  47211. get: function () {
  47212. return this._blurBoxOffset;
  47213. },
  47214. set: function (value) {
  47215. if (this._blurBoxOffset === value) {
  47216. return;
  47217. }
  47218. this._blurBoxOffset = value;
  47219. this._disposeBlurPostProcesses();
  47220. },
  47221. enumerable: true,
  47222. configurable: true
  47223. });
  47224. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  47225. get: function () {
  47226. return this._blurScale;
  47227. },
  47228. set: function (value) {
  47229. if (this._blurScale === value) {
  47230. return;
  47231. }
  47232. this._blurScale = value;
  47233. this._disposeBlurPostProcesses();
  47234. },
  47235. enumerable: true,
  47236. configurable: true
  47237. });
  47238. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  47239. get: function () {
  47240. return this._blurKernel;
  47241. },
  47242. set: function (value) {
  47243. if (this._blurKernel === value) {
  47244. return;
  47245. }
  47246. this._blurKernel = value;
  47247. this._disposeBlurPostProcesses();
  47248. },
  47249. enumerable: true,
  47250. configurable: true
  47251. });
  47252. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  47253. get: function () {
  47254. return this._useKernelBlur;
  47255. },
  47256. set: function (value) {
  47257. if (this._useKernelBlur === value) {
  47258. return;
  47259. }
  47260. this._useKernelBlur = value;
  47261. this._disposeBlurPostProcesses();
  47262. },
  47263. enumerable: true,
  47264. configurable: true
  47265. });
  47266. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  47267. get: function () {
  47268. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  47269. },
  47270. set: function (value) {
  47271. this._depthScale = value;
  47272. },
  47273. enumerable: true,
  47274. configurable: true
  47275. });
  47276. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  47277. get: function () {
  47278. return this._filter;
  47279. },
  47280. set: function (value) {
  47281. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  47282. if (this._light.needCube()) {
  47283. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47284. this.useExponentialShadowMap = true;
  47285. return;
  47286. }
  47287. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47288. this.useCloseExponentialShadowMap = true;
  47289. return;
  47290. }
  47291. }
  47292. if (this._filter === value) {
  47293. return;
  47294. }
  47295. this._filter = value;
  47296. this._disposeBlurPostProcesses();
  47297. this._applyFilterValues();
  47298. this._light._markMeshesAsLightDirty();
  47299. },
  47300. enumerable: true,
  47301. configurable: true
  47302. });
  47303. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  47304. get: function () {
  47305. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  47306. },
  47307. set: function (value) {
  47308. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  47309. return;
  47310. }
  47311. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  47312. },
  47313. enumerable: true,
  47314. configurable: true
  47315. });
  47316. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  47317. get: function () {
  47318. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47319. return this.useExponentialShadowMap;
  47320. },
  47321. set: function (value) {
  47322. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47323. this.useExponentialShadowMap = value;
  47324. },
  47325. enumerable: true,
  47326. configurable: true
  47327. });
  47328. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  47329. get: function () {
  47330. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47331. return this.useBlurExponentialShadowMap;
  47332. },
  47333. set: function (value) {
  47334. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47335. this.useBlurExponentialShadowMap = value;
  47336. },
  47337. enumerable: true,
  47338. configurable: true
  47339. });
  47340. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  47341. get: function () {
  47342. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  47343. },
  47344. set: function (value) {
  47345. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  47346. return;
  47347. }
  47348. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47349. },
  47350. enumerable: true,
  47351. configurable: true
  47352. });
  47353. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  47354. get: function () {
  47355. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  47356. },
  47357. set: function (value) {
  47358. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47359. return;
  47360. }
  47361. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47362. },
  47363. enumerable: true,
  47364. configurable: true
  47365. });
  47366. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  47367. get: function () {
  47368. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47369. },
  47370. set: function (value) {
  47371. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  47372. return;
  47373. }
  47374. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47375. },
  47376. enumerable: true,
  47377. configurable: true
  47378. });
  47379. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  47380. get: function () {
  47381. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47382. },
  47383. set: function (value) {
  47384. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47385. return;
  47386. }
  47387. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47388. },
  47389. enumerable: true,
  47390. configurable: true
  47391. });
  47392. /**
  47393. * Returns the darkness value (float).
  47394. */
  47395. ShadowGenerator.prototype.getDarkness = function () {
  47396. return this._darkness;
  47397. };
  47398. /**
  47399. * Sets the ShadowGenerator darkness value (float <= 1.0).
  47400. * Returns the ShadowGenerator.
  47401. */
  47402. ShadowGenerator.prototype.setDarkness = function (darkness) {
  47403. if (darkness >= 1.0)
  47404. this._darkness = 1.0;
  47405. else if (darkness <= 0.0)
  47406. this._darkness = 0.0;
  47407. else
  47408. this._darkness = darkness;
  47409. return this;
  47410. };
  47411. /**
  47412. * Sets the ability to have transparent shadow (boolean).
  47413. * Returns the ShadowGenerator.
  47414. */
  47415. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  47416. this._transparencyShadow = hasShadow;
  47417. return this;
  47418. };
  47419. /**
  47420. * Returns a RenderTargetTexture object : the shadow map texture.
  47421. */
  47422. ShadowGenerator.prototype.getShadowMap = function () {
  47423. return this._shadowMap;
  47424. };
  47425. /**
  47426. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  47427. */
  47428. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  47429. if (this._shadowMap2) {
  47430. return this._shadowMap2;
  47431. }
  47432. return this._shadowMap;
  47433. };
  47434. /**
  47435. * Returns the associated light object.
  47436. */
  47437. ShadowGenerator.prototype.getLight = function () {
  47438. return this._light;
  47439. };
  47440. ShadowGenerator.prototype._initializeGenerator = function () {
  47441. this._light._markMeshesAsLightDirty();
  47442. this._initializeShadowMap();
  47443. };
  47444. ShadowGenerator.prototype._initializeShadowMap = function () {
  47445. var _this = this;
  47446. // Render target
  47447. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  47448. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47449. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47450. this._shadowMap.anisotropicFilteringLevel = 1;
  47451. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47452. this._shadowMap.renderParticles = false;
  47453. // Record Face Index before render.
  47454. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  47455. _this._currentFaceIndex = faceIndex;
  47456. });
  47457. // Custom render function.
  47458. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  47459. // Blur if required afer render.
  47460. this._shadowMap.onAfterUnbindObservable.add(function () {
  47461. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  47462. return;
  47463. }
  47464. if (!_this._blurPostProcesses) {
  47465. _this._initializeBlurRTTAndPostProcesses();
  47466. }
  47467. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  47468. });
  47469. // Clear according to the chosen filter.
  47470. this._shadowMap.onClearObservable.add(function (engine) {
  47471. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  47472. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  47473. }
  47474. else {
  47475. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47476. }
  47477. });
  47478. };
  47479. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  47480. var _this = this;
  47481. var engine = this._scene.getEngine();
  47482. var targetSize = this._mapSize / this.blurScale;
  47483. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  47484. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  47485. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47486. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47487. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47488. }
  47489. if (this.useKernelBlur) {
  47490. 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);
  47491. this._kernelBlurXPostprocess.width = targetSize;
  47492. this._kernelBlurXPostprocess.height = targetSize;
  47493. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  47494. effect.setTexture("textureSampler", _this._shadowMap);
  47495. });
  47496. 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);
  47497. this._kernelBlurXPostprocess.autoClear = false;
  47498. this._kernelBlurYPostprocess.autoClear = false;
  47499. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47500. this._kernelBlurXPostprocess.packedFloat = true;
  47501. this._kernelBlurYPostprocess.packedFloat = true;
  47502. }
  47503. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  47504. }
  47505. else {
  47506. 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);
  47507. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  47508. effect.setFloat2("screenSize", targetSize, targetSize);
  47509. effect.setTexture("textureSampler", _this._shadowMap);
  47510. });
  47511. this._boxBlurPostprocess.autoClear = false;
  47512. this._blurPostProcesses = [this._boxBlurPostprocess];
  47513. }
  47514. };
  47515. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  47516. var index;
  47517. var engine = this._scene.getEngine();
  47518. if (depthOnlySubMeshes.length) {
  47519. engine.setColorWrite(false);
  47520. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  47521. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  47522. }
  47523. engine.setColorWrite(true);
  47524. }
  47525. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47526. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  47527. }
  47528. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47529. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  47530. }
  47531. if (this._transparencyShadow) {
  47532. for (index = 0; index < transparentSubMeshes.length; index++) {
  47533. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  47534. }
  47535. }
  47536. };
  47537. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  47538. var _this = this;
  47539. var mesh = subMesh.getRenderingMesh();
  47540. var scene = this._scene;
  47541. var engine = scene.getEngine();
  47542. // Culling
  47543. engine.setState(subMesh.getMaterial().backFaceCulling);
  47544. // Managing instances
  47545. var batch = mesh._getInstancesRenderList(subMesh._id);
  47546. if (batch.mustReturn) {
  47547. return;
  47548. }
  47549. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47550. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  47551. engine.enableEffect(this._effect);
  47552. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47553. var material = subMesh.getMaterial();
  47554. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  47555. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  47556. this._effect.setVector3("lightPosition", this.getLight().position);
  47557. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  47558. // Alpha test
  47559. if (material && material.needAlphaTesting()) {
  47560. var alphaTexture = material.getAlphaTestTexture();
  47561. if (alphaTexture) {
  47562. this._effect.setTexture("diffuseSampler", alphaTexture);
  47563. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  47564. }
  47565. }
  47566. // Bones
  47567. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47568. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47569. }
  47570. if (this.forceBackFacesOnly) {
  47571. engine.setState(true, 0, false, true);
  47572. }
  47573. // Draw
  47574. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47575. if (this.forceBackFacesOnly) {
  47576. engine.setState(true, 0, false, false);
  47577. }
  47578. }
  47579. else {
  47580. // Need to reset refresh rate of the shadowMap
  47581. this._shadowMap.resetRefreshCounter();
  47582. }
  47583. };
  47584. ShadowGenerator.prototype._applyFilterValues = function () {
  47585. if (this.filter === ShadowGenerator.FILTER_NONE) {
  47586. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  47587. }
  47588. else {
  47589. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47590. }
  47591. };
  47592. /**
  47593. * Force shader compilation including textures ready check
  47594. */
  47595. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  47596. var _this = this;
  47597. var scene = this._scene;
  47598. var engine = scene.getEngine();
  47599. var subMeshes = new Array();
  47600. var currentIndex = 0;
  47601. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  47602. var mesh = _a[_i];
  47603. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  47604. }
  47605. var checkReady = function () {
  47606. if (!_this._scene || !_this._scene.getEngine()) {
  47607. return;
  47608. }
  47609. var subMesh = subMeshes[currentIndex];
  47610. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  47611. currentIndex++;
  47612. if (currentIndex >= subMeshes.length) {
  47613. if (onCompiled) {
  47614. onCompiled(_this);
  47615. }
  47616. return;
  47617. }
  47618. }
  47619. setTimeout(checkReady, 16);
  47620. };
  47621. if (subMeshes.length > 0) {
  47622. checkReady();
  47623. }
  47624. };
  47625. /**
  47626. * Boolean : true when the ShadowGenerator is finally computed.
  47627. */
  47628. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  47629. var defines = [];
  47630. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47631. defines.push("#define FLOAT");
  47632. }
  47633. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47634. defines.push("#define ESM");
  47635. }
  47636. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47637. var mesh = subMesh.getMesh();
  47638. var material = subMesh.getMaterial();
  47639. // Alpha test
  47640. if (material && material.needAlphaTesting()) {
  47641. var alphaTexture = material.getAlphaTestTexture();
  47642. if (alphaTexture) {
  47643. defines.push("#define ALPHATEST");
  47644. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47645. attribs.push(BABYLON.VertexBuffer.UVKind);
  47646. defines.push("#define UV1");
  47647. }
  47648. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47649. if (alphaTexture.coordinatesIndex === 1) {
  47650. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47651. defines.push("#define UV2");
  47652. }
  47653. }
  47654. }
  47655. }
  47656. // Bones
  47657. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47658. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47659. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47660. if (mesh.numBoneInfluencers > 4) {
  47661. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47662. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47663. }
  47664. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47665. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47666. }
  47667. else {
  47668. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47669. }
  47670. // Instances
  47671. if (useInstances) {
  47672. defines.push("#define INSTANCES");
  47673. attribs.push("world0");
  47674. attribs.push("world1");
  47675. attribs.push("world2");
  47676. attribs.push("world3");
  47677. }
  47678. // Get correct effect
  47679. var join = defines.join("\n");
  47680. if (this._cachedDefines !== join) {
  47681. this._cachedDefines = join;
  47682. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  47683. }
  47684. return this._effect.isReady();
  47685. };
  47686. /**
  47687. * This creates the defines related to the standard BJS materials.
  47688. */
  47689. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  47690. var scene = this._scene;
  47691. var light = this._light;
  47692. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47693. return;
  47694. }
  47695. defines["SHADOW" + lightIndex] = true;
  47696. if (this.usePoissonSampling) {
  47697. defines["SHADOWPCF" + lightIndex] = true;
  47698. }
  47699. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47700. defines["SHADOWESM" + lightIndex] = true;
  47701. }
  47702. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  47703. defines["SHADOWCLOSEESM" + lightIndex] = true;
  47704. }
  47705. if (light.needCube()) {
  47706. defines["SHADOWCUBE" + lightIndex] = true;
  47707. }
  47708. };
  47709. /**
  47710. * This binds shadow lights related to the standard BJS materials.
  47711. * It implies the unifroms available on the materials are the standard BJS ones.
  47712. */
  47713. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  47714. var light = this._light;
  47715. var scene = this._scene;
  47716. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47717. return;
  47718. }
  47719. if (!light.needCube()) {
  47720. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  47721. }
  47722. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  47723. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  47724. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  47725. };
  47726. // Methods
  47727. /**
  47728. * Returns a Matrix object : the updated transformation matrix.
  47729. */
  47730. ShadowGenerator.prototype.getTransformMatrix = function () {
  47731. var scene = this._scene;
  47732. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  47733. return this._transformMatrix;
  47734. }
  47735. this._currentRenderID = scene.getRenderId();
  47736. this._currentFaceIndexCache = this._currentFaceIndex;
  47737. var lightPosition = this._light.position;
  47738. if (this._light.computeTransformedInformation()) {
  47739. lightPosition = this._light.transformedPosition;
  47740. }
  47741. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  47742. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  47743. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  47744. }
  47745. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  47746. this._cachedPosition = lightPosition.clone();
  47747. this._cachedDirection = this._lightDirection.clone();
  47748. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  47749. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  47750. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  47751. }
  47752. return this._transformMatrix;
  47753. };
  47754. ShadowGenerator.prototype.recreateShadowMap = function () {
  47755. // Track render list.
  47756. var renderList = this._shadowMap.renderList;
  47757. // Clean up existing data.
  47758. this._disposeRTTandPostProcesses();
  47759. // Reinitializes.
  47760. this._initializeGenerator();
  47761. // Reaffect the filter to ensure a correct fallback if necessary.
  47762. this.filter = this.filter;
  47763. // Reaffect the filter.
  47764. this._applyFilterValues();
  47765. // Reaffect Render List.
  47766. this._shadowMap.renderList = renderList;
  47767. };
  47768. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  47769. if (this._shadowMap2) {
  47770. this._shadowMap2.dispose();
  47771. this._shadowMap2 = null;
  47772. }
  47773. if (this._downSamplePostprocess) {
  47774. this._downSamplePostprocess.dispose();
  47775. this._downSamplePostprocess = null;
  47776. }
  47777. if (this._boxBlurPostprocess) {
  47778. this._boxBlurPostprocess.dispose();
  47779. this._boxBlurPostprocess = null;
  47780. }
  47781. if (this._kernelBlurXPostprocess) {
  47782. this._kernelBlurXPostprocess.dispose();
  47783. this._kernelBlurXPostprocess = null;
  47784. }
  47785. if (this._kernelBlurYPostprocess) {
  47786. this._kernelBlurYPostprocess.dispose();
  47787. this._kernelBlurYPostprocess = null;
  47788. }
  47789. this._blurPostProcesses = null;
  47790. };
  47791. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  47792. if (this._shadowMap) {
  47793. this._shadowMap.dispose();
  47794. this._shadowMap = null;
  47795. }
  47796. this._disposeBlurPostProcesses();
  47797. };
  47798. /**
  47799. * Disposes the ShadowGenerator.
  47800. * Returns nothing.
  47801. */
  47802. ShadowGenerator.prototype.dispose = function () {
  47803. this._disposeRTTandPostProcesses();
  47804. this._light._shadowGenerator = null;
  47805. this._light._markMeshesAsLightDirty();
  47806. };
  47807. /**
  47808. * Serializes the ShadowGenerator and returns a serializationObject.
  47809. */
  47810. ShadowGenerator.prototype.serialize = function () {
  47811. var serializationObject = {};
  47812. var shadowMap = this.getShadowMap();
  47813. serializationObject.lightId = this._light.id;
  47814. serializationObject.mapSize = shadowMap.getRenderSize();
  47815. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  47816. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  47817. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47818. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47819. serializationObject.usePoissonSampling = this.usePoissonSampling;
  47820. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  47821. serializationObject.depthScale = this.depthScale;
  47822. serializationObject.darkness = this.getDarkness();
  47823. serializationObject.blurBoxOffset = this.blurBoxOffset;
  47824. serializationObject.blurKernel = this.blurKernel;
  47825. serializationObject.blurScale = this.blurScale;
  47826. serializationObject.useKernelBlur = this.useKernelBlur;
  47827. serializationObject.transparencyShadow = this._transparencyShadow;
  47828. serializationObject.renderList = [];
  47829. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  47830. var mesh = shadowMap.renderList[meshIndex];
  47831. serializationObject.renderList.push(mesh.id);
  47832. }
  47833. return serializationObject;
  47834. };
  47835. /**
  47836. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  47837. */
  47838. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  47839. //casting to point light, as light is missing the position attr and typescript complains.
  47840. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  47841. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  47842. var shadowMap = shadowGenerator.getShadowMap();
  47843. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  47844. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  47845. meshes.forEach(function (mesh) {
  47846. shadowMap.renderList.push(mesh);
  47847. });
  47848. }
  47849. if (parsedShadowGenerator.usePoissonSampling) {
  47850. shadowGenerator.usePoissonSampling = true;
  47851. }
  47852. else if (parsedShadowGenerator.useExponentialShadowMap) {
  47853. shadowGenerator.useExponentialShadowMap = true;
  47854. }
  47855. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47856. shadowGenerator.useBlurExponentialShadowMap = true;
  47857. }
  47858. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  47859. shadowGenerator.useCloseExponentialShadowMap = true;
  47860. }
  47861. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47862. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  47863. }
  47864. else if (parsedShadowGenerator.useVarianceShadowMap) {
  47865. shadowGenerator.useExponentialShadowMap = true;
  47866. }
  47867. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  47868. shadowGenerator.useBlurExponentialShadowMap = true;
  47869. }
  47870. if (parsedShadowGenerator.depthScale) {
  47871. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  47872. }
  47873. if (parsedShadowGenerator.blurScale) {
  47874. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  47875. }
  47876. if (parsedShadowGenerator.blurBoxOffset) {
  47877. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  47878. }
  47879. if (parsedShadowGenerator.useKernelBlur) {
  47880. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  47881. }
  47882. if (parsedShadowGenerator.blurKernel) {
  47883. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  47884. }
  47885. if (parsedShadowGenerator.bias !== undefined) {
  47886. shadowGenerator.bias = parsedShadowGenerator.bias;
  47887. }
  47888. if (parsedShadowGenerator.darkness) {
  47889. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  47890. }
  47891. if (parsedShadowGenerator.transparencyShadow) {
  47892. shadowGenerator.setTransparencyShadow(true);
  47893. }
  47894. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  47895. return shadowGenerator;
  47896. };
  47897. ShadowGenerator._FILTER_NONE = 0;
  47898. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  47899. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  47900. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  47901. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  47902. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  47903. return ShadowGenerator;
  47904. }());
  47905. BABYLON.ShadowGenerator = ShadowGenerator;
  47906. })(BABYLON || (BABYLON = {}));
  47907. //# sourceMappingURL=babylon.shadowGenerator.js.map
  47908. var BABYLON;
  47909. (function (BABYLON) {
  47910. var DefaultLoadingScreen = (function () {
  47911. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  47912. if (_loadingText === void 0) { _loadingText = ""; }
  47913. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  47914. var _this = this;
  47915. this._renderingCanvas = _renderingCanvas;
  47916. this._loadingText = _loadingText;
  47917. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  47918. // Resize
  47919. this._resizeLoadingUI = function () {
  47920. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  47921. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  47922. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  47923. _this._loadingDiv.style.left = canvasRect.left + "px";
  47924. _this._loadingDiv.style.top = canvasRect.top + "px";
  47925. _this._loadingDiv.style.width = canvasRect.width + "px";
  47926. _this._loadingDiv.style.height = canvasRect.height + "px";
  47927. };
  47928. }
  47929. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  47930. if (this._loadingDiv) {
  47931. // Do not add a loading screen if there is already one
  47932. return;
  47933. }
  47934. this._loadingDiv = document.createElement("div");
  47935. this._loadingDiv.id = "babylonjsLoadingDiv";
  47936. this._loadingDiv.style.opacity = "0";
  47937. this._loadingDiv.style.transition = "opacity 1.5s ease";
  47938. // Loading text
  47939. this._loadingTextDiv = document.createElement("div");
  47940. this._loadingTextDiv.style.position = "absolute";
  47941. this._loadingTextDiv.style.left = "0";
  47942. this._loadingTextDiv.style.top = "50%";
  47943. this._loadingTextDiv.style.marginTop = "80px";
  47944. this._loadingTextDiv.style.width = "100%";
  47945. this._loadingTextDiv.style.height = "20px";
  47946. this._loadingTextDiv.style.fontFamily = "Arial";
  47947. this._loadingTextDiv.style.fontSize = "14px";
  47948. this._loadingTextDiv.style.color = "white";
  47949. this._loadingTextDiv.style.textAlign = "center";
  47950. this._loadingTextDiv.innerHTML = "Loading";
  47951. this._loadingDiv.appendChild(this._loadingTextDiv);
  47952. //set the predefined text
  47953. this._loadingTextDiv.innerHTML = this._loadingText;
  47954. // Generating keyframes
  47955. var style = document.createElement('style');
  47956. style.type = 'text/css';
  47957. 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 }";
  47958. style.innerHTML = keyFrames;
  47959. document.getElementsByTagName('head')[0].appendChild(style);
  47960. // Loading img
  47961. var imgBack = new Image();
  47962. 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";
  47963. imgBack.style.position = "absolute";
  47964. imgBack.style.left = "50%";
  47965. imgBack.style.top = "50%";
  47966. imgBack.style.marginLeft = "-60px";
  47967. imgBack.style.marginTop = "-60px";
  47968. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  47969. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  47970. imgBack.style.transformOrigin = "50% 50%";
  47971. imgBack.style.webkitTransformOrigin = "50% 50%";
  47972. this._loadingDiv.appendChild(imgBack);
  47973. this._resizeLoadingUI();
  47974. window.addEventListener("resize", this._resizeLoadingUI);
  47975. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47976. document.body.appendChild(this._loadingDiv);
  47977. this._loadingDiv.style.opacity = "1";
  47978. };
  47979. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  47980. var _this = this;
  47981. if (!this._loadingDiv) {
  47982. return;
  47983. }
  47984. var onTransitionEnd = function () {
  47985. if (!_this._loadingDiv) {
  47986. return;
  47987. }
  47988. document.body.removeChild(_this._loadingDiv);
  47989. window.removeEventListener("resize", _this._resizeLoadingUI);
  47990. _this._loadingDiv = null;
  47991. };
  47992. this._loadingDiv.style.opacity = "0";
  47993. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  47994. };
  47995. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  47996. set: function (text) {
  47997. this._loadingText = text;
  47998. if (this._loadingTextDiv) {
  47999. this._loadingTextDiv.innerHTML = this._loadingText;
  48000. }
  48001. },
  48002. enumerable: true,
  48003. configurable: true
  48004. });
  48005. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48006. get: function () {
  48007. return this._loadingDivBackgroundColor;
  48008. },
  48009. set: function (color) {
  48010. this._loadingDivBackgroundColor = color;
  48011. if (!this._loadingDiv) {
  48012. return;
  48013. }
  48014. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48015. },
  48016. enumerable: true,
  48017. configurable: true
  48018. });
  48019. return DefaultLoadingScreen;
  48020. }());
  48021. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48022. })(BABYLON || (BABYLON = {}));
  48023. //# sourceMappingURL=babylon.loadingScreen.js.map
  48024. var BABYLON;
  48025. (function (BABYLON) {
  48026. var SceneLoader = (function () {
  48027. function SceneLoader() {
  48028. }
  48029. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48030. get: function () {
  48031. return 0;
  48032. },
  48033. enumerable: true,
  48034. configurable: true
  48035. });
  48036. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48037. get: function () {
  48038. return 1;
  48039. },
  48040. enumerable: true,
  48041. configurable: true
  48042. });
  48043. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48044. get: function () {
  48045. return 2;
  48046. },
  48047. enumerable: true,
  48048. configurable: true
  48049. });
  48050. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48051. get: function () {
  48052. return 3;
  48053. },
  48054. enumerable: true,
  48055. configurable: true
  48056. });
  48057. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48058. get: function () {
  48059. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48060. },
  48061. set: function (value) {
  48062. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48063. },
  48064. enumerable: true,
  48065. configurable: true
  48066. });
  48067. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48068. get: function () {
  48069. return SceneLoader._ShowLoadingScreen;
  48070. },
  48071. set: function (value) {
  48072. SceneLoader._ShowLoadingScreen = value;
  48073. },
  48074. enumerable: true,
  48075. configurable: true
  48076. });
  48077. Object.defineProperty(SceneLoader, "loggingLevel", {
  48078. get: function () {
  48079. return SceneLoader._loggingLevel;
  48080. },
  48081. set: function (value) {
  48082. SceneLoader._loggingLevel = value;
  48083. },
  48084. enumerable: true,
  48085. configurable: true
  48086. });
  48087. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48088. get: function () {
  48089. return SceneLoader._CleanBoneMatrixWeights;
  48090. },
  48091. set: function (value) {
  48092. SceneLoader._CleanBoneMatrixWeights = value;
  48093. },
  48094. enumerable: true,
  48095. configurable: true
  48096. });
  48097. SceneLoader._getDefaultPlugin = function () {
  48098. return SceneLoader._registeredPlugins[".babylon"];
  48099. };
  48100. SceneLoader._getPluginForExtension = function (extension) {
  48101. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  48102. if (registeredPlugin) {
  48103. return registeredPlugin;
  48104. }
  48105. return SceneLoader._getDefaultPlugin();
  48106. };
  48107. SceneLoader._getPluginForDirectLoad = function (data) {
  48108. for (var extension in SceneLoader._registeredPlugins) {
  48109. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  48110. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  48111. return SceneLoader._registeredPlugins[extension];
  48112. }
  48113. }
  48114. return SceneLoader._getDefaultPlugin();
  48115. };
  48116. SceneLoader._getPluginForFilename = function (sceneFilename) {
  48117. if (sceneFilename.name) {
  48118. sceneFilename = sceneFilename.name;
  48119. }
  48120. var dotPosition = sceneFilename.lastIndexOf(".");
  48121. var queryStringPosition = sceneFilename.indexOf("?");
  48122. if (queryStringPosition === -1) {
  48123. queryStringPosition = sceneFilename.length;
  48124. }
  48125. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  48126. return SceneLoader._getPluginForExtension(extension);
  48127. };
  48128. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  48129. SceneLoader._getDirectLoad = function (sceneFilename) {
  48130. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  48131. return sceneFilename.substr(5);
  48132. }
  48133. return null;
  48134. };
  48135. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48136. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  48137. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  48138. var plugin = registeredPlugin.plugin;
  48139. var useArrayBuffer = registeredPlugin.isBinary;
  48140. var database;
  48141. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  48142. var dataCallback = function (data) {
  48143. if (scene.isDisposed) {
  48144. onError("Scene has been disposed");
  48145. return;
  48146. }
  48147. scene.database = database;
  48148. try {
  48149. onSuccess(plugin, data);
  48150. }
  48151. catch (e) {
  48152. onError(null, e);
  48153. }
  48154. };
  48155. var manifestChecked = function (success) {
  48156. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  48157. onError(request.status + " " + request.statusText);
  48158. });
  48159. };
  48160. if (directLoad) {
  48161. dataCallback(directLoad);
  48162. return;
  48163. }
  48164. if (rootUrl.indexOf("file:") === -1) {
  48165. if (scene.getEngine().enableOfflineSupport) {
  48166. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  48167. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  48168. }
  48169. else {
  48170. manifestChecked(true);
  48171. }
  48172. }
  48173. else {
  48174. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  48175. }
  48176. };
  48177. // Public functions
  48178. SceneLoader.GetPluginForExtension = function (extension) {
  48179. return SceneLoader._getPluginForExtension(extension).plugin;
  48180. };
  48181. SceneLoader.RegisterPlugin = function (plugin) {
  48182. if (typeof plugin.extensions === "string") {
  48183. var extension = plugin.extensions;
  48184. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48185. plugin: plugin,
  48186. isBinary: false
  48187. };
  48188. }
  48189. else {
  48190. var extensions = plugin.extensions;
  48191. Object.keys(extensions).forEach(function (extension) {
  48192. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48193. plugin: plugin,
  48194. isBinary: extensions[extension].isBinary
  48195. };
  48196. });
  48197. }
  48198. };
  48199. /**
  48200. * Import meshes into a scene
  48201. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  48202. * @param rootUrl a string that defines the root url for scene and resources
  48203. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48204. * @param scene the instance of BABYLON.Scene to append to
  48205. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  48206. * @param onProgress a callback with a progress event for each file being loaded
  48207. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48208. */
  48209. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48210. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48211. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48212. return;
  48213. }
  48214. var loadingToken = {};
  48215. scene._addPendingData(loadingToken);
  48216. var errorHandler = function (message, exception) {
  48217. if (onError) {
  48218. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48219. }
  48220. scene._removePendingData(loadingToken);
  48221. };
  48222. var progressHandler = function (event) {
  48223. if (onProgress) {
  48224. onProgress(event);
  48225. }
  48226. };
  48227. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48228. if (plugin.importMesh) {
  48229. var syncedPlugin = plugin;
  48230. var meshes = [];
  48231. var particleSystems = [];
  48232. var skeletons = [];
  48233. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  48234. return;
  48235. }
  48236. if (onSuccess) {
  48237. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48238. onSuccess(meshes, particleSystems, skeletons);
  48239. scene._removePendingData(loadingToken);
  48240. }
  48241. }
  48242. else {
  48243. var asyncedPlugin = plugin;
  48244. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  48245. if (onSuccess) {
  48246. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48247. onSuccess(meshes, particleSystems, skeletons);
  48248. scene._removePendingData(loadingToken);
  48249. }
  48250. }, progressHandler, errorHandler);
  48251. }
  48252. }, progressHandler, errorHandler);
  48253. };
  48254. /**
  48255. * Load a scene
  48256. * @param rootUrl a string that defines the root url for scene and resources
  48257. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48258. * @param engine is the instance of BABYLON.Engine to use to create the scene
  48259. * @param onSuccess a callback with the scene when import succeeds
  48260. * @param onProgress a callback with a progress event for each file being loaded
  48261. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48262. */
  48263. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  48264. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  48265. };
  48266. /**
  48267. * Append a scene
  48268. * @param rootUrl a string that defines the root url for scene and resources
  48269. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48270. * @param scene is the instance of BABYLON.Scene to append to
  48271. * @param onSuccess a callback with the scene when import succeeds
  48272. * @param onProgress a callback with a progress event for each file being loaded
  48273. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48274. */
  48275. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48276. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48277. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48278. return;
  48279. }
  48280. if (SceneLoader.ShowLoadingScreen) {
  48281. scene.getEngine().displayLoadingUI();
  48282. }
  48283. var loadingToken = {};
  48284. scene._addPendingData(loadingToken);
  48285. var errorHandler = function (message, exception) {
  48286. if (onError) {
  48287. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48288. }
  48289. scene._removePendingData(loadingToken);
  48290. scene.getEngine().hideLoadingUI();
  48291. };
  48292. var progressHandler = function (event) {
  48293. if (onProgress) {
  48294. onProgress(event);
  48295. }
  48296. };
  48297. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48298. if (plugin.load) {
  48299. var syncedPlugin = plugin;
  48300. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  48301. return;
  48302. }
  48303. if (onSuccess) {
  48304. onSuccess(scene);
  48305. }
  48306. scene.loadingPluginName = plugin.name;
  48307. scene._removePendingData(loadingToken);
  48308. }
  48309. else {
  48310. var asyncedPlugin = plugin;
  48311. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  48312. if (onSuccess) {
  48313. onSuccess(scene);
  48314. }
  48315. scene.loadingPluginName = plugin.name;
  48316. scene._removePendingData(loadingToken);
  48317. }, progressHandler, errorHandler);
  48318. }
  48319. if (SceneLoader.ShowLoadingScreen) {
  48320. scene.executeWhenReady(function () {
  48321. scene.getEngine().hideLoadingUI();
  48322. });
  48323. }
  48324. }, progressHandler, errorHandler);
  48325. };
  48326. // Flags
  48327. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  48328. SceneLoader._ShowLoadingScreen = true;
  48329. SceneLoader._CleanBoneMatrixWeights = false;
  48330. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  48331. // Members
  48332. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  48333. SceneLoader._registeredPlugins = {};
  48334. return SceneLoader;
  48335. }());
  48336. BABYLON.SceneLoader = SceneLoader;
  48337. ;
  48338. })(BABYLON || (BABYLON = {}));
  48339. //# sourceMappingURL=babylon.sceneLoader.js.map
  48340. var BABYLON;
  48341. (function (BABYLON) {
  48342. var Internals;
  48343. (function (Internals) {
  48344. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  48345. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48346. var parsedMaterial = parsedData.materials[index];
  48347. if (parsedMaterial.id === id) {
  48348. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48349. }
  48350. }
  48351. return null;
  48352. };
  48353. var isDescendantOf = function (mesh, names, hierarchyIds) {
  48354. for (var i in names) {
  48355. if (mesh.name === names[i]) {
  48356. hierarchyIds.push(mesh.id);
  48357. return true;
  48358. }
  48359. }
  48360. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  48361. hierarchyIds.push(mesh.id);
  48362. return true;
  48363. }
  48364. return false;
  48365. };
  48366. var logOperation = function (operation, producer) {
  48367. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  48368. };
  48369. BABYLON.SceneLoader.RegisterPlugin({
  48370. name: "babylon.js",
  48371. extensions: ".babylon",
  48372. canDirectLoad: function (data) {
  48373. if (data.indexOf("babylon") !== -1) {
  48374. return true;
  48375. }
  48376. return false;
  48377. },
  48378. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  48379. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48380. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48381. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48382. // and avoid problems with multiple concurrent .babylon loads.
  48383. var log = "importMesh has failed JSON parse";
  48384. try {
  48385. var parsedData = JSON.parse(data);
  48386. log = "";
  48387. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48388. if (!meshesNames) {
  48389. meshesNames = null;
  48390. }
  48391. else if (!Array.isArray(meshesNames)) {
  48392. meshesNames = [meshesNames];
  48393. }
  48394. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48395. var loadedSkeletonsIds = [];
  48396. var loadedMaterialsIds = [];
  48397. var hierarchyIds = [];
  48398. var index;
  48399. var cache;
  48400. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48401. var parsedMesh = parsedData.meshes[index];
  48402. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  48403. if (meshesNames !== null) {
  48404. // Remove found mesh name from list.
  48405. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  48406. }
  48407. //Geometry?
  48408. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  48409. //does the file contain geometries?
  48410. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  48411. //find the correct geometry and add it to the scene
  48412. var found = false;
  48413. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  48414. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  48415. return;
  48416. }
  48417. else {
  48418. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  48419. if (parsedGeometryData.id === parsedMesh.geometryId) {
  48420. switch (geometryType) {
  48421. case "boxes":
  48422. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  48423. break;
  48424. case "spheres":
  48425. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  48426. break;
  48427. case "cylinders":
  48428. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  48429. break;
  48430. case "toruses":
  48431. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  48432. break;
  48433. case "grounds":
  48434. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  48435. break;
  48436. case "planes":
  48437. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  48438. break;
  48439. case "torusKnots":
  48440. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  48441. break;
  48442. case "vertexData":
  48443. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  48444. break;
  48445. }
  48446. found = true;
  48447. }
  48448. });
  48449. }
  48450. });
  48451. if (found === false) {
  48452. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  48453. }
  48454. }
  48455. }
  48456. // Material ?
  48457. if (parsedMesh.materialId) {
  48458. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  48459. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48460. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  48461. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  48462. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  48463. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  48464. var subMatId = parsedMultiMaterial.materials[matIndex];
  48465. loadedMaterialsIds.push(subMatId);
  48466. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  48467. log += "\n\tMaterial " + mat.toString(fullDetails);
  48468. }
  48469. loadedMaterialsIds.push(parsedMultiMaterial.id);
  48470. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48471. materialFound = true;
  48472. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  48473. break;
  48474. }
  48475. }
  48476. }
  48477. if (materialFound === false) {
  48478. loadedMaterialsIds.push(parsedMesh.materialId);
  48479. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  48480. if (!mat) {
  48481. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  48482. }
  48483. else {
  48484. log += "\n\tMaterial " + mat.toString(fullDetails);
  48485. }
  48486. }
  48487. }
  48488. // Skeleton ?
  48489. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48490. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  48491. if (skeletonAlreadyLoaded === false) {
  48492. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  48493. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  48494. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  48495. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48496. skeletons.push(skeleton);
  48497. loadedSkeletonsIds.push(parsedSkeleton.id);
  48498. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  48499. }
  48500. }
  48501. }
  48502. }
  48503. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48504. meshes.push(mesh);
  48505. log += "\n\tMesh " + mesh.toString(fullDetails);
  48506. }
  48507. }
  48508. // Connecting parents
  48509. var currentMesh;
  48510. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48511. currentMesh = scene.meshes[index];
  48512. if (currentMesh._waitingParentId) {
  48513. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  48514. currentMesh._waitingParentId = undefined;
  48515. }
  48516. }
  48517. // freeze and compute world matrix application
  48518. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48519. currentMesh = scene.meshes[index];
  48520. if (currentMesh._waitingFreezeWorldMatrix) {
  48521. currentMesh.freezeWorldMatrix();
  48522. currentMesh._waitingFreezeWorldMatrix = undefined;
  48523. }
  48524. else {
  48525. currentMesh.computeWorldMatrix(true);
  48526. }
  48527. }
  48528. }
  48529. // Particles
  48530. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48531. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48532. var parsedParticleSystem = parsedData.particleSystems[index];
  48533. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  48534. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  48535. }
  48536. }
  48537. }
  48538. return true;
  48539. }
  48540. catch (err) {
  48541. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  48542. log = null;
  48543. throw err;
  48544. }
  48545. finally {
  48546. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48547. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48548. }
  48549. }
  48550. },
  48551. load: function (scene, data, rootUrl) {
  48552. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48553. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48554. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48555. // and avoid problems with multiple concurrent .babylon loads.
  48556. var log = "importScene has failed JSON parse";
  48557. try {
  48558. var parsedData = JSON.parse(data);
  48559. log = "";
  48560. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48561. // Scene
  48562. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  48563. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  48564. }
  48565. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  48566. scene.autoClear = parsedData.autoClear;
  48567. }
  48568. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  48569. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  48570. }
  48571. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  48572. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  48573. }
  48574. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  48575. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  48576. }
  48577. // Fog
  48578. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  48579. scene.fogMode = parsedData.fogMode;
  48580. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  48581. scene.fogStart = parsedData.fogStart;
  48582. scene.fogEnd = parsedData.fogEnd;
  48583. scene.fogDensity = parsedData.fogDensity;
  48584. log += "\tFog mode for scene: ";
  48585. switch (scene.fogMode) {
  48586. // getters not compiling, so using hardcoded
  48587. case 1:
  48588. log += "exp\n";
  48589. break;
  48590. case 2:
  48591. log += "exp2\n";
  48592. break;
  48593. case 3:
  48594. log += "linear\n";
  48595. break;
  48596. }
  48597. }
  48598. //Physics
  48599. if (parsedData.physicsEnabled) {
  48600. var physicsPlugin;
  48601. if (parsedData.physicsEngine === "cannon") {
  48602. physicsPlugin = new BABYLON.CannonJSPlugin();
  48603. }
  48604. else if (parsedData.physicsEngine === "oimo") {
  48605. physicsPlugin = new BABYLON.OimoJSPlugin();
  48606. }
  48607. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  48608. //else - default engine, which is currently oimo
  48609. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  48610. scene.enablePhysics(physicsGravity, physicsPlugin);
  48611. }
  48612. // Metadata
  48613. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  48614. scene.metadata = parsedData.metadata;
  48615. }
  48616. //collisions, if defined. otherwise, default is true
  48617. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  48618. scene.collisionsEnabled = parsedData.collisionsEnabled;
  48619. }
  48620. scene.workerCollisions = !!parsedData.workerCollisions;
  48621. var index;
  48622. var cache;
  48623. // Lights
  48624. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  48625. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  48626. var parsedLight = parsedData.lights[index];
  48627. var light = BABYLON.Light.Parse(parsedLight, scene);
  48628. log += (index === 0 ? "\n\tLights:" : "");
  48629. log += "\n\t\t" + light.toString(fullDetails);
  48630. }
  48631. }
  48632. // Animations
  48633. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  48634. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  48635. var parsedAnimation = parsedData.animations[index];
  48636. var animation = BABYLON.Animation.Parse(parsedAnimation);
  48637. scene.animations.push(animation);
  48638. log += (index === 0 ? "\n\tAnimations:" : "");
  48639. log += "\n\t\t" + animation.toString(fullDetails);
  48640. }
  48641. }
  48642. if (parsedData.autoAnimate) {
  48643. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  48644. }
  48645. // Materials
  48646. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  48647. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48648. var parsedMaterial = parsedData.materials[index];
  48649. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48650. log += (index === 0 ? "\n\tMaterials:" : "");
  48651. log += "\n\t\t" + mat.toString(fullDetails);
  48652. }
  48653. }
  48654. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48655. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  48656. var parsedMultiMaterial = parsedData.multiMaterials[index];
  48657. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48658. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  48659. log += "\n\t\t" + mmat.toString(fullDetails);
  48660. }
  48661. }
  48662. // Morph targets
  48663. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  48664. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  48665. var managerData = _a[_i];
  48666. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  48667. }
  48668. }
  48669. // Skeletons
  48670. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48671. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  48672. var parsedSkeleton = parsedData.skeletons[index];
  48673. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48674. log += (index === 0 ? "\n\tSkeletons:" : "");
  48675. log += "\n\t\t" + skeleton.toString(fullDetails);
  48676. }
  48677. }
  48678. // Geometries
  48679. var geometries = parsedData.geometries;
  48680. if (geometries !== undefined && geometries !== null) {
  48681. // Boxes
  48682. var boxes = geometries.boxes;
  48683. if (boxes !== undefined && boxes !== null) {
  48684. for (index = 0, cache = boxes.length; index < cache; index++) {
  48685. var parsedBox = boxes[index];
  48686. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  48687. }
  48688. }
  48689. // Spheres
  48690. var spheres = geometries.spheres;
  48691. if (spheres !== undefined && spheres !== null) {
  48692. for (index = 0, cache = spheres.length; index < cache; index++) {
  48693. var parsedSphere = spheres[index];
  48694. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  48695. }
  48696. }
  48697. // Cylinders
  48698. var cylinders = geometries.cylinders;
  48699. if (cylinders !== undefined && cylinders !== null) {
  48700. for (index = 0, cache = cylinders.length; index < cache; index++) {
  48701. var parsedCylinder = cylinders[index];
  48702. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  48703. }
  48704. }
  48705. // Toruses
  48706. var toruses = geometries.toruses;
  48707. if (toruses !== undefined && toruses !== null) {
  48708. for (index = 0, cache = toruses.length; index < cache; index++) {
  48709. var parsedTorus = toruses[index];
  48710. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  48711. }
  48712. }
  48713. // Grounds
  48714. var grounds = geometries.grounds;
  48715. if (grounds !== undefined && grounds !== null) {
  48716. for (index = 0, cache = grounds.length; index < cache; index++) {
  48717. var parsedGround = grounds[index];
  48718. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  48719. }
  48720. }
  48721. // Planes
  48722. var planes = geometries.planes;
  48723. if (planes !== undefined && planes !== null) {
  48724. for (index = 0, cache = planes.length; index < cache; index++) {
  48725. var parsedPlane = planes[index];
  48726. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  48727. }
  48728. }
  48729. // TorusKnots
  48730. var torusKnots = geometries.torusKnots;
  48731. if (torusKnots !== undefined && torusKnots !== null) {
  48732. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  48733. var parsedTorusKnot = torusKnots[index];
  48734. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  48735. }
  48736. }
  48737. // VertexData
  48738. var vertexData = geometries.vertexData;
  48739. if (vertexData !== undefined && vertexData !== null) {
  48740. for (index = 0, cache = vertexData.length; index < cache; index++) {
  48741. var parsedVertexData = vertexData[index];
  48742. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  48743. }
  48744. }
  48745. }
  48746. // Meshes
  48747. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48748. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48749. var parsedMesh = parsedData.meshes[index];
  48750. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48751. log += (index === 0 ? "\n\tMeshes:" : "");
  48752. log += "\n\t\t" + mesh.toString(fullDetails);
  48753. }
  48754. }
  48755. // Cameras
  48756. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  48757. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  48758. var parsedCamera = parsedData.cameras[index];
  48759. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  48760. log += (index === 0 ? "\n\tCameras:" : "");
  48761. log += "\n\t\t" + camera.toString(fullDetails);
  48762. }
  48763. }
  48764. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  48765. scene.setActiveCameraByID(parsedData.activeCameraID);
  48766. }
  48767. // Browsing all the graph to connect the dots
  48768. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  48769. var camera = scene.cameras[index];
  48770. if (camera._waitingParentId) {
  48771. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  48772. camera._waitingParentId = undefined;
  48773. }
  48774. }
  48775. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48776. var light = scene.lights[index];
  48777. if (light._waitingParentId) {
  48778. light.parent = scene.getLastEntryByID(light._waitingParentId);
  48779. light._waitingParentId = undefined;
  48780. }
  48781. }
  48782. // Sounds
  48783. var loadedSounds = [];
  48784. var loadedSound;
  48785. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  48786. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  48787. var parsedSound = parsedData.sounds[index];
  48788. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48789. if (!parsedSound.url)
  48790. parsedSound.url = parsedSound.name;
  48791. if (!loadedSounds[parsedSound.url]) {
  48792. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  48793. loadedSounds[parsedSound.url] = loadedSound;
  48794. }
  48795. else {
  48796. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  48797. }
  48798. }
  48799. else {
  48800. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  48801. }
  48802. }
  48803. }
  48804. loadedSounds = [];
  48805. // Connect parents & children and parse actions
  48806. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48807. var mesh = scene.meshes[index];
  48808. if (mesh._waitingParentId) {
  48809. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  48810. mesh._waitingParentId = undefined;
  48811. }
  48812. if (mesh._waitingActions) {
  48813. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  48814. mesh._waitingActions = undefined;
  48815. }
  48816. }
  48817. // freeze world matrix application
  48818. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48819. var currentMesh = scene.meshes[index];
  48820. if (currentMesh._waitingFreezeWorldMatrix) {
  48821. currentMesh.freezeWorldMatrix();
  48822. currentMesh._waitingFreezeWorldMatrix = undefined;
  48823. }
  48824. else {
  48825. currentMesh.computeWorldMatrix(true);
  48826. }
  48827. }
  48828. // Particles Systems
  48829. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48830. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48831. var parsedParticleSystem = parsedData.particleSystems[index];
  48832. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  48833. }
  48834. }
  48835. // Lens flares
  48836. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  48837. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  48838. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  48839. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  48840. }
  48841. }
  48842. // Shadows
  48843. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  48844. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  48845. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  48846. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  48847. }
  48848. }
  48849. // Lights exclusions / inclusions
  48850. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48851. var light = scene.lights[index];
  48852. // Excluded check
  48853. if (light._excludedMeshesIds.length > 0) {
  48854. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  48855. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  48856. if (excludedMesh) {
  48857. light.excludedMeshes.push(excludedMesh);
  48858. }
  48859. }
  48860. light._excludedMeshesIds = [];
  48861. }
  48862. // Included check
  48863. if (light._includedOnlyMeshesIds.length > 0) {
  48864. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  48865. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  48866. if (includedOnlyMesh) {
  48867. light.includedOnlyMeshes.push(includedOnlyMesh);
  48868. }
  48869. }
  48870. light._includedOnlyMeshesIds = [];
  48871. }
  48872. }
  48873. // Actions (scene)
  48874. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  48875. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  48876. }
  48877. // Finish
  48878. return true;
  48879. }
  48880. catch (err) {
  48881. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  48882. log = null;
  48883. throw err;
  48884. }
  48885. finally {
  48886. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48887. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48888. }
  48889. }
  48890. }
  48891. });
  48892. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48893. })(BABYLON || (BABYLON = {}));
  48894. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  48895. var BABYLON;
  48896. (function (BABYLON) {
  48897. var FilesInput = (function () {
  48898. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  48899. this._engine = engine;
  48900. this._currentScene = scene;
  48901. this._sceneLoadedCallback = sceneLoadedCallback;
  48902. this._progressCallback = progressCallback;
  48903. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  48904. this._textureLoadingCallback = textureLoadingCallback;
  48905. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  48906. this._onReloadCallback = onReloadCallback;
  48907. }
  48908. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  48909. var _this = this;
  48910. if (elementToMonitor) {
  48911. this._elementToMonitor = elementToMonitor;
  48912. this._dragEnterHandler = function (e) { _this.drag(e); };
  48913. this._dragOverHandler = function (e) { _this.drag(e); };
  48914. this._dropHandler = function (e) { _this.drop(e); };
  48915. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  48916. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  48917. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  48918. }
  48919. };
  48920. FilesInput.prototype.dispose = function () {
  48921. if (!this._elementToMonitor) {
  48922. return;
  48923. }
  48924. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  48925. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  48926. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  48927. };
  48928. FilesInput.prototype.renderFunction = function () {
  48929. if (this._additionalRenderLoopLogicCallback) {
  48930. this._additionalRenderLoopLogicCallback();
  48931. }
  48932. if (this._currentScene) {
  48933. if (this._textureLoadingCallback) {
  48934. var remaining = this._currentScene.getWaitingItemsCount();
  48935. if (remaining > 0) {
  48936. this._textureLoadingCallback(remaining);
  48937. }
  48938. }
  48939. this._currentScene.render();
  48940. }
  48941. };
  48942. FilesInput.prototype.drag = function (e) {
  48943. e.stopPropagation();
  48944. e.preventDefault();
  48945. };
  48946. FilesInput.prototype.drop = function (eventDrop) {
  48947. eventDrop.stopPropagation();
  48948. eventDrop.preventDefault();
  48949. this.loadFiles(eventDrop);
  48950. };
  48951. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  48952. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  48953. reader.readEntries(function (fileEntries) {
  48954. var remaining = fileEntries.length;
  48955. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  48956. var fileEntry = fileEntries_1[_i];
  48957. if (fileEntry.isFile) {
  48958. fileEntry.file(function (file) {
  48959. file.correctName = relativePath + file.name;
  48960. files.push(file);
  48961. remaining--;
  48962. if (remaining === 0) {
  48963. callback();
  48964. }
  48965. });
  48966. }
  48967. else {
  48968. remaining--;
  48969. if (remaining === 0) {
  48970. callback();
  48971. }
  48972. }
  48973. }
  48974. });
  48975. };
  48976. FilesInput.prototype._processFiles = function (files) {
  48977. for (var i = 0; i < files.length; i++) {
  48978. var name = files[i].correctName.toLowerCase();
  48979. var extension = name.split('.').pop();
  48980. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  48981. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  48982. this._sceneFileToLoad = files[i];
  48983. }
  48984. else {
  48985. FilesInput.FilesToLoad[name] = files[i];
  48986. }
  48987. }
  48988. if (this._onReloadCallback) {
  48989. this._onReloadCallback(this._sceneFileToLoad);
  48990. }
  48991. else {
  48992. this.reload();
  48993. }
  48994. };
  48995. FilesInput.prototype.loadFiles = function (event) {
  48996. var _this = this;
  48997. if (this._startingProcessingFilesCallback)
  48998. this._startingProcessingFilesCallback();
  48999. // Handling data transfer via drag'n'drop
  49000. if (event && event.dataTransfer && event.dataTransfer.files) {
  49001. this._filesToLoad = event.dataTransfer.files;
  49002. }
  49003. // Handling files from input files
  49004. if (event && event.target && event.target.files) {
  49005. this._filesToLoad = event.target.files;
  49006. }
  49007. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49008. var files_1 = [];
  49009. var folders = [];
  49010. var items = event.dataTransfer ? event.dataTransfer.items : null;
  49011. for (var i = 0; i < this._filesToLoad.length; i++) {
  49012. var fileToLoad = this._filesToLoad[i];
  49013. var name_1 = fileToLoad.name.toLowerCase();
  49014. var type = fileToLoad.type;
  49015. var entry = void 0;
  49016. fileToLoad.correctName = name_1;
  49017. if (items) {
  49018. var item = items[i];
  49019. if (item.getAsEntry) {
  49020. entry = item.getAsEntry();
  49021. }
  49022. else if (item.webkitGetAsEntry) {
  49023. entry = item.webkitGetAsEntry();
  49024. }
  49025. }
  49026. if (!entry) {
  49027. files_1.push(fileToLoad);
  49028. }
  49029. else {
  49030. if (entry.isDirectory) {
  49031. folders.push(entry);
  49032. }
  49033. else {
  49034. files_1.push(fileToLoad);
  49035. }
  49036. }
  49037. }
  49038. if (folders.length === 0) {
  49039. this._processFiles(files_1);
  49040. }
  49041. else {
  49042. var remaining = folders.length;
  49043. // Extract folder content
  49044. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49045. var folder = folders_1[_i];
  49046. this._handleFolderDrop(folder, files_1, function () {
  49047. remaining--;
  49048. if (remaining === 0) {
  49049. _this._processFiles(files_1);
  49050. }
  49051. });
  49052. }
  49053. }
  49054. }
  49055. };
  49056. FilesInput.prototype.reload = function () {
  49057. var _this = this;
  49058. // If a ".babylon" file has been provided
  49059. if (this._sceneFileToLoad) {
  49060. if (this._currentScene) {
  49061. if (BABYLON.Tools.errorsCount > 0) {
  49062. BABYLON.Tools.ClearLogCache();
  49063. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49064. }
  49065. this._engine.stopRenderLoop();
  49066. this._currentScene.dispose();
  49067. }
  49068. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49069. _this._currentScene = newScene;
  49070. if (_this._sceneLoadedCallback) {
  49071. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  49072. }
  49073. // Wait for textures and shaders to be ready
  49074. _this._currentScene.executeWhenReady(function () {
  49075. _this._engine.runRenderLoop(function () {
  49076. _this.renderFunction();
  49077. });
  49078. });
  49079. }, function (progress) {
  49080. if (_this._progressCallback) {
  49081. _this._progressCallback(progress);
  49082. }
  49083. });
  49084. }
  49085. else {
  49086. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49087. }
  49088. };
  49089. FilesInput.FilesToLoad = new Array();
  49090. return FilesInput;
  49091. }());
  49092. BABYLON.FilesInput = FilesInput;
  49093. })(BABYLON || (BABYLON = {}));
  49094. //# sourceMappingURL=babylon.filesInput.js.map
  49095. var BABYLON;
  49096. (function (BABYLON) {
  49097. /**
  49098. * This class implement a typical dictionary using a string as key and the generic type T as value.
  49099. * The underlying implementation relies on an associative array to ensure the best performances.
  49100. * The value can be anything including 'null' but except 'undefined'
  49101. */
  49102. var StringDictionary = (function () {
  49103. function StringDictionary() {
  49104. this._count = 0;
  49105. this._data = {};
  49106. }
  49107. /**
  49108. * This will clear this dictionary and copy the content from the 'source' one.
  49109. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  49110. * @param source the dictionary to take the content from and copy to this dictionary
  49111. */
  49112. StringDictionary.prototype.copyFrom = function (source) {
  49113. var _this = this;
  49114. this.clear();
  49115. source.forEach(function (t, v) { return _this.add(t, v); });
  49116. };
  49117. /**
  49118. * Get a value based from its key
  49119. * @param key the given key to get the matching value from
  49120. * @return the value if found, otherwise undefined is returned
  49121. */
  49122. StringDictionary.prototype.get = function (key) {
  49123. var val = this._data[key];
  49124. if (val !== undefined) {
  49125. return val;
  49126. }
  49127. return undefined;
  49128. };
  49129. /**
  49130. * Get a value from its key or add it if it doesn't exist.
  49131. * This method will ensure you that a given key/data will be present in the dictionary.
  49132. * @param key the given key to get the matching value from
  49133. * @param factory the factory that will create the value if the key is not present in the dictionary.
  49134. * The factory will only be invoked if there's no data for the given key.
  49135. * @return the value corresponding to the key.
  49136. */
  49137. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  49138. var val = this.get(key);
  49139. if (val !== undefined) {
  49140. return val;
  49141. }
  49142. val = factory(key);
  49143. if (val) {
  49144. this.add(key, val);
  49145. }
  49146. return val;
  49147. };
  49148. /**
  49149. * Get a value from its key if present in the dictionary otherwise add it
  49150. * @param key the key to get the value from
  49151. * @param val if there's no such key/value pair in the dictionary add it with this value
  49152. * @return the value corresponding to the key
  49153. */
  49154. StringDictionary.prototype.getOrAdd = function (key, val) {
  49155. var curVal = this.get(key);
  49156. if (curVal !== undefined) {
  49157. return curVal;
  49158. }
  49159. this.add(key, val);
  49160. return val;
  49161. };
  49162. /**
  49163. * Check if there's a given key in the dictionary
  49164. * @param key the key to check for
  49165. * @return true if the key is present, false otherwise
  49166. */
  49167. StringDictionary.prototype.contains = function (key) {
  49168. return this._data[key] !== undefined;
  49169. };
  49170. /**
  49171. * Add a new key and its corresponding value
  49172. * @param key the key to add
  49173. * @param value the value corresponding to the key
  49174. * @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
  49175. */
  49176. StringDictionary.prototype.add = function (key, value) {
  49177. if (this._data[key] !== undefined) {
  49178. return false;
  49179. }
  49180. this._data[key] = value;
  49181. ++this._count;
  49182. return true;
  49183. };
  49184. StringDictionary.prototype.set = function (key, value) {
  49185. if (this._data[key] === undefined) {
  49186. return false;
  49187. }
  49188. this._data[key] = value;
  49189. return true;
  49190. };
  49191. /**
  49192. * Get the element of the given key and remove it from the dictionary
  49193. * @param key
  49194. */
  49195. StringDictionary.prototype.getAndRemove = function (key) {
  49196. var val = this.get(key);
  49197. if (val !== undefined) {
  49198. delete this._data[key];
  49199. --this._count;
  49200. return val;
  49201. }
  49202. return null;
  49203. };
  49204. /**
  49205. * Remove a key/value from the dictionary.
  49206. * @param key the key to remove
  49207. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  49208. */
  49209. StringDictionary.prototype.remove = function (key) {
  49210. if (this.contains(key)) {
  49211. delete this._data[key];
  49212. --this._count;
  49213. return true;
  49214. }
  49215. return false;
  49216. };
  49217. /**
  49218. * Clear the whole content of the dictionary
  49219. */
  49220. StringDictionary.prototype.clear = function () {
  49221. this._data = {};
  49222. this._count = 0;
  49223. };
  49224. Object.defineProperty(StringDictionary.prototype, "count", {
  49225. get: function () {
  49226. return this._count;
  49227. },
  49228. enumerable: true,
  49229. configurable: true
  49230. });
  49231. /**
  49232. * Execute a callback on each key/val of the dictionary.
  49233. * Note that you can remove any element in this dictionary in the callback implementation
  49234. * @param callback the callback to execute on a given key/value pair
  49235. */
  49236. StringDictionary.prototype.forEach = function (callback) {
  49237. for (var cur in this._data) {
  49238. var val = this._data[cur];
  49239. callback(cur, val);
  49240. }
  49241. };
  49242. /**
  49243. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  49244. * If the callback returns null or undefined the method will iterate to the next key/value pair
  49245. * Note that you can remove any element in this dictionary in the callback implementation
  49246. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  49247. */
  49248. StringDictionary.prototype.first = function (callback) {
  49249. for (var cur in this._data) {
  49250. var val = this._data[cur];
  49251. var res = callback(cur, val);
  49252. if (res) {
  49253. return res;
  49254. }
  49255. }
  49256. return null;
  49257. };
  49258. return StringDictionary;
  49259. }());
  49260. BABYLON.StringDictionary = StringDictionary;
  49261. })(BABYLON || (BABYLON = {}));
  49262. //# sourceMappingURL=babylon.stringDictionary.js.map
  49263. var BABYLON;
  49264. (function (BABYLON) {
  49265. var Tags = (function () {
  49266. function Tags() {
  49267. }
  49268. Tags.EnableFor = function (obj) {
  49269. obj._tags = obj._tags || {};
  49270. obj.hasTags = function () {
  49271. return Tags.HasTags(obj);
  49272. };
  49273. obj.addTags = function (tagsString) {
  49274. return Tags.AddTagsTo(obj, tagsString);
  49275. };
  49276. obj.removeTags = function (tagsString) {
  49277. return Tags.RemoveTagsFrom(obj, tagsString);
  49278. };
  49279. obj.matchesTagsQuery = function (tagsQuery) {
  49280. return Tags.MatchesQuery(obj, tagsQuery);
  49281. };
  49282. };
  49283. Tags.DisableFor = function (obj) {
  49284. delete obj._tags;
  49285. delete obj.hasTags;
  49286. delete obj.addTags;
  49287. delete obj.removeTags;
  49288. delete obj.matchesTagsQuery;
  49289. };
  49290. Tags.HasTags = function (obj) {
  49291. if (!obj._tags) {
  49292. return false;
  49293. }
  49294. return !BABYLON.Tools.IsEmpty(obj._tags);
  49295. };
  49296. Tags.GetTags = function (obj, asString) {
  49297. if (asString === void 0) { asString = true; }
  49298. if (!obj._tags) {
  49299. return null;
  49300. }
  49301. if (asString) {
  49302. var tagsArray = [];
  49303. for (var tag in obj._tags) {
  49304. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  49305. tagsArray.push(tag);
  49306. }
  49307. }
  49308. return tagsArray.join(" ");
  49309. }
  49310. else {
  49311. return obj._tags;
  49312. }
  49313. };
  49314. // the tags 'true' and 'false' are reserved and cannot be used as tags
  49315. // a tag cannot start with '||', '&&', and '!'
  49316. // it cannot contain whitespaces
  49317. Tags.AddTagsTo = function (obj, tagsString) {
  49318. if (!tagsString) {
  49319. return;
  49320. }
  49321. if (typeof tagsString !== "string") {
  49322. return;
  49323. }
  49324. var tags = tagsString.split(" ");
  49325. tags.forEach(function (tag, index, array) {
  49326. Tags._AddTagTo(obj, tag);
  49327. });
  49328. };
  49329. Tags._AddTagTo = function (obj, tag) {
  49330. tag = tag.trim();
  49331. if (tag === "" || tag === "true" || tag === "false") {
  49332. return;
  49333. }
  49334. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  49335. return;
  49336. }
  49337. Tags.EnableFor(obj);
  49338. obj._tags[tag] = true;
  49339. };
  49340. Tags.RemoveTagsFrom = function (obj, tagsString) {
  49341. if (!Tags.HasTags(obj)) {
  49342. return;
  49343. }
  49344. var tags = tagsString.split(" ");
  49345. for (var t in tags) {
  49346. Tags._RemoveTagFrom(obj, tags[t]);
  49347. }
  49348. };
  49349. Tags._RemoveTagFrom = function (obj, tag) {
  49350. delete obj._tags[tag];
  49351. };
  49352. Tags.MatchesQuery = function (obj, tagsQuery) {
  49353. if (tagsQuery === undefined) {
  49354. return true;
  49355. }
  49356. if (tagsQuery === "") {
  49357. return Tags.HasTags(obj);
  49358. }
  49359. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  49360. };
  49361. return Tags;
  49362. }());
  49363. BABYLON.Tags = Tags;
  49364. })(BABYLON || (BABYLON = {}));
  49365. //# sourceMappingURL=babylon.tags.js.map
  49366. var BABYLON;
  49367. (function (BABYLON) {
  49368. var Internals;
  49369. (function (Internals) {
  49370. var AndOrNotEvaluator = (function () {
  49371. function AndOrNotEvaluator() {
  49372. }
  49373. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  49374. if (!query.match(/\([^\(\)]*\)/g)) {
  49375. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  49376. }
  49377. else {
  49378. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  49379. // remove parenthesis
  49380. r = r.slice(1, r.length - 1);
  49381. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  49382. });
  49383. }
  49384. if (query === "true") {
  49385. return true;
  49386. }
  49387. if (query === "false") {
  49388. return false;
  49389. }
  49390. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  49391. };
  49392. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  49393. evaluateCallback = evaluateCallback || (function (r) {
  49394. return r === "true" ? true : false;
  49395. });
  49396. var result;
  49397. var or = parenthesisContent.split("||");
  49398. for (var i in or) {
  49399. if (or.hasOwnProperty(i)) {
  49400. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  49401. var and = ori.split("&&");
  49402. if (and.length > 1) {
  49403. for (var j = 0; j < and.length; ++j) {
  49404. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  49405. if (andj !== "true" && andj !== "false") {
  49406. if (andj[0] === "!") {
  49407. result = !evaluateCallback(andj.substring(1));
  49408. }
  49409. else {
  49410. result = evaluateCallback(andj);
  49411. }
  49412. }
  49413. else {
  49414. result = andj === "true" ? true : false;
  49415. }
  49416. if (!result) {
  49417. ori = "false";
  49418. break;
  49419. }
  49420. }
  49421. }
  49422. if (result || ori === "true") {
  49423. result = true;
  49424. break;
  49425. }
  49426. // result equals false (or undefined)
  49427. if (ori !== "true" && ori !== "false") {
  49428. if (ori[0] === "!") {
  49429. result = !evaluateCallback(ori.substring(1));
  49430. }
  49431. else {
  49432. result = evaluateCallback(ori);
  49433. }
  49434. }
  49435. else {
  49436. result = ori === "true" ? true : false;
  49437. }
  49438. }
  49439. }
  49440. // the whole parenthesis scope is replaced by 'true' or 'false'
  49441. return result ? "true" : "false";
  49442. };
  49443. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  49444. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  49445. // remove whitespaces
  49446. r = r.replace(/[\s]/g, function () { return ""; });
  49447. return r.length % 2 ? "!" : "";
  49448. });
  49449. booleanString = booleanString.trim();
  49450. if (booleanString === "!true") {
  49451. booleanString = "false";
  49452. }
  49453. else if (booleanString === "!false") {
  49454. booleanString = "true";
  49455. }
  49456. return booleanString;
  49457. };
  49458. return AndOrNotEvaluator;
  49459. }());
  49460. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  49461. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49462. })(BABYLON || (BABYLON = {}));
  49463. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  49464. var BABYLON;
  49465. (function (BABYLON) {
  49466. var Database = (function () {
  49467. function Database(urlToScene, callbackManifestChecked) {
  49468. // Handling various flavors of prefixed version of IndexedDB
  49469. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  49470. this.callbackManifestChecked = callbackManifestChecked;
  49471. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  49472. this.db = null;
  49473. this.enableSceneOffline = false;
  49474. this.enableTexturesOffline = false;
  49475. this.manifestVersionFound = 0;
  49476. this.mustUpdateRessources = false;
  49477. this.hasReachedQuota = false;
  49478. if (!Database.IDBStorageEnabled) {
  49479. this.callbackManifestChecked(true);
  49480. }
  49481. else {
  49482. this.checkManifestFile();
  49483. }
  49484. }
  49485. Database.prototype.checkManifestFile = function () {
  49486. var _this = this;
  49487. function noManifestFile() {
  49488. that.enableSceneOffline = false;
  49489. that.enableTexturesOffline = false;
  49490. that.callbackManifestChecked(false);
  49491. }
  49492. var that = this;
  49493. var timeStampUsed = false;
  49494. var manifestURL = this.currentSceneUrl + ".manifest";
  49495. var xhr = new XMLHttpRequest();
  49496. if (navigator.onLine) {
  49497. // Adding a timestamp to by-pass browsers' cache
  49498. timeStampUsed = true;
  49499. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  49500. }
  49501. xhr.open("GET", manifestURL, true);
  49502. xhr.addEventListener("load", function () {
  49503. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  49504. try {
  49505. var manifestFile = JSON.parse(xhr.response);
  49506. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  49507. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  49508. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  49509. _this.manifestVersionFound = manifestFile.version;
  49510. }
  49511. if (_this.callbackManifestChecked) {
  49512. _this.callbackManifestChecked(true);
  49513. }
  49514. }
  49515. catch (ex) {
  49516. noManifestFile();
  49517. }
  49518. }
  49519. else {
  49520. noManifestFile();
  49521. }
  49522. }, false);
  49523. xhr.addEventListener("error", function (event) {
  49524. if (timeStampUsed) {
  49525. timeStampUsed = false;
  49526. // Let's retry without the timeStamp
  49527. // It could fail when coupled with HTML5 Offline API
  49528. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  49529. xhr.open("GET", retryManifestURL, true);
  49530. xhr.send();
  49531. }
  49532. else {
  49533. noManifestFile();
  49534. }
  49535. }, false);
  49536. try {
  49537. xhr.send();
  49538. }
  49539. catch (ex) {
  49540. BABYLON.Tools.Error("Error on XHR send request.");
  49541. that.callbackManifestChecked(false);
  49542. }
  49543. };
  49544. Database.prototype.openAsync = function (successCallback, errorCallback) {
  49545. var _this = this;
  49546. function handleError() {
  49547. that.isSupported = false;
  49548. if (errorCallback)
  49549. errorCallback();
  49550. }
  49551. var that = this;
  49552. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  49553. // Your browser doesn't support IndexedDB
  49554. this.isSupported = false;
  49555. if (errorCallback)
  49556. errorCallback();
  49557. }
  49558. else {
  49559. // If the DB hasn't been opened or created yet
  49560. if (!this.db) {
  49561. this.hasReachedQuota = false;
  49562. this.isSupported = true;
  49563. var request = this.idbFactory.open("babylonjs", 1);
  49564. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  49565. request.onerror = function (event) {
  49566. handleError();
  49567. };
  49568. // executes when a version change transaction cannot complete due to other active transactions
  49569. request.onblocked = function (event) {
  49570. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  49571. handleError();
  49572. };
  49573. // DB has been opened successfully
  49574. request.onsuccess = function (event) {
  49575. _this.db = request.result;
  49576. successCallback();
  49577. };
  49578. // Initialization of the DB. Creating Scenes & Textures stores
  49579. request.onupgradeneeded = function (event) {
  49580. _this.db = (event.target).result;
  49581. try {
  49582. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  49583. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  49584. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  49585. }
  49586. catch (ex) {
  49587. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  49588. handleError();
  49589. }
  49590. };
  49591. }
  49592. else {
  49593. if (successCallback)
  49594. successCallback();
  49595. }
  49596. }
  49597. };
  49598. Database.prototype.loadImageFromDB = function (url, image) {
  49599. var _this = this;
  49600. var completeURL = Database.ReturnFullUrlLocation(url);
  49601. var saveAndLoadImage = function () {
  49602. if (!_this.hasReachedQuota && _this.db !== null) {
  49603. // the texture is not yet in the DB, let's try to save it
  49604. _this._saveImageIntoDBAsync(completeURL, image);
  49605. }
  49606. else {
  49607. image.src = url;
  49608. }
  49609. };
  49610. if (!this.mustUpdateRessources) {
  49611. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  49612. }
  49613. else {
  49614. saveAndLoadImage();
  49615. }
  49616. };
  49617. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  49618. if (this.isSupported && this.db !== null) {
  49619. var texture;
  49620. var transaction = this.db.transaction(["textures"]);
  49621. transaction.onabort = function (event) {
  49622. image.src = url;
  49623. };
  49624. transaction.oncomplete = function (event) {
  49625. var blobTextureURL;
  49626. if (texture) {
  49627. var URL = window.URL || window.webkitURL;
  49628. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  49629. image.onerror = function () {
  49630. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  49631. image.src = url;
  49632. };
  49633. image.src = blobTextureURL;
  49634. }
  49635. else {
  49636. notInDBCallback();
  49637. }
  49638. };
  49639. var getRequest = transaction.objectStore("textures").get(url);
  49640. getRequest.onsuccess = function (event) {
  49641. texture = (event.target).result;
  49642. };
  49643. getRequest.onerror = function (event) {
  49644. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  49645. image.src = url;
  49646. };
  49647. }
  49648. else {
  49649. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49650. image.src = url;
  49651. }
  49652. };
  49653. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  49654. var _this = this;
  49655. if (this.isSupported) {
  49656. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  49657. var generateBlobUrl = function () {
  49658. var blobTextureURL;
  49659. if (blob) {
  49660. var URL = window.URL || window.webkitURL;
  49661. try {
  49662. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  49663. }
  49664. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  49665. catch (ex) {
  49666. blobTextureURL = URL.createObjectURL(blob);
  49667. }
  49668. }
  49669. image.src = blobTextureURL;
  49670. };
  49671. if (Database.IsUASupportingBlobStorage) {
  49672. var xhr = new XMLHttpRequest(), blob;
  49673. xhr.open("GET", url, true);
  49674. xhr.responseType = "blob";
  49675. xhr.addEventListener("load", function () {
  49676. if (xhr.status === 200) {
  49677. // Blob as response (XHR2)
  49678. blob = xhr.response;
  49679. var transaction = _this.db.transaction(["textures"], "readwrite");
  49680. // the transaction could abort because of a QuotaExceededError error
  49681. transaction.onabort = function (event) {
  49682. try {
  49683. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49684. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49685. _this.hasReachedQuota = true;
  49686. }
  49687. }
  49688. catch (ex) { }
  49689. generateBlobUrl();
  49690. };
  49691. transaction.oncomplete = function (event) {
  49692. generateBlobUrl();
  49693. };
  49694. var newTexture = { textureUrl: url, data: blob };
  49695. try {
  49696. // Put the blob into the dabase
  49697. var addRequest = transaction.objectStore("textures").put(newTexture);
  49698. addRequest.onsuccess = function (event) {
  49699. };
  49700. addRequest.onerror = function (event) {
  49701. generateBlobUrl();
  49702. };
  49703. }
  49704. catch (ex) {
  49705. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  49706. if (ex.code === 25) {
  49707. Database.IsUASupportingBlobStorage = false;
  49708. }
  49709. image.src = url;
  49710. }
  49711. }
  49712. else {
  49713. image.src = url;
  49714. }
  49715. }, false);
  49716. xhr.addEventListener("error", function (event) {
  49717. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  49718. image.src = url;
  49719. }, false);
  49720. xhr.send();
  49721. }
  49722. else {
  49723. image.src = url;
  49724. }
  49725. }
  49726. else {
  49727. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49728. image.src = url;
  49729. }
  49730. };
  49731. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  49732. var _this = this;
  49733. var updateVersion = function (event) {
  49734. // the version is not yet in the DB or we need to update it
  49735. _this._saveVersionIntoDBAsync(url, versionLoaded);
  49736. };
  49737. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  49738. };
  49739. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  49740. var _this = this;
  49741. if (this.isSupported) {
  49742. var version;
  49743. try {
  49744. var transaction = this.db.transaction(["versions"]);
  49745. transaction.oncomplete = function (event) {
  49746. if (version) {
  49747. // If the version in the JSON file is > than the version in DB
  49748. if (_this.manifestVersionFound > version.data) {
  49749. _this.mustUpdateRessources = true;
  49750. updateInDBCallback();
  49751. }
  49752. else {
  49753. callback(version.data);
  49754. }
  49755. }
  49756. else {
  49757. _this.mustUpdateRessources = true;
  49758. updateInDBCallback();
  49759. }
  49760. };
  49761. transaction.onabort = function (event) {
  49762. callback(-1);
  49763. };
  49764. var getRequest = transaction.objectStore("versions").get(url);
  49765. getRequest.onsuccess = function (event) {
  49766. version = (event.target).result;
  49767. };
  49768. getRequest.onerror = function (event) {
  49769. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  49770. callback(-1);
  49771. };
  49772. }
  49773. catch (ex) {
  49774. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  49775. callback(-1);
  49776. }
  49777. }
  49778. else {
  49779. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49780. callback(-1);
  49781. }
  49782. };
  49783. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  49784. var _this = this;
  49785. if (this.isSupported && !this.hasReachedQuota) {
  49786. try {
  49787. // Open a transaction to the database
  49788. var transaction = this.db.transaction(["versions"], "readwrite");
  49789. // the transaction could abort because of a QuotaExceededError error
  49790. transaction.onabort = function (event) {
  49791. try {
  49792. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49793. _this.hasReachedQuota = true;
  49794. }
  49795. }
  49796. catch (ex) { }
  49797. callback(-1);
  49798. };
  49799. transaction.oncomplete = function (event) {
  49800. callback(_this.manifestVersionFound);
  49801. };
  49802. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  49803. // Put the scene into the database
  49804. var addRequest = transaction.objectStore("versions").put(newVersion);
  49805. addRequest.onsuccess = function (event) {
  49806. };
  49807. addRequest.onerror = function (event) {
  49808. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  49809. };
  49810. }
  49811. catch (ex) {
  49812. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  49813. callback(-1);
  49814. }
  49815. }
  49816. else {
  49817. callback(-1);
  49818. }
  49819. };
  49820. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  49821. var _this = this;
  49822. var completeUrl = Database.ReturnFullUrlLocation(url);
  49823. var saveAndLoadFile = function (event) {
  49824. // the scene is not yet in the DB, let's try to save it
  49825. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  49826. };
  49827. this._checkVersionFromDB(completeUrl, function (version) {
  49828. if (version !== -1) {
  49829. if (!_this.mustUpdateRessources) {
  49830. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  49831. }
  49832. else {
  49833. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  49834. }
  49835. }
  49836. else {
  49837. errorCallback();
  49838. }
  49839. });
  49840. };
  49841. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  49842. if (this.isSupported) {
  49843. var targetStore;
  49844. if (url.indexOf(".babylon") !== -1) {
  49845. targetStore = "scenes";
  49846. }
  49847. else {
  49848. targetStore = "textures";
  49849. }
  49850. var file;
  49851. var transaction = this.db.transaction([targetStore]);
  49852. transaction.oncomplete = function (event) {
  49853. if (file) {
  49854. callback(file.data);
  49855. }
  49856. else {
  49857. notInDBCallback();
  49858. }
  49859. };
  49860. transaction.onabort = function (event) {
  49861. notInDBCallback();
  49862. };
  49863. var getRequest = transaction.objectStore(targetStore).get(url);
  49864. getRequest.onsuccess = function (event) {
  49865. file = (event.target).result;
  49866. };
  49867. getRequest.onerror = function (event) {
  49868. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  49869. notInDBCallback();
  49870. };
  49871. }
  49872. else {
  49873. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49874. callback();
  49875. }
  49876. };
  49877. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  49878. var _this = this;
  49879. if (this.isSupported) {
  49880. var targetStore;
  49881. if (url.indexOf(".babylon") !== -1) {
  49882. targetStore = "scenes";
  49883. }
  49884. else {
  49885. targetStore = "textures";
  49886. }
  49887. // Create XHR
  49888. var xhr = new XMLHttpRequest(), fileData;
  49889. xhr.open("GET", url, true);
  49890. if (useArrayBuffer) {
  49891. xhr.responseType = "arraybuffer";
  49892. }
  49893. xhr.onprogress = progressCallback;
  49894. xhr.addEventListener("load", function () {
  49895. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  49896. // Blob as response (XHR2)
  49897. //fileData = xhr.responseText;
  49898. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  49899. if (!_this.hasReachedQuota) {
  49900. // Open a transaction to the database
  49901. var transaction = _this.db.transaction([targetStore], "readwrite");
  49902. // the transaction could abort because of a QuotaExceededError error
  49903. transaction.onabort = function (event) {
  49904. try {
  49905. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49906. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49907. _this.hasReachedQuota = true;
  49908. }
  49909. }
  49910. catch (ex) { }
  49911. callback(fileData);
  49912. };
  49913. transaction.oncomplete = function (event) {
  49914. callback(fileData);
  49915. };
  49916. var newFile;
  49917. if (targetStore === "scenes") {
  49918. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  49919. }
  49920. else {
  49921. newFile = { textureUrl: url, data: fileData };
  49922. }
  49923. try {
  49924. // Put the scene into the database
  49925. var addRequest = transaction.objectStore(targetStore).put(newFile);
  49926. addRequest.onsuccess = function (event) {
  49927. };
  49928. addRequest.onerror = function (event) {
  49929. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  49930. };
  49931. }
  49932. catch (ex) {
  49933. callback(fileData);
  49934. }
  49935. }
  49936. else {
  49937. callback(fileData);
  49938. }
  49939. }
  49940. else {
  49941. callback();
  49942. }
  49943. }, false);
  49944. xhr.addEventListener("error", function (event) {
  49945. BABYLON.Tools.Error("error on XHR request.");
  49946. callback();
  49947. }, false);
  49948. xhr.send();
  49949. }
  49950. else {
  49951. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49952. callback();
  49953. }
  49954. };
  49955. Database.IsUASupportingBlobStorage = true;
  49956. Database.IDBStorageEnabled = true;
  49957. Database.parseURL = function (url) {
  49958. var a = document.createElement('a');
  49959. a.href = url;
  49960. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  49961. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  49962. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  49963. return absLocation;
  49964. };
  49965. Database.ReturnFullUrlLocation = function (url) {
  49966. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  49967. return (Database.parseURL(window.location.href) + url);
  49968. }
  49969. else {
  49970. return url;
  49971. }
  49972. };
  49973. return Database;
  49974. }());
  49975. BABYLON.Database = Database;
  49976. })(BABYLON || (BABYLON = {}));
  49977. //# sourceMappingURL=babylon.database.js.map
  49978. var BABYLON;
  49979. (function (BABYLON) {
  49980. var FresnelParameters = (function () {
  49981. function FresnelParameters() {
  49982. this._isEnabled = true;
  49983. this.leftColor = BABYLON.Color3.White();
  49984. this.rightColor = BABYLON.Color3.Black();
  49985. this.bias = 0;
  49986. this.power = 1;
  49987. }
  49988. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  49989. get: function () {
  49990. return this._isEnabled;
  49991. },
  49992. set: function (value) {
  49993. if (this._isEnabled === value) {
  49994. return;
  49995. }
  49996. this._isEnabled = value;
  49997. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  49998. },
  49999. enumerable: true,
  50000. configurable: true
  50001. });
  50002. FresnelParameters.prototype.clone = function () {
  50003. var newFresnelParameters = new FresnelParameters();
  50004. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  50005. return newFresnelParameters;
  50006. };
  50007. FresnelParameters.prototype.serialize = function () {
  50008. var serializationObject = {};
  50009. serializationObject.isEnabled = this.isEnabled;
  50010. serializationObject.leftColor = this.leftColor;
  50011. serializationObject.rightColor = this.rightColor;
  50012. serializationObject.bias = this.bias;
  50013. serializationObject.power = this.power;
  50014. return serializationObject;
  50015. };
  50016. FresnelParameters.Parse = function (parsedFresnelParameters) {
  50017. var fresnelParameters = new FresnelParameters();
  50018. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  50019. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  50020. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  50021. fresnelParameters.bias = parsedFresnelParameters.bias;
  50022. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  50023. return fresnelParameters;
  50024. };
  50025. return FresnelParameters;
  50026. }());
  50027. BABYLON.FresnelParameters = FresnelParameters;
  50028. })(BABYLON || (BABYLON = {}));
  50029. //# sourceMappingURL=babylon.fresnelParameters.js.map
  50030. var BABYLON;
  50031. (function (BABYLON) {
  50032. var MultiMaterial = (function (_super) {
  50033. __extends(MultiMaterial, _super);
  50034. function MultiMaterial(name, scene) {
  50035. var _this = _super.call(this, name, scene, true) || this;
  50036. scene.multiMaterials.push(_this);
  50037. _this.subMaterials = new Array();
  50038. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  50039. return _this;
  50040. }
  50041. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  50042. get: function () {
  50043. return this._subMaterials;
  50044. },
  50045. set: function (value) {
  50046. this._subMaterials = value;
  50047. this._hookArray(value);
  50048. },
  50049. enumerable: true,
  50050. configurable: true
  50051. });
  50052. MultiMaterial.prototype._hookArray = function (array) {
  50053. var _this = this;
  50054. var oldPush = array.push;
  50055. array.push = function () {
  50056. var items = [];
  50057. for (var _i = 0; _i < arguments.length; _i++) {
  50058. items[_i] = arguments[_i];
  50059. }
  50060. var result = oldPush.apply(array, items);
  50061. _this._markAllSubMeshesAsTexturesDirty();
  50062. return result;
  50063. };
  50064. var oldSplice = array.splice;
  50065. array.splice = function (index, deleteCount) {
  50066. var deleted = oldSplice.apply(array, [index, deleteCount]);
  50067. _this._markAllSubMeshesAsTexturesDirty();
  50068. return deleted;
  50069. };
  50070. };
  50071. // Properties
  50072. MultiMaterial.prototype.getSubMaterial = function (index) {
  50073. if (index < 0 || index >= this.subMaterials.length) {
  50074. return this.getScene().defaultMaterial;
  50075. }
  50076. return this.subMaterials[index];
  50077. };
  50078. MultiMaterial.prototype.getActiveTextures = function () {
  50079. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  50080. var _a;
  50081. };
  50082. // Methods
  50083. MultiMaterial.prototype.getClassName = function () {
  50084. return "MultiMaterial";
  50085. };
  50086. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  50087. for (var index = 0; index < this.subMaterials.length; index++) {
  50088. var subMaterial = this.subMaterials[index];
  50089. if (subMaterial) {
  50090. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  50091. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  50092. return false;
  50093. }
  50094. continue;
  50095. }
  50096. if (!this.subMaterials[index].isReady(mesh)) {
  50097. return false;
  50098. }
  50099. }
  50100. }
  50101. return true;
  50102. };
  50103. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  50104. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  50105. for (var index = 0; index < this.subMaterials.length; index++) {
  50106. var subMaterial = null;
  50107. if (cloneChildren) {
  50108. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  50109. }
  50110. else {
  50111. subMaterial = this.subMaterials[index];
  50112. }
  50113. newMultiMaterial.subMaterials.push(subMaterial);
  50114. }
  50115. return newMultiMaterial;
  50116. };
  50117. MultiMaterial.prototype.serialize = function () {
  50118. var serializationObject = {};
  50119. serializationObject.name = this.name;
  50120. serializationObject.id = this.id;
  50121. serializationObject.tags = BABYLON.Tags.GetTags(this);
  50122. serializationObject.materials = [];
  50123. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  50124. var subMat = this.subMaterials[matIndex];
  50125. if (subMat) {
  50126. serializationObject.materials.push(subMat.id);
  50127. }
  50128. else {
  50129. serializationObject.materials.push(null);
  50130. }
  50131. }
  50132. return serializationObject;
  50133. };
  50134. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50135. var scene = this.getScene();
  50136. if (!scene) {
  50137. return;
  50138. }
  50139. var index = scene.multiMaterials.indexOf(this);
  50140. if (index >= 0) {
  50141. scene.multiMaterials.splice(index, 1);
  50142. }
  50143. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50144. };
  50145. return MultiMaterial;
  50146. }(BABYLON.Material));
  50147. BABYLON.MultiMaterial = MultiMaterial;
  50148. })(BABYLON || (BABYLON = {}));
  50149. //# sourceMappingURL=babylon.multiMaterial.js.map
  50150. var BABYLON;
  50151. (function (BABYLON) {
  50152. var FreeCameraTouchInput = (function () {
  50153. function FreeCameraTouchInput() {
  50154. this._offsetX = null;
  50155. this._offsetY = null;
  50156. this._pointerCount = 0;
  50157. this._pointerPressed = [];
  50158. this.touchAngularSensibility = 200000.0;
  50159. this.touchMoveSensibility = 250.0;
  50160. }
  50161. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  50162. var _this = this;
  50163. var previousPosition;
  50164. if (this._pointerInput === undefined) {
  50165. this._onLostFocus = function (evt) {
  50166. _this._offsetX = null;
  50167. _this._offsetY = null;
  50168. };
  50169. this._pointerInput = function (p, s) {
  50170. var evt = p.event;
  50171. if (evt.pointerType === "mouse") {
  50172. return;
  50173. }
  50174. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50175. if (!noPreventDefault) {
  50176. evt.preventDefault();
  50177. }
  50178. _this._pointerPressed.push(evt.pointerId);
  50179. if (_this._pointerPressed.length !== 1) {
  50180. return;
  50181. }
  50182. previousPosition = {
  50183. x: evt.clientX,
  50184. y: evt.clientY
  50185. };
  50186. }
  50187. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  50188. if (!noPreventDefault) {
  50189. evt.preventDefault();
  50190. }
  50191. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50192. if (index === -1) {
  50193. return;
  50194. }
  50195. _this._pointerPressed.splice(index, 1);
  50196. if (index != 0) {
  50197. return;
  50198. }
  50199. previousPosition = null;
  50200. _this._offsetX = null;
  50201. _this._offsetY = null;
  50202. }
  50203. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50204. if (!noPreventDefault) {
  50205. evt.preventDefault();
  50206. }
  50207. if (!previousPosition) {
  50208. return;
  50209. }
  50210. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50211. if (index != 0) {
  50212. return;
  50213. }
  50214. _this._offsetX = evt.clientX - previousPosition.x;
  50215. _this._offsetY = -(evt.clientY - previousPosition.y);
  50216. }
  50217. };
  50218. }
  50219. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  50220. element.addEventListener("blur", this._onLostFocus);
  50221. };
  50222. FreeCameraTouchInput.prototype.detachControl = function (element) {
  50223. if (this._pointerInput && element) {
  50224. this.camera.getScene().onPointerObservable.remove(this._observer);
  50225. this._observer = null;
  50226. element.removeEventListener("blur", this._onLostFocus);
  50227. this._onLostFocus = null;
  50228. this._pointerPressed = [];
  50229. this._offsetX = null;
  50230. this._offsetY = null;
  50231. this._pointerCount = 0;
  50232. }
  50233. };
  50234. FreeCameraTouchInput.prototype.checkInputs = function () {
  50235. if (this._offsetX) {
  50236. var camera = this.camera;
  50237. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  50238. if (this._pointerPressed.length > 1) {
  50239. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  50240. }
  50241. else {
  50242. var speed = camera._computeLocalCameraSpeed();
  50243. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  50244. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  50245. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  50246. }
  50247. }
  50248. };
  50249. FreeCameraTouchInput.prototype.getClassName = function () {
  50250. return "FreeCameraTouchInput";
  50251. };
  50252. FreeCameraTouchInput.prototype.getSimpleName = function () {
  50253. return "touch";
  50254. };
  50255. __decorate([
  50256. BABYLON.serialize()
  50257. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  50258. __decorate([
  50259. BABYLON.serialize()
  50260. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  50261. return FreeCameraTouchInput;
  50262. }());
  50263. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  50264. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  50265. })(BABYLON || (BABYLON = {}));
  50266. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  50267. /// <reference path="babylon.freeCamera.ts" />
  50268. var BABYLON;
  50269. (function (BABYLON) {
  50270. // We're mainly based on the logic defined into the FreeCamera code
  50271. var TouchCamera = (function (_super) {
  50272. __extends(TouchCamera, _super);
  50273. //-- end properties for backward compatibility for inputs
  50274. function TouchCamera(name, position, scene) {
  50275. var _this = _super.call(this, name, position, scene) || this;
  50276. _this.inputs.addTouch();
  50277. _this._setupInputs();
  50278. return _this;
  50279. }
  50280. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  50281. //-- Begin properties for backward compatibility for inputs
  50282. get: function () {
  50283. var touch = this.inputs.attached["touch"];
  50284. if (touch)
  50285. return touch.touchAngularSensibility;
  50286. },
  50287. set: function (value) {
  50288. var touch = this.inputs.attached["touch"];
  50289. if (touch)
  50290. touch.touchAngularSensibility = value;
  50291. },
  50292. enumerable: true,
  50293. configurable: true
  50294. });
  50295. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  50296. get: function () {
  50297. var touch = this.inputs.attached["touch"];
  50298. if (touch)
  50299. return touch.touchMoveSensibility;
  50300. },
  50301. set: function (value) {
  50302. var touch = this.inputs.attached["touch"];
  50303. if (touch)
  50304. touch.touchMoveSensibility = value;
  50305. },
  50306. enumerable: true,
  50307. configurable: true
  50308. });
  50309. TouchCamera.prototype.getClassName = function () {
  50310. return "TouchCamera";
  50311. };
  50312. TouchCamera.prototype._setupInputs = function () {
  50313. var mouse = this.inputs.attached["mouse"];
  50314. if (mouse) {
  50315. mouse.touchEnabled = false;
  50316. }
  50317. };
  50318. return TouchCamera;
  50319. }(BABYLON.FreeCamera));
  50320. BABYLON.TouchCamera = TouchCamera;
  50321. })(BABYLON || (BABYLON = {}));
  50322. //# sourceMappingURL=babylon.touchCamera.js.map
  50323. var BABYLON;
  50324. (function (BABYLON) {
  50325. var ProceduralTexture = (function (_super) {
  50326. __extends(ProceduralTexture, _super);
  50327. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  50328. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50329. if (isCube === void 0) { isCube = false; }
  50330. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50331. _this.isCube = isCube;
  50332. _this.isEnabled = true;
  50333. _this._currentRefreshId = -1;
  50334. _this._refreshRate = 1;
  50335. _this._vertexBuffers = {};
  50336. _this._uniforms = new Array();
  50337. _this._samplers = new Array();
  50338. _this._textures = new Array();
  50339. _this._floats = new Array();
  50340. _this._floatsArrays = {};
  50341. _this._colors3 = new Array();
  50342. _this._colors4 = new Array();
  50343. _this._vectors2 = new Array();
  50344. _this._vectors3 = new Array();
  50345. _this._matrices = new Array();
  50346. _this._fallbackTextureUsed = false;
  50347. scene._proceduralTextures.push(_this);
  50348. _this.name = name;
  50349. _this.isRenderTarget = true;
  50350. _this._size = size;
  50351. _this._generateMipMaps = generateMipMaps;
  50352. _this.setFragment(fragment);
  50353. _this._fallbackTexture = fallbackTexture;
  50354. var engine = scene.getEngine();
  50355. if (isCube) {
  50356. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  50357. _this.setFloat("face", 0);
  50358. }
  50359. else {
  50360. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  50361. }
  50362. // VBO
  50363. var vertices = [];
  50364. vertices.push(1, 1);
  50365. vertices.push(-1, 1);
  50366. vertices.push(-1, -1);
  50367. vertices.push(1, -1);
  50368. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50369. _this._createIndexBuffer();
  50370. return _this;
  50371. }
  50372. ProceduralTexture.prototype._createIndexBuffer = function () {
  50373. var engine = this.getScene().getEngine();
  50374. // Indices
  50375. var indices = [];
  50376. indices.push(0);
  50377. indices.push(1);
  50378. indices.push(2);
  50379. indices.push(0);
  50380. indices.push(2);
  50381. indices.push(3);
  50382. this._indexBuffer = engine.createIndexBuffer(indices);
  50383. };
  50384. ProceduralTexture.prototype._rebuild = function () {
  50385. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  50386. this._createIndexBuffer();
  50387. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50388. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50389. }
  50390. };
  50391. ProceduralTexture.prototype.reset = function () {
  50392. if (this._effect === undefined) {
  50393. return;
  50394. }
  50395. var engine = this.getScene().getEngine();
  50396. engine._releaseEffect(this._effect);
  50397. };
  50398. ProceduralTexture.prototype.isReady = function () {
  50399. var _this = this;
  50400. var engine = this.getScene().getEngine();
  50401. var shaders;
  50402. if (!this._fragment) {
  50403. return false;
  50404. }
  50405. if (this._fallbackTextureUsed) {
  50406. return true;
  50407. }
  50408. if (this._fragment.fragmentElement !== undefined) {
  50409. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  50410. }
  50411. else {
  50412. shaders = { vertex: "procedural", fragment: this._fragment };
  50413. }
  50414. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  50415. _this.releaseInternalTexture();
  50416. if (_this._fallbackTexture) {
  50417. _this._texture = _this._fallbackTexture._texture;
  50418. _this._texture.incrementReferences();
  50419. }
  50420. _this._fallbackTextureUsed = true;
  50421. });
  50422. return this._effect.isReady();
  50423. };
  50424. ProceduralTexture.prototype.resetRefreshCounter = function () {
  50425. this._currentRefreshId = -1;
  50426. };
  50427. ProceduralTexture.prototype.setFragment = function (fragment) {
  50428. this._fragment = fragment;
  50429. };
  50430. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  50431. get: function () {
  50432. return this._refreshRate;
  50433. },
  50434. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50435. set: function (value) {
  50436. this._refreshRate = value;
  50437. this.resetRefreshCounter();
  50438. },
  50439. enumerable: true,
  50440. configurable: true
  50441. });
  50442. ProceduralTexture.prototype._shouldRender = function () {
  50443. if (!this.isEnabled || !this.isReady() || !this._texture) {
  50444. return false;
  50445. }
  50446. if (this._fallbackTextureUsed) {
  50447. return false;
  50448. }
  50449. if (this._currentRefreshId === -1) {
  50450. this._currentRefreshId = 1;
  50451. return true;
  50452. }
  50453. if (this.refreshRate === this._currentRefreshId) {
  50454. this._currentRefreshId = 1;
  50455. return true;
  50456. }
  50457. this._currentRefreshId++;
  50458. return false;
  50459. };
  50460. ProceduralTexture.prototype.getRenderSize = function () {
  50461. return this._size;
  50462. };
  50463. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  50464. if (this._fallbackTextureUsed) {
  50465. return;
  50466. }
  50467. this.releaseInternalTexture();
  50468. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  50469. };
  50470. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  50471. if (this._uniforms.indexOf(uniformName) === -1) {
  50472. this._uniforms.push(uniformName);
  50473. }
  50474. };
  50475. ProceduralTexture.prototype.setTexture = function (name, texture) {
  50476. if (this._samplers.indexOf(name) === -1) {
  50477. this._samplers.push(name);
  50478. }
  50479. this._textures[name] = texture;
  50480. return this;
  50481. };
  50482. ProceduralTexture.prototype.setFloat = function (name, value) {
  50483. this._checkUniform(name);
  50484. this._floats[name] = value;
  50485. return this;
  50486. };
  50487. ProceduralTexture.prototype.setFloats = function (name, value) {
  50488. this._checkUniform(name);
  50489. this._floatsArrays[name] = value;
  50490. return this;
  50491. };
  50492. ProceduralTexture.prototype.setColor3 = function (name, value) {
  50493. this._checkUniform(name);
  50494. this._colors3[name] = value;
  50495. return this;
  50496. };
  50497. ProceduralTexture.prototype.setColor4 = function (name, value) {
  50498. this._checkUniform(name);
  50499. this._colors4[name] = value;
  50500. return this;
  50501. };
  50502. ProceduralTexture.prototype.setVector2 = function (name, value) {
  50503. this._checkUniform(name);
  50504. this._vectors2[name] = value;
  50505. return this;
  50506. };
  50507. ProceduralTexture.prototype.setVector3 = function (name, value) {
  50508. this._checkUniform(name);
  50509. this._vectors3[name] = value;
  50510. return this;
  50511. };
  50512. ProceduralTexture.prototype.setMatrix = function (name, value) {
  50513. this._checkUniform(name);
  50514. this._matrices[name] = value;
  50515. return this;
  50516. };
  50517. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50518. var scene = this.getScene();
  50519. var engine = scene.getEngine();
  50520. // Render
  50521. engine.enableEffect(this._effect);
  50522. engine.setState(false);
  50523. // Texture
  50524. for (var name in this._textures) {
  50525. this._effect.setTexture(name, this._textures[name]);
  50526. }
  50527. // Float
  50528. for (name in this._floats) {
  50529. this._effect.setFloat(name, this._floats[name]);
  50530. }
  50531. // Floats
  50532. for (name in this._floatsArrays) {
  50533. this._effect.setArray(name, this._floatsArrays[name]);
  50534. }
  50535. // Color3
  50536. for (name in this._colors3) {
  50537. this._effect.setColor3(name, this._colors3[name]);
  50538. }
  50539. // Color4
  50540. for (name in this._colors4) {
  50541. var color = this._colors4[name];
  50542. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50543. }
  50544. // Vector2
  50545. for (name in this._vectors2) {
  50546. this._effect.setVector2(name, this._vectors2[name]);
  50547. }
  50548. // Vector3
  50549. for (name in this._vectors3) {
  50550. this._effect.setVector3(name, this._vectors3[name]);
  50551. }
  50552. // Matrix
  50553. for (name in this._matrices) {
  50554. this._effect.setMatrix(name, this._matrices[name]);
  50555. }
  50556. if (this.isCube) {
  50557. for (var face = 0; face < 6; face++) {
  50558. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  50559. // VBOs
  50560. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50561. this._effect.setFloat("face", face);
  50562. // Clear
  50563. engine.clear(scene.clearColor, true, true, true);
  50564. // Draw order
  50565. engine.draw(true, 0, 6);
  50566. // Mipmaps
  50567. if (face === 5) {
  50568. engine.generateMipMapsForCubemap(this._texture);
  50569. }
  50570. }
  50571. }
  50572. else {
  50573. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  50574. // VBOs
  50575. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50576. // Clear
  50577. engine.clear(scene.clearColor, true, true, true);
  50578. // Draw order
  50579. engine.draw(true, 0, 6);
  50580. }
  50581. // Unbind
  50582. engine.unBindFramebuffer(this._texture, this.isCube);
  50583. if (this.onGenerated) {
  50584. this.onGenerated();
  50585. }
  50586. };
  50587. ProceduralTexture.prototype.clone = function () {
  50588. var textureSize = this.getSize();
  50589. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  50590. // Base texture
  50591. newTexture.hasAlpha = this.hasAlpha;
  50592. newTexture.level = this.level;
  50593. // RenderTarget Texture
  50594. newTexture.coordinatesMode = this.coordinatesMode;
  50595. return newTexture;
  50596. };
  50597. ProceduralTexture.prototype.dispose = function () {
  50598. var index = this.getScene()._proceduralTextures.indexOf(this);
  50599. if (index >= 0) {
  50600. this.getScene()._proceduralTextures.splice(index, 1);
  50601. }
  50602. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50603. if (vertexBuffer) {
  50604. vertexBuffer.dispose();
  50605. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50606. }
  50607. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  50608. this._indexBuffer = null;
  50609. }
  50610. _super.prototype.dispose.call(this);
  50611. };
  50612. return ProceduralTexture;
  50613. }(BABYLON.Texture));
  50614. BABYLON.ProceduralTexture = ProceduralTexture;
  50615. })(BABYLON || (BABYLON = {}));
  50616. //# sourceMappingURL=babylon.proceduralTexture.js.map
  50617. /// <reference path="babylon.proceduralTexture.ts" />
  50618. var BABYLON;
  50619. (function (BABYLON) {
  50620. var CustomProceduralTexture = (function (_super) {
  50621. __extends(CustomProceduralTexture, _super);
  50622. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  50623. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  50624. _this._animate = true;
  50625. _this._time = 0;
  50626. _this._texturePath = texturePath;
  50627. //Try to load json
  50628. _this.loadJson(texturePath);
  50629. _this.refreshRate = 1;
  50630. return _this;
  50631. }
  50632. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  50633. var _this = this;
  50634. var that = this;
  50635. function noConfigFile() {
  50636. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  50637. try {
  50638. that.setFragment(that._texturePath);
  50639. }
  50640. catch (ex) {
  50641. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  50642. }
  50643. }
  50644. var configFileUrl = jsonUrl + "/config.json";
  50645. var xhr = new XMLHttpRequest();
  50646. xhr.open("GET", configFileUrl, true);
  50647. xhr.addEventListener("load", function () {
  50648. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  50649. try {
  50650. _this._config = JSON.parse(xhr.response);
  50651. _this.updateShaderUniforms();
  50652. _this.updateTextures();
  50653. _this.setFragment(_this._texturePath + "/custom");
  50654. _this._animate = _this._config.animate;
  50655. _this.refreshRate = _this._config.refreshrate;
  50656. }
  50657. catch (ex) {
  50658. noConfigFile();
  50659. }
  50660. }
  50661. else {
  50662. noConfigFile();
  50663. }
  50664. }, false);
  50665. xhr.addEventListener("error", function () {
  50666. noConfigFile();
  50667. }, false);
  50668. try {
  50669. xhr.send();
  50670. }
  50671. catch (ex) {
  50672. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  50673. }
  50674. };
  50675. CustomProceduralTexture.prototype.isReady = function () {
  50676. if (!_super.prototype.isReady.call(this)) {
  50677. return false;
  50678. }
  50679. for (var name in this._textures) {
  50680. var texture = this._textures[name];
  50681. if (!texture.isReady()) {
  50682. return false;
  50683. }
  50684. }
  50685. return true;
  50686. };
  50687. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50688. if (this._animate) {
  50689. this._time += this.getScene().getAnimationRatio() * 0.03;
  50690. this.updateShaderUniforms();
  50691. }
  50692. _super.prototype.render.call(this, useCameraPostProcess);
  50693. };
  50694. CustomProceduralTexture.prototype.updateTextures = function () {
  50695. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  50696. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  50697. }
  50698. };
  50699. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  50700. if (this._config) {
  50701. for (var j = 0; j < this._config.uniforms.length; j++) {
  50702. var uniform = this._config.uniforms[j];
  50703. switch (uniform.type) {
  50704. case "float":
  50705. this.setFloat(uniform.name, uniform.value);
  50706. break;
  50707. case "color3":
  50708. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  50709. break;
  50710. case "color4":
  50711. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  50712. break;
  50713. case "vector2":
  50714. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  50715. break;
  50716. case "vector3":
  50717. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  50718. break;
  50719. }
  50720. }
  50721. }
  50722. this.setFloat("time", this._time);
  50723. };
  50724. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  50725. get: function () {
  50726. return this._animate;
  50727. },
  50728. set: function (value) {
  50729. this._animate = value;
  50730. },
  50731. enumerable: true,
  50732. configurable: true
  50733. });
  50734. return CustomProceduralTexture;
  50735. }(BABYLON.ProceduralTexture));
  50736. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  50737. })(BABYLON || (BABYLON = {}));
  50738. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  50739. var BABYLON;
  50740. (function (BABYLON) {
  50741. var FreeCameraGamepadInput = (function () {
  50742. function FreeCameraGamepadInput() {
  50743. this.gamepadAngularSensibility = 200;
  50744. this.gamepadMoveSensibility = 40;
  50745. // private members
  50746. this._cameraTransform = BABYLON.Matrix.Identity();
  50747. this._deltaTransform = BABYLON.Vector3.Zero();
  50748. this._vector3 = BABYLON.Vector3.Zero();
  50749. this._vector2 = BABYLON.Vector2.Zero();
  50750. }
  50751. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50752. var _this = this;
  50753. var manager = this.camera.getScene().gamepadManager;
  50754. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50755. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50756. // prioritize XBOX gamepads.
  50757. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50758. _this.gamepad = gamepad;
  50759. }
  50760. }
  50761. });
  50762. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50763. if (_this.gamepad === gamepad) {
  50764. _this.gamepad = null;
  50765. }
  50766. });
  50767. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50768. };
  50769. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  50770. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50771. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50772. this.gamepad = null;
  50773. };
  50774. FreeCameraGamepadInput.prototype.checkInputs = function () {
  50775. if (this.gamepad && this.gamepad.leftStick) {
  50776. var camera = this.camera;
  50777. var LSValues = this.gamepad.leftStick;
  50778. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  50779. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50780. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  50781. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  50782. var RSValues = this.gamepad.rightStick;
  50783. if (RSValues) {
  50784. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  50785. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  50786. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  50787. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  50788. }
  50789. else {
  50790. RSValues = { x: 0, y: 0 };
  50791. }
  50792. if (!camera.rotationQuaternion) {
  50793. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  50794. }
  50795. else {
  50796. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  50797. }
  50798. var speed = camera._computeLocalCameraSpeed() * 50.0;
  50799. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  50800. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  50801. camera.cameraDirection.addInPlace(this._deltaTransform);
  50802. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  50803. camera.cameraRotation.addInPlace(this._vector2);
  50804. }
  50805. };
  50806. FreeCameraGamepadInput.prototype.getClassName = function () {
  50807. return "FreeCameraGamepadInput";
  50808. };
  50809. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  50810. return "gamepad";
  50811. };
  50812. __decorate([
  50813. BABYLON.serialize()
  50814. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  50815. __decorate([
  50816. BABYLON.serialize()
  50817. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  50818. return FreeCameraGamepadInput;
  50819. }());
  50820. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  50821. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  50822. })(BABYLON || (BABYLON = {}));
  50823. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  50824. var BABYLON;
  50825. (function (BABYLON) {
  50826. var ArcRotateCameraGamepadInput = (function () {
  50827. function ArcRotateCameraGamepadInput() {
  50828. this.gamepadRotationSensibility = 80;
  50829. this.gamepadMoveSensibility = 40;
  50830. }
  50831. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50832. var _this = this;
  50833. var manager = this.camera.getScene().gamepadManager;
  50834. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50835. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50836. // prioritize XBOX gamepads.
  50837. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50838. _this.gamepad = gamepad;
  50839. }
  50840. }
  50841. });
  50842. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50843. if (_this.gamepad === gamepad) {
  50844. _this.gamepad = null;
  50845. }
  50846. });
  50847. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50848. };
  50849. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  50850. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50851. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50852. this.gamepad = null;
  50853. };
  50854. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  50855. if (this.gamepad) {
  50856. var camera = this.camera;
  50857. var RSValues = this.gamepad.rightStick;
  50858. if (RSValues) {
  50859. if (RSValues.x != 0) {
  50860. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  50861. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  50862. camera.inertialAlphaOffset += normalizedRX;
  50863. }
  50864. }
  50865. if (RSValues.y != 0) {
  50866. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  50867. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  50868. camera.inertialBetaOffset += normalizedRY;
  50869. }
  50870. }
  50871. }
  50872. var LSValues = this.gamepad.leftStick;
  50873. if (LSValues && LSValues.y != 0) {
  50874. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50875. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  50876. this.camera.inertialRadiusOffset -= normalizedLY;
  50877. }
  50878. }
  50879. }
  50880. };
  50881. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  50882. return "ArcRotateCameraGamepadInput";
  50883. };
  50884. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  50885. return "gamepad";
  50886. };
  50887. __decorate([
  50888. BABYLON.serialize()
  50889. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  50890. __decorate([
  50891. BABYLON.serialize()
  50892. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  50893. return ArcRotateCameraGamepadInput;
  50894. }());
  50895. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  50896. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  50897. })(BABYLON || (BABYLON = {}));
  50898. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  50899. var BABYLON;
  50900. (function (BABYLON) {
  50901. var GamepadManager = (function () {
  50902. function GamepadManager() {
  50903. var _this = this;
  50904. this._babylonGamepads = [];
  50905. this._oneGamepadConnected = false;
  50906. this._isMonitoring = false;
  50907. this._gamepadEventSupported = 'GamepadEvent' in window;
  50908. this._gamepadSupport = (navigator.getGamepads ||
  50909. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50910. this.onGamepadConnectedObservable = new BABYLON.Observable();
  50911. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  50912. this._onGamepadConnectedEvent = function (evt) {
  50913. var gamepad = evt.gamepad;
  50914. // Protection code for Chrome which has a very buggy gamepad implementation...
  50915. // And raises a connected event on disconnection for instance
  50916. if (gamepad.index in _this._babylonGamepads) {
  50917. return;
  50918. }
  50919. var newGamepad = _this._addNewGamepad(gamepad);
  50920. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  50921. _this._startMonitoringGamepads();
  50922. };
  50923. this._onGamepadDisconnectedEvent = function (evt) {
  50924. var gamepad = evt.gamepad;
  50925. // Remove the gamepad from the list of gamepads to monitor.
  50926. for (var i in _this._babylonGamepads) {
  50927. if (_this._babylonGamepads[i].index === gamepad.index) {
  50928. var gamepadToRemove = _this._babylonGamepads[i];
  50929. _this._babylonGamepads[i] = null;
  50930. _this.onGamepadDisconnectedObservable.notifyObservers(gamepadToRemove);
  50931. gamepadToRemove.dispose();
  50932. break;
  50933. }
  50934. }
  50935. };
  50936. if (this._gamepadSupport) {
  50937. //first add already-connected gamepads
  50938. this._updateGamepadObjects();
  50939. if (this._babylonGamepads.length) {
  50940. this._startMonitoringGamepads();
  50941. }
  50942. // Checking if the gamepad connected event is supported (like in Firefox)
  50943. if (this._gamepadEventSupported) {
  50944. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50945. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  50946. }
  50947. else {
  50948. this._startMonitoringGamepads();
  50949. }
  50950. }
  50951. }
  50952. GamepadManager.prototype.getGamepadByType = function (type) {
  50953. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  50954. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  50955. var gamepad = _a[_i];
  50956. if (gamepad && gamepad.type === type) {
  50957. return gamepad;
  50958. }
  50959. }
  50960. return null;
  50961. };
  50962. GamepadManager.prototype.dispose = function () {
  50963. if (this._gamepadEventSupported) {
  50964. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  50965. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  50966. this._onGamepadConnectedEvent = null;
  50967. this._onGamepadDisconnectedEvent = null;
  50968. }
  50969. this._oneGamepadConnected = false;
  50970. this._stopMonitoringGamepads();
  50971. this._babylonGamepads = [];
  50972. };
  50973. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  50974. if (!this._oneGamepadConnected) {
  50975. this._oneGamepadConnected = true;
  50976. }
  50977. var newGamepad;
  50978. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  50979. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50980. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  50981. }
  50982. else if (gamepad.pose) {
  50983. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  50984. }
  50985. else {
  50986. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  50987. }
  50988. this._babylonGamepads[newGamepad.index] = newGamepad;
  50989. return newGamepad;
  50990. };
  50991. GamepadManager.prototype._startMonitoringGamepads = function () {
  50992. if (!this._isMonitoring) {
  50993. this._isMonitoring = true;
  50994. this._checkGamepadsStatus();
  50995. }
  50996. };
  50997. GamepadManager.prototype._stopMonitoringGamepads = function () {
  50998. this._isMonitoring = false;
  50999. };
  51000. GamepadManager.prototype._checkGamepadsStatus = function () {
  51001. var _this = this;
  51002. // Hack to be compatible Chrome
  51003. this._updateGamepadObjects();
  51004. for (var i in this._babylonGamepads) {
  51005. var gamepad = this._babylonGamepads[i];
  51006. if (!gamepad) {
  51007. continue;
  51008. }
  51009. gamepad.update();
  51010. }
  51011. if (this._isMonitoring) {
  51012. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  51013. }
  51014. };
  51015. // This function is called only on Chrome, which does not properly support
  51016. // connection/disconnection events and forces you to recopy again the gamepad object
  51017. GamepadManager.prototype._updateGamepadObjects = function () {
  51018. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51019. for (var i = 0; i < gamepads.length; i++) {
  51020. if (gamepads[i]) {
  51021. if (!this._babylonGamepads[gamepads[i].index]) {
  51022. var newGamepad = this._addNewGamepad(gamepads[i]);
  51023. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51024. }
  51025. else {
  51026. // Forced to copy again this object for Chrome for unknown reason
  51027. this._babylonGamepads[i].browserGamepad = gamepads[i];
  51028. }
  51029. }
  51030. }
  51031. };
  51032. return GamepadManager;
  51033. }());
  51034. BABYLON.GamepadManager = GamepadManager;
  51035. })(BABYLON || (BABYLON = {}));
  51036. //# sourceMappingURL=babylon.gamepadManager.js.map
  51037. var BABYLON;
  51038. (function (BABYLON) {
  51039. var StickValues = (function () {
  51040. function StickValues(x, y) {
  51041. this.x = x;
  51042. this.y = y;
  51043. }
  51044. return StickValues;
  51045. }());
  51046. BABYLON.StickValues = StickValues;
  51047. var Gamepad = (function () {
  51048. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51049. if (leftStickX === void 0) { leftStickX = 0; }
  51050. if (leftStickY === void 0) { leftStickY = 1; }
  51051. if (rightStickX === void 0) { rightStickX = 2; }
  51052. if (rightStickY === void 0) { rightStickY = 3; }
  51053. this.id = id;
  51054. this.index = index;
  51055. this.browserGamepad = browserGamepad;
  51056. this.type = Gamepad.GAMEPAD;
  51057. this._leftStickAxisX = leftStickX;
  51058. this._leftStickAxisY = leftStickY;
  51059. this._rightStickAxisX = rightStickX;
  51060. this._rightStickAxisY = rightStickY;
  51061. if (this.browserGamepad.axes.length >= 2) {
  51062. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51063. }
  51064. if (this.browserGamepad.axes.length >= 4) {
  51065. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51066. }
  51067. }
  51068. Gamepad.prototype.onleftstickchanged = function (callback) {
  51069. this._onleftstickchanged = callback;
  51070. };
  51071. Gamepad.prototype.onrightstickchanged = function (callback) {
  51072. this._onrightstickchanged = callback;
  51073. };
  51074. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51075. get: function () {
  51076. return this._leftStick;
  51077. },
  51078. set: function (newValues) {
  51079. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51080. this._onleftstickchanged(newValues);
  51081. }
  51082. this._leftStick = newValues;
  51083. },
  51084. enumerable: true,
  51085. configurable: true
  51086. });
  51087. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51088. get: function () {
  51089. return this._rightStick;
  51090. },
  51091. set: function (newValues) {
  51092. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51093. this._onrightstickchanged(newValues);
  51094. }
  51095. this._rightStick = newValues;
  51096. },
  51097. enumerable: true,
  51098. configurable: true
  51099. });
  51100. Gamepad.prototype.update = function () {
  51101. if (this._leftStick) {
  51102. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51103. }
  51104. if (this._rightStick) {
  51105. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51106. }
  51107. };
  51108. Gamepad.prototype.dispose = function () {
  51109. };
  51110. Gamepad.GAMEPAD = 0;
  51111. Gamepad.GENERIC = 1;
  51112. Gamepad.XBOX = 2;
  51113. Gamepad.POSE_ENABLED = 3;
  51114. return Gamepad;
  51115. }());
  51116. BABYLON.Gamepad = Gamepad;
  51117. var GenericPad = (function (_super) {
  51118. __extends(GenericPad, _super);
  51119. function GenericPad(id, index, browserGamepad) {
  51120. var _this = _super.call(this, id, index, browserGamepad) || this;
  51121. _this.type = Gamepad.GENERIC;
  51122. _this._buttons = new Array(browserGamepad.buttons.length);
  51123. return _this;
  51124. }
  51125. GenericPad.prototype.onbuttondown = function (callback) {
  51126. this._onbuttondown = callback;
  51127. };
  51128. GenericPad.prototype.onbuttonup = function (callback) {
  51129. this._onbuttonup = callback;
  51130. };
  51131. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51132. if (newValue !== currentValue) {
  51133. if (this._onbuttondown && newValue === 1) {
  51134. this._onbuttondown(buttonIndex);
  51135. }
  51136. if (this._onbuttonup && newValue === 0) {
  51137. this._onbuttonup(buttonIndex);
  51138. }
  51139. }
  51140. return newValue;
  51141. };
  51142. GenericPad.prototype.update = function () {
  51143. _super.prototype.update.call(this);
  51144. for (var index = 0; index < this._buttons.length; index++) {
  51145. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  51146. }
  51147. };
  51148. return GenericPad;
  51149. }(Gamepad));
  51150. BABYLON.GenericPad = GenericPad;
  51151. })(BABYLON || (BABYLON = {}));
  51152. //# sourceMappingURL=babylon.gamepad.js.map
  51153. var BABYLON;
  51154. (function (BABYLON) {
  51155. var Xbox360Button;
  51156. (function (Xbox360Button) {
  51157. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51158. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51159. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51160. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51161. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51162. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51163. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51164. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51165. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51166. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51167. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51168. var Xbox360Dpad;
  51169. (function (Xbox360Dpad) {
  51170. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51171. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51172. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51173. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51174. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51175. var Xbox360Pad = (function (_super) {
  51176. __extends(Xbox360Pad, _super);
  51177. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51178. if (xboxOne === void 0) { xboxOne = false; }
  51179. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51180. _this._leftTrigger = 0;
  51181. _this._rightTrigger = 0;
  51182. _this._buttonA = 0;
  51183. _this._buttonB = 0;
  51184. _this._buttonX = 0;
  51185. _this._buttonY = 0;
  51186. _this._buttonBack = 0;
  51187. _this._buttonStart = 0;
  51188. _this._buttonLB = 0;
  51189. _this._buttonRB = 0;
  51190. _this._buttonLeftStick = 0;
  51191. _this._buttonRightStick = 0;
  51192. _this._dPadUp = 0;
  51193. _this._dPadDown = 0;
  51194. _this._dPadLeft = 0;
  51195. _this._dPadRight = 0;
  51196. _this._isXboxOnePad = false;
  51197. _this.type = BABYLON.Gamepad.XBOX;
  51198. _this._isXboxOnePad = xboxOne;
  51199. return _this;
  51200. }
  51201. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51202. this._onlefttriggerchanged = callback;
  51203. };
  51204. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51205. this._onrighttriggerchanged = callback;
  51206. };
  51207. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51208. get: function () {
  51209. return this._leftTrigger;
  51210. },
  51211. set: function (newValue) {
  51212. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51213. this._onlefttriggerchanged(newValue);
  51214. }
  51215. this._leftTrigger = newValue;
  51216. },
  51217. enumerable: true,
  51218. configurable: true
  51219. });
  51220. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51221. get: function () {
  51222. return this._rightTrigger;
  51223. },
  51224. set: function (newValue) {
  51225. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51226. this._onrighttriggerchanged(newValue);
  51227. }
  51228. this._rightTrigger = newValue;
  51229. },
  51230. enumerable: true,
  51231. configurable: true
  51232. });
  51233. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51234. this._onbuttondown = callback;
  51235. };
  51236. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51237. this._onbuttonup = callback;
  51238. };
  51239. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51240. this._ondpaddown = callback;
  51241. };
  51242. Xbox360Pad.prototype.ondpadup = function (callback) {
  51243. this._ondpadup = callback;
  51244. };
  51245. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51246. if (newValue !== currentValue) {
  51247. if (this._onbuttondown && newValue === 1) {
  51248. this._onbuttondown(buttonType);
  51249. }
  51250. if (this._onbuttonup && newValue === 0) {
  51251. this._onbuttonup(buttonType);
  51252. }
  51253. }
  51254. return newValue;
  51255. };
  51256. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51257. if (newValue !== currentValue) {
  51258. if (this._ondpaddown && newValue === 1) {
  51259. this._ondpaddown(buttonType);
  51260. }
  51261. if (this._ondpadup && newValue === 0) {
  51262. this._ondpadup(buttonType);
  51263. }
  51264. }
  51265. return newValue;
  51266. };
  51267. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51268. get: function () {
  51269. return this._buttonA;
  51270. },
  51271. set: function (value) {
  51272. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51273. },
  51274. enumerable: true,
  51275. configurable: true
  51276. });
  51277. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51278. get: function () {
  51279. return this._buttonB;
  51280. },
  51281. set: function (value) {
  51282. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51283. },
  51284. enumerable: true,
  51285. configurable: true
  51286. });
  51287. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51288. get: function () {
  51289. return this._buttonX;
  51290. },
  51291. set: function (value) {
  51292. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51293. },
  51294. enumerable: true,
  51295. configurable: true
  51296. });
  51297. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51298. get: function () {
  51299. return this._buttonY;
  51300. },
  51301. set: function (value) {
  51302. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51303. },
  51304. enumerable: true,
  51305. configurable: true
  51306. });
  51307. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51308. get: function () {
  51309. return this._buttonStart;
  51310. },
  51311. set: function (value) {
  51312. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51313. },
  51314. enumerable: true,
  51315. configurable: true
  51316. });
  51317. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51318. get: function () {
  51319. return this._buttonBack;
  51320. },
  51321. set: function (value) {
  51322. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51323. },
  51324. enumerable: true,
  51325. configurable: true
  51326. });
  51327. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51328. get: function () {
  51329. return this._buttonLB;
  51330. },
  51331. set: function (value) {
  51332. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51333. },
  51334. enumerable: true,
  51335. configurable: true
  51336. });
  51337. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51338. get: function () {
  51339. return this._buttonRB;
  51340. },
  51341. set: function (value) {
  51342. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51343. },
  51344. enumerable: true,
  51345. configurable: true
  51346. });
  51347. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51348. get: function () {
  51349. return this._buttonLeftStick;
  51350. },
  51351. set: function (value) {
  51352. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51353. },
  51354. enumerable: true,
  51355. configurable: true
  51356. });
  51357. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51358. get: function () {
  51359. return this._buttonRightStick;
  51360. },
  51361. set: function (value) {
  51362. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51363. },
  51364. enumerable: true,
  51365. configurable: true
  51366. });
  51367. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51368. get: function () {
  51369. return this._dPadUp;
  51370. },
  51371. set: function (value) {
  51372. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51373. },
  51374. enumerable: true,
  51375. configurable: true
  51376. });
  51377. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51378. get: function () {
  51379. return this._dPadDown;
  51380. },
  51381. set: function (value) {
  51382. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51383. },
  51384. enumerable: true,
  51385. configurable: true
  51386. });
  51387. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51388. get: function () {
  51389. return this._dPadLeft;
  51390. },
  51391. set: function (value) {
  51392. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51393. },
  51394. enumerable: true,
  51395. configurable: true
  51396. });
  51397. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51398. get: function () {
  51399. return this._dPadRight;
  51400. },
  51401. set: function (value) {
  51402. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51403. },
  51404. enumerable: true,
  51405. configurable: true
  51406. });
  51407. Xbox360Pad.prototype.update = function () {
  51408. _super.prototype.update.call(this);
  51409. if (this._isXboxOnePad) {
  51410. this.buttonA = this.browserGamepad.buttons[0].value;
  51411. this.buttonB = this.browserGamepad.buttons[1].value;
  51412. this.buttonX = this.browserGamepad.buttons[2].value;
  51413. this.buttonY = this.browserGamepad.buttons[3].value;
  51414. this.buttonLB = this.browserGamepad.buttons[4].value;
  51415. this.buttonRB = this.browserGamepad.buttons[5].value;
  51416. this.leftTrigger = this.browserGamepad.axes[2];
  51417. this.rightTrigger = this.browserGamepad.axes[5];
  51418. this.buttonBack = this.browserGamepad.buttons[9].value;
  51419. this.buttonStart = this.browserGamepad.buttons[8].value;
  51420. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51421. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51422. this.dPadUp = this.browserGamepad.buttons[11].value;
  51423. this.dPadDown = this.browserGamepad.buttons[12].value;
  51424. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51425. this.dPadRight = this.browserGamepad.buttons[14].value;
  51426. }
  51427. else {
  51428. this.buttonA = this.browserGamepad.buttons[0].value;
  51429. this.buttonB = this.browserGamepad.buttons[1].value;
  51430. this.buttonX = this.browserGamepad.buttons[2].value;
  51431. this.buttonY = this.browserGamepad.buttons[3].value;
  51432. this.buttonLB = this.browserGamepad.buttons[4].value;
  51433. this.buttonRB = this.browserGamepad.buttons[5].value;
  51434. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51435. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51436. this.buttonBack = this.browserGamepad.buttons[8].value;
  51437. this.buttonStart = this.browserGamepad.buttons[9].value;
  51438. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51439. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51440. this.dPadUp = this.browserGamepad.buttons[12].value;
  51441. this.dPadDown = this.browserGamepad.buttons[13].value;
  51442. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51443. this.dPadRight = this.browserGamepad.buttons[15].value;
  51444. }
  51445. };
  51446. return Xbox360Pad;
  51447. }(BABYLON.Gamepad));
  51448. BABYLON.Xbox360Pad = Xbox360Pad;
  51449. })(BABYLON || (BABYLON = {}));
  51450. //# sourceMappingURL=babylon.xboxGamepad.js.map
  51451. var BABYLON;
  51452. (function (BABYLON) {
  51453. var PoseEnabledControllerType;
  51454. (function (PoseEnabledControllerType) {
  51455. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51456. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51457. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  51458. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  51459. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51460. var PoseEnabledControllerHelper = (function () {
  51461. function PoseEnabledControllerHelper() {
  51462. }
  51463. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51464. // Oculus Touch
  51465. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51466. return new BABYLON.OculusTouchController(vrGamepad);
  51467. }
  51468. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  51469. return new BABYLON.ViveController(vrGamepad);
  51470. }
  51471. else {
  51472. return new BABYLON.GenericController(vrGamepad);
  51473. }
  51474. };
  51475. return PoseEnabledControllerHelper;
  51476. }());
  51477. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51478. var PoseEnabledController = (function (_super) {
  51479. __extends(PoseEnabledController, _super);
  51480. function PoseEnabledController(vrGamepad) {
  51481. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  51482. _this.vrGamepad = vrGamepad;
  51483. _this.deviceScaleFactor = 1;
  51484. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51485. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51486. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51487. _this.position = BABYLON.Vector3.Zero();
  51488. _this.rotationQuaternion = new BABYLON.Quaternion();
  51489. _this.devicePosition = BABYLON.Vector3.Zero();
  51490. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51491. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51492. _this._calculatedRotation = new BABYLON.Quaternion();
  51493. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51494. return _this;
  51495. }
  51496. PoseEnabledController.prototype.update = function () {
  51497. _super.prototype.update.call(this);
  51498. var pose = this.vrGamepad.pose;
  51499. this.updateFromDevice(pose);
  51500. if (this._mesh) {
  51501. this._mesh.position.copyFrom(this._calculatedPosition);
  51502. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51503. }
  51504. };
  51505. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51506. if (poseData) {
  51507. this.rawPose = poseData;
  51508. if (poseData.position) {
  51509. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51510. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51511. this.devicePosition.z *= -1;
  51512. }
  51513. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51514. this._calculatedPosition.addInPlace(this.position);
  51515. }
  51516. if (poseData.orientation) {
  51517. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51518. if (this._mesh) {
  51519. if (this._mesh.getScene().useRightHandedSystem) {
  51520. this.deviceRotationQuaternion.z *= -1;
  51521. this.deviceRotationQuaternion.w *= -1;
  51522. }
  51523. else {
  51524. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51525. }
  51526. }
  51527. // if the camera is set, rotate to the camera's rotation
  51528. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51529. }
  51530. }
  51531. };
  51532. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51533. if (this._mesh) {
  51534. this._mesh.parent = undefined;
  51535. }
  51536. this._mesh = mesh;
  51537. if (this._poseControlledCamera) {
  51538. this._mesh.parent = this._poseControlledCamera;
  51539. }
  51540. if (!this._mesh.rotationQuaternion) {
  51541. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51542. }
  51543. };
  51544. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51545. this._poseControlledCamera = camera;
  51546. if (this._mesh) {
  51547. this._mesh.parent = this._poseControlledCamera;
  51548. }
  51549. };
  51550. PoseEnabledController.prototype.dispose = function () {
  51551. if (this._mesh) {
  51552. this._mesh.dispose();
  51553. }
  51554. this._mesh = undefined;
  51555. _super.prototype.dispose.call(this);
  51556. };
  51557. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  51558. get: function () {
  51559. return this._mesh;
  51560. },
  51561. enumerable: true,
  51562. configurable: true
  51563. });
  51564. PoseEnabledController.prototype.getForwardRay = function (length) {
  51565. if (length === void 0) { length = 100; }
  51566. if (!this.mesh) {
  51567. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  51568. }
  51569. var m = this.mesh.getWorldMatrix();
  51570. var origin = m.getTranslation();
  51571. var forward = new BABYLON.Vector3(0, 0, -1);
  51572. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  51573. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  51574. return new BABYLON.Ray(origin, direction, length);
  51575. };
  51576. return PoseEnabledController;
  51577. }(BABYLON.Gamepad));
  51578. BABYLON.PoseEnabledController = PoseEnabledController;
  51579. })(BABYLON || (BABYLON = {}));
  51580. //# sourceMappingURL=babylon.poseEnabledController.js.map
  51581. var BABYLON;
  51582. (function (BABYLON) {
  51583. var WebVRController = (function (_super) {
  51584. __extends(WebVRController, _super);
  51585. function WebVRController(vrGamepad) {
  51586. var _this = _super.call(this, vrGamepad) || this;
  51587. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51588. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51589. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51590. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51591. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51592. _this.pad = { x: 0, y: 0 };
  51593. // avoid GC, store state in a tmp object
  51594. _this._changes = {
  51595. pressChanged: false,
  51596. touchChanged: false,
  51597. valueChanged: false,
  51598. changed: false
  51599. };
  51600. _this._buttons = new Array(vrGamepad.buttons.length);
  51601. _this.hand = vrGamepad.hand;
  51602. return _this;
  51603. }
  51604. WebVRController.prototype.onButtonStateChange = function (callback) {
  51605. this._onButtonStateChange = callback;
  51606. };
  51607. WebVRController.prototype.update = function () {
  51608. _super.prototype.update.call(this);
  51609. for (var index = 0; index < this._buttons.length; index++) {
  51610. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51611. }
  51612. ;
  51613. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51614. this.pad.x = this.leftStick.x;
  51615. this.pad.y = this.leftStick.y;
  51616. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51617. }
  51618. };
  51619. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51620. if (!newState) {
  51621. newState = {
  51622. pressed: false,
  51623. touched: false,
  51624. value: 0
  51625. };
  51626. }
  51627. if (!currentState) {
  51628. this._buttons[buttonIndex] = {
  51629. pressed: newState.pressed,
  51630. touched: newState.touched,
  51631. value: newState.value
  51632. };
  51633. return;
  51634. }
  51635. this._checkChanges(newState, currentState);
  51636. if (this._changes.changed) {
  51637. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51638. this.handleButtonChange(buttonIndex, newState, this._changes);
  51639. }
  51640. this._buttons[buttonIndex].pressed = newState.pressed;
  51641. this._buttons[buttonIndex].touched = newState.touched;
  51642. // oculus triggers are never 0, thou not touched.
  51643. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51644. };
  51645. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51646. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51647. this._changes.touchChanged = newState.touched !== currentState.touched;
  51648. this._changes.valueChanged = newState.value !== currentState.value;
  51649. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51650. return this._changes;
  51651. };
  51652. return WebVRController;
  51653. }(BABYLON.PoseEnabledController));
  51654. BABYLON.WebVRController = WebVRController;
  51655. })(BABYLON || (BABYLON = {}));
  51656. //# sourceMappingURL=babylon.webVRController.js.map
  51657. var BABYLON;
  51658. (function (BABYLON) {
  51659. var OculusTouchController = (function (_super) {
  51660. __extends(OculusTouchController, _super);
  51661. function OculusTouchController(vrGamepad) {
  51662. var _this = _super.call(this, vrGamepad) || this;
  51663. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51664. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51665. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  51666. return _this;
  51667. }
  51668. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51669. var _this = this;
  51670. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51671. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51672. /*
  51673. Parent Mesh name: oculus_touch_left
  51674. - body
  51675. - trigger
  51676. - thumbstick
  51677. - grip
  51678. - button_y
  51679. - button_x
  51680. - button_enter
  51681. */
  51682. _this._defaultModel = newMeshes[1];
  51683. if (meshLoaded) {
  51684. meshLoaded(_this._defaultModel);
  51685. }
  51686. _this.attachToMesh(_this._defaultModel);
  51687. });
  51688. };
  51689. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51690. // helper getters for left and right hand.
  51691. get: function () {
  51692. if (this.hand === 'right') {
  51693. return this.onMainButtonStateChangedObservable;
  51694. }
  51695. else {
  51696. throw new Error('No A button on left hand');
  51697. }
  51698. },
  51699. enumerable: true,
  51700. configurable: true
  51701. });
  51702. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51703. get: function () {
  51704. if (this.hand === 'right') {
  51705. return this.onSecondaryButtonStateChangedObservable;
  51706. }
  51707. else {
  51708. throw new Error('No B button on left hand');
  51709. }
  51710. },
  51711. enumerable: true,
  51712. configurable: true
  51713. });
  51714. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51715. get: function () {
  51716. if (this.hand === 'left') {
  51717. return this.onMainButtonStateChangedObservable;
  51718. }
  51719. else {
  51720. throw new Error('No X button on right hand');
  51721. }
  51722. },
  51723. enumerable: true,
  51724. configurable: true
  51725. });
  51726. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51727. get: function () {
  51728. if (this.hand === 'left') {
  51729. return this.onSecondaryButtonStateChangedObservable;
  51730. }
  51731. else {
  51732. throw new Error('No Y button on right hand');
  51733. }
  51734. },
  51735. enumerable: true,
  51736. configurable: true
  51737. });
  51738. /*
  51739. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51740. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51741. 2) secondary trigger (same)
  51742. 3) A (right) X (left), touch, pressed = value
  51743. 4) B / Y
  51744. 5) thumb rest
  51745. */
  51746. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51747. var notifyObject = state; //{ state: state, changes: changes };
  51748. var triggerDirection = this.hand === 'right' ? -1 : 1;
  51749. switch (buttonIdx) {
  51750. case 0:
  51751. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51752. return;
  51753. case 1:// index trigger
  51754. if (this._defaultModel) {
  51755. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51756. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51757. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51758. }
  51759. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51760. return;
  51761. case 2:// secondary trigger
  51762. if (this._defaultModel) {
  51763. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  51764. }
  51765. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51766. return;
  51767. case 3:
  51768. if (this._defaultModel) {
  51769. if (notifyObject.pressed) {
  51770. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51771. }
  51772. else {
  51773. (this._defaultModel.getChildren()[1]).position.y = 0;
  51774. }
  51775. }
  51776. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51777. return;
  51778. case 4:
  51779. if (this._defaultModel) {
  51780. if (notifyObject.pressed) {
  51781. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51782. }
  51783. else {
  51784. (this._defaultModel.getChildren()[2]).position.y = 0;
  51785. }
  51786. }
  51787. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51788. return;
  51789. case 5:
  51790. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51791. return;
  51792. }
  51793. };
  51794. return OculusTouchController;
  51795. }(BABYLON.WebVRController));
  51796. BABYLON.OculusTouchController = OculusTouchController;
  51797. })(BABYLON || (BABYLON = {}));
  51798. //# sourceMappingURL=babylon.oculusTouchController.js.map
  51799. var BABYLON;
  51800. (function (BABYLON) {
  51801. var ViveController = (function (_super) {
  51802. __extends(ViveController, _super);
  51803. function ViveController(vrGamepad) {
  51804. var _this = _super.call(this, vrGamepad) || this;
  51805. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  51806. return _this;
  51807. }
  51808. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51809. var _this = this;
  51810. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  51811. /*
  51812. Parent Mesh name: ViveWand
  51813. - body
  51814. - r_gripper
  51815. - l_gripper
  51816. - menu_button
  51817. - system_button
  51818. - trackpad
  51819. - trigger
  51820. - LED
  51821. */
  51822. _this._defaultModel = newMeshes[1];
  51823. if (meshLoaded) {
  51824. meshLoaded(_this._defaultModel);
  51825. }
  51826. _this.attachToMesh(_this._defaultModel);
  51827. });
  51828. };
  51829. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  51830. get: function () {
  51831. return this.onMainButtonStateChangedObservable;
  51832. },
  51833. enumerable: true,
  51834. configurable: true
  51835. });
  51836. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  51837. get: function () {
  51838. return this.onMainButtonStateChangedObservable;
  51839. },
  51840. enumerable: true,
  51841. configurable: true
  51842. });
  51843. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  51844. get: function () {
  51845. return this.onSecondaryButtonStateChangedObservable;
  51846. },
  51847. enumerable: true,
  51848. configurable: true
  51849. });
  51850. /**
  51851. * Vive mapping:
  51852. * 0: touchpad
  51853. * 1: trigger
  51854. * 2: left AND right buttons
  51855. * 3: menu button
  51856. */
  51857. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51858. var notifyObject = state; //{ state: state, changes: changes };
  51859. switch (buttonIdx) {
  51860. case 0:
  51861. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51862. return;
  51863. case 1:// index trigger
  51864. if (this._defaultModel) {
  51865. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  51866. }
  51867. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51868. return;
  51869. case 2:// left AND right button
  51870. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51871. return;
  51872. case 3:
  51873. if (this._defaultModel) {
  51874. if (notifyObject.pressed) {
  51875. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51876. }
  51877. else {
  51878. (this._defaultModel.getChildren()[2]).position.y = 0;
  51879. }
  51880. }
  51881. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51882. return;
  51883. }
  51884. };
  51885. return ViveController;
  51886. }(BABYLON.WebVRController));
  51887. BABYLON.ViveController = ViveController;
  51888. })(BABYLON || (BABYLON = {}));
  51889. //# sourceMappingURL=babylon.viveController.js.map
  51890. var BABYLON;
  51891. (function (BABYLON) {
  51892. var GenericController = (function (_super) {
  51893. __extends(GenericController, _super);
  51894. function GenericController(vrGamepad) {
  51895. return _super.call(this, vrGamepad) || this;
  51896. }
  51897. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51898. var _this = this;
  51899. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "genericvrcontroller.babylon", scene, function (newMeshes) {
  51900. _this._defaultModel = newMeshes[1];
  51901. if (meshLoaded) {
  51902. meshLoaded(_this._defaultModel);
  51903. }
  51904. _this.attachToMesh(_this._defaultModel);
  51905. });
  51906. };
  51907. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51908. console.log("Button id: " + buttonIdx + "state: ");
  51909. console.dir(state);
  51910. };
  51911. return GenericController;
  51912. }(BABYLON.WebVRController));
  51913. BABYLON.GenericController = GenericController;
  51914. })(BABYLON || (BABYLON = {}));
  51915. //# sourceMappingURL=babylon.genericController.js.map
  51916. /// <reference path="babylon.targetCamera.ts" />
  51917. var BABYLON;
  51918. (function (BABYLON) {
  51919. var FollowCamera = (function (_super) {
  51920. __extends(FollowCamera, _super);
  51921. function FollowCamera(name, position, scene, lockedTarget) {
  51922. var _this = _super.call(this, name, position, scene) || this;
  51923. _this.radius = 12;
  51924. _this.rotationOffset = 0;
  51925. _this.heightOffset = 4;
  51926. _this.cameraAcceleration = 0.05;
  51927. _this.maxCameraSpeed = 20;
  51928. _this.lockedTarget = lockedTarget;
  51929. return _this;
  51930. }
  51931. FollowCamera.prototype.getRadians = function (degrees) {
  51932. return degrees * Math.PI / 180;
  51933. };
  51934. FollowCamera.prototype.follow = function (cameraTarget) {
  51935. if (!cameraTarget)
  51936. return;
  51937. var yRotation;
  51938. if (cameraTarget.rotationQuaternion) {
  51939. var rotMatrix = new BABYLON.Matrix();
  51940. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  51941. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  51942. }
  51943. else {
  51944. yRotation = cameraTarget.rotation.y;
  51945. }
  51946. var radians = this.getRadians(this.rotationOffset) + yRotation;
  51947. var targetPosition = cameraTarget.getAbsolutePosition();
  51948. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  51949. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  51950. var dx = targetX - this.position.x;
  51951. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  51952. var dz = (targetZ) - this.position.z;
  51953. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  51954. var vy = dy * this.cameraAcceleration;
  51955. var vz = dz * this.cameraAcceleration * 2;
  51956. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  51957. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51958. }
  51959. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  51960. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51961. }
  51962. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  51963. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51964. }
  51965. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  51966. this.setTarget(targetPosition);
  51967. };
  51968. FollowCamera.prototype._checkInputs = function () {
  51969. _super.prototype._checkInputs.call(this);
  51970. this.follow(this.lockedTarget);
  51971. };
  51972. FollowCamera.prototype.getClassName = function () {
  51973. return "FollowCamera";
  51974. };
  51975. __decorate([
  51976. BABYLON.serialize()
  51977. ], FollowCamera.prototype, "radius", void 0);
  51978. __decorate([
  51979. BABYLON.serialize()
  51980. ], FollowCamera.prototype, "rotationOffset", void 0);
  51981. __decorate([
  51982. BABYLON.serialize()
  51983. ], FollowCamera.prototype, "heightOffset", void 0);
  51984. __decorate([
  51985. BABYLON.serialize()
  51986. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  51987. __decorate([
  51988. BABYLON.serialize()
  51989. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  51990. __decorate([
  51991. BABYLON.serializeAsMeshReference("lockedTargetId")
  51992. ], FollowCamera.prototype, "lockedTarget", void 0);
  51993. return FollowCamera;
  51994. }(BABYLON.TargetCamera));
  51995. BABYLON.FollowCamera = FollowCamera;
  51996. var ArcFollowCamera = (function (_super) {
  51997. __extends(ArcFollowCamera, _super);
  51998. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  51999. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  52000. _this.alpha = alpha;
  52001. _this.beta = beta;
  52002. _this.radius = radius;
  52003. _this.target = target;
  52004. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  52005. _this.follow();
  52006. return _this;
  52007. }
  52008. ArcFollowCamera.prototype.follow = function () {
  52009. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  52010. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  52011. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  52012. var targetPosition = this.target.getAbsolutePosition();
  52013. this.position = targetPosition.add(this._cartesianCoordinates);
  52014. this.setTarget(targetPosition);
  52015. };
  52016. ArcFollowCamera.prototype._checkInputs = function () {
  52017. _super.prototype._checkInputs.call(this);
  52018. this.follow();
  52019. };
  52020. ArcFollowCamera.prototype.getClassName = function () {
  52021. return "ArcFollowCamera";
  52022. };
  52023. return ArcFollowCamera;
  52024. }(BABYLON.TargetCamera));
  52025. BABYLON.ArcFollowCamera = ArcFollowCamera;
  52026. })(BABYLON || (BABYLON = {}));
  52027. //# sourceMappingURL=babylon.followCamera.js.map
  52028. /// <reference path="babylon.touchCamera.ts" />
  52029. var BABYLON;
  52030. (function (BABYLON) {
  52031. // We're mainly based on the logic defined into the FreeCamera code
  52032. var UniversalCamera = (function (_super) {
  52033. __extends(UniversalCamera, _super);
  52034. //-- end properties for backward compatibility for inputs
  52035. function UniversalCamera(name, position, scene) {
  52036. var _this = _super.call(this, name, position, scene) || this;
  52037. _this.inputs.addGamepad();
  52038. return _this;
  52039. }
  52040. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52041. //-- Begin properties for backward compatibility for inputs
  52042. get: function () {
  52043. var gamepad = this.inputs.attached["gamepad"];
  52044. if (gamepad)
  52045. return gamepad.gamepadAngularSensibility;
  52046. },
  52047. set: function (value) {
  52048. var gamepad = this.inputs.attached["gamepad"];
  52049. if (gamepad)
  52050. gamepad.gamepadAngularSensibility = value;
  52051. },
  52052. enumerable: true,
  52053. configurable: true
  52054. });
  52055. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52056. get: function () {
  52057. var gamepad = this.inputs.attached["gamepad"];
  52058. if (gamepad)
  52059. return gamepad.gamepadMoveSensibility;
  52060. },
  52061. set: function (value) {
  52062. var gamepad = this.inputs.attached["gamepad"];
  52063. if (gamepad)
  52064. gamepad.gamepadMoveSensibility = value;
  52065. },
  52066. enumerable: true,
  52067. configurable: true
  52068. });
  52069. UniversalCamera.prototype.getClassName = function () {
  52070. return "UniversalCamera";
  52071. };
  52072. return UniversalCamera;
  52073. }(BABYLON.TouchCamera));
  52074. BABYLON.UniversalCamera = UniversalCamera;
  52075. })(BABYLON || (BABYLON = {}));
  52076. //# sourceMappingURL=babylon.universalCamera.js.map
  52077. /// <reference path="babylon.universalCamera.ts" />
  52078. var BABYLON;
  52079. (function (BABYLON) {
  52080. // We're mainly based on the logic defined into the FreeCamera code
  52081. var GamepadCamera = (function (_super) {
  52082. __extends(GamepadCamera, _super);
  52083. //-- end properties for backward compatibility for inputs
  52084. function GamepadCamera(name, position, scene) {
  52085. return _super.call(this, name, position, scene) || this;
  52086. }
  52087. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  52088. //-- Begin properties for backward compatibility for inputs
  52089. get: function () {
  52090. var gamepad = this.inputs.attached["gamepad"];
  52091. if (gamepad)
  52092. return gamepad.gamepadAngularSensibility;
  52093. },
  52094. set: function (value) {
  52095. var gamepad = this.inputs.attached["gamepad"];
  52096. if (gamepad)
  52097. gamepad.gamepadAngularSensibility = value;
  52098. },
  52099. enumerable: true,
  52100. configurable: true
  52101. });
  52102. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  52103. get: function () {
  52104. var gamepad = this.inputs.attached["gamepad"];
  52105. if (gamepad)
  52106. return gamepad.gamepadMoveSensibility;
  52107. },
  52108. set: function (value) {
  52109. var gamepad = this.inputs.attached["gamepad"];
  52110. if (gamepad)
  52111. gamepad.gamepadMoveSensibility = value;
  52112. },
  52113. enumerable: true,
  52114. configurable: true
  52115. });
  52116. GamepadCamera.prototype.getClassName = function () {
  52117. return "GamepadCamera";
  52118. };
  52119. return GamepadCamera;
  52120. }(BABYLON.UniversalCamera));
  52121. BABYLON.GamepadCamera = GamepadCamera;
  52122. })(BABYLON || (BABYLON = {}));
  52123. //# sourceMappingURL=babylon.gamepadCamera.js.map
  52124. var BABYLON;
  52125. (function (BABYLON) {
  52126. var PostProcessRenderPipelineManager = (function () {
  52127. function PostProcessRenderPipelineManager() {
  52128. this._renderPipelines = {};
  52129. }
  52130. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  52131. this._renderPipelines[renderPipeline._name] = renderPipeline;
  52132. };
  52133. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  52134. var renderPipeline = this._renderPipelines[renderPipelineName];
  52135. if (!renderPipeline) {
  52136. return;
  52137. }
  52138. renderPipeline._attachCameras(cameras, unique);
  52139. };
  52140. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  52141. var renderPipeline = this._renderPipelines[renderPipelineName];
  52142. if (!renderPipeline) {
  52143. return;
  52144. }
  52145. renderPipeline._detachCameras(cameras);
  52146. };
  52147. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52148. var renderPipeline = this._renderPipelines[renderPipelineName];
  52149. if (!renderPipeline) {
  52150. return;
  52151. }
  52152. renderPipeline._enableEffect(renderEffectName, cameras);
  52153. };
  52154. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52155. var renderPipeline = this._renderPipelines[renderPipelineName];
  52156. if (!renderPipeline) {
  52157. return;
  52158. }
  52159. renderPipeline._disableEffect(renderEffectName, cameras);
  52160. };
  52161. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  52162. var renderPipeline = this._renderPipelines[renderPipelineName];
  52163. if (!renderPipeline) {
  52164. return;
  52165. }
  52166. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  52167. };
  52168. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  52169. var renderPipeline = this._renderPipelines[renderPipelineName];
  52170. if (!renderPipeline) {
  52171. return;
  52172. }
  52173. renderPipeline._disableDisplayOnlyPass(cameras);
  52174. };
  52175. PostProcessRenderPipelineManager.prototype.update = function () {
  52176. for (var renderPipelineName in this._renderPipelines) {
  52177. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52178. var pipeline = this._renderPipelines[renderPipelineName];
  52179. if (!pipeline.isSupported) {
  52180. pipeline.dispose();
  52181. delete this._renderPipelines[renderPipelineName];
  52182. }
  52183. else {
  52184. pipeline._update();
  52185. }
  52186. }
  52187. }
  52188. };
  52189. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  52190. for (var renderPipelineName in this._renderPipelines) {
  52191. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52192. var pipeline = this._renderPipelines[renderPipelineName];
  52193. pipeline._rebuild();
  52194. }
  52195. }
  52196. };
  52197. PostProcessRenderPipelineManager.prototype.dispose = function () {
  52198. for (var renderPipelineName in this._renderPipelines) {
  52199. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52200. var pipeline = this._renderPipelines[renderPipelineName];
  52201. pipeline.dispose();
  52202. }
  52203. }
  52204. };
  52205. return PostProcessRenderPipelineManager;
  52206. }());
  52207. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  52208. })(BABYLON || (BABYLON = {}));
  52209. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  52210. var BABYLON;
  52211. (function (BABYLON) {
  52212. var PostProcessRenderPass = (function () {
  52213. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  52214. this._enabled = true;
  52215. this._refCount = 0;
  52216. this._name = name;
  52217. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  52218. this.setRenderList(renderList);
  52219. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  52220. this._renderTexture.onAfterRenderObservable.add(afterRender);
  52221. this._scene = scene;
  52222. this._renderList = renderList;
  52223. }
  52224. // private
  52225. PostProcessRenderPass.prototype._incRefCount = function () {
  52226. if (this._refCount === 0) {
  52227. this._scene.customRenderTargets.push(this._renderTexture);
  52228. }
  52229. return ++this._refCount;
  52230. };
  52231. PostProcessRenderPass.prototype._decRefCount = function () {
  52232. this._refCount--;
  52233. if (this._refCount <= 0) {
  52234. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  52235. }
  52236. return this._refCount;
  52237. };
  52238. PostProcessRenderPass.prototype._update = function () {
  52239. this.setRenderList(this._renderList);
  52240. };
  52241. // public
  52242. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  52243. this._renderTexture.renderList = renderList;
  52244. };
  52245. PostProcessRenderPass.prototype.getRenderTexture = function () {
  52246. return this._renderTexture;
  52247. };
  52248. return PostProcessRenderPass;
  52249. }());
  52250. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  52251. })(BABYLON || (BABYLON = {}));
  52252. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  52253. var BABYLON;
  52254. (function (BABYLON) {
  52255. var PostProcessRenderEffect = (function () {
  52256. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  52257. this._engine = engine;
  52258. this._name = name;
  52259. this._singleInstance = singleInstance || true;
  52260. this._getPostProcess = getPostProcess;
  52261. this._cameras = [];
  52262. this._indicesForCamera = [];
  52263. this._postProcesses = {};
  52264. this._renderPasses = {};
  52265. this._renderEffectAsPasses = {};
  52266. }
  52267. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  52268. get: function () {
  52269. for (var index in this._postProcesses) {
  52270. if (!this._postProcesses[index].isSupported) {
  52271. return false;
  52272. }
  52273. }
  52274. return true;
  52275. },
  52276. enumerable: true,
  52277. configurable: true
  52278. });
  52279. PostProcessRenderEffect.prototype._update = function () {
  52280. for (var renderPassName in this._renderPasses) {
  52281. this._renderPasses[renderPassName]._update();
  52282. }
  52283. };
  52284. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  52285. this._renderPasses[renderPass._name] = renderPass;
  52286. this._linkParameters();
  52287. };
  52288. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  52289. delete this._renderPasses[renderPass._name];
  52290. this._linkParameters();
  52291. };
  52292. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  52293. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  52294. this._linkParameters();
  52295. };
  52296. PostProcessRenderEffect.prototype.getPass = function (passName) {
  52297. for (var renderPassName in this._renderPasses) {
  52298. if (renderPassName === passName) {
  52299. return this._renderPasses[passName];
  52300. }
  52301. }
  52302. };
  52303. PostProcessRenderEffect.prototype.emptyPasses = function () {
  52304. this._renderPasses = {};
  52305. this._linkParameters();
  52306. };
  52307. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  52308. var cameraKey;
  52309. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52310. for (var i = 0; i < _cam.length; i++) {
  52311. var camera = _cam[i];
  52312. var cameraName = camera.name;
  52313. if (this._singleInstance) {
  52314. cameraKey = 0;
  52315. }
  52316. else {
  52317. cameraKey = cameraName;
  52318. }
  52319. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  52320. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  52321. if (!this._indicesForCamera[cameraName]) {
  52322. this._indicesForCamera[cameraName] = [];
  52323. }
  52324. this._indicesForCamera[cameraName].push(index);
  52325. if (this._cameras.indexOf(camera) === -1) {
  52326. this._cameras[cameraName] = camera;
  52327. }
  52328. for (var passName in this._renderPasses) {
  52329. this._renderPasses[passName]._incRefCount();
  52330. }
  52331. }
  52332. this._linkParameters();
  52333. };
  52334. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  52335. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52336. for (var i = 0; i < _cam.length; i++) {
  52337. var camera = _cam[i];
  52338. var cameraName = camera.name;
  52339. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  52340. var index = this._cameras.indexOf(cameraName);
  52341. this._indicesForCamera.splice(index, 1);
  52342. this._cameras.splice(index, 1);
  52343. for (var passName in this._renderPasses) {
  52344. this._renderPasses[passName]._decRefCount();
  52345. }
  52346. }
  52347. };
  52348. PostProcessRenderEffect.prototype._enable = function (cameras) {
  52349. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52350. for (var i = 0; i < _cam.length; i++) {
  52351. var camera = _cam[i];
  52352. var cameraName = camera.name;
  52353. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  52354. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  52355. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  52356. }
  52357. }
  52358. for (var passName in this._renderPasses) {
  52359. this._renderPasses[passName]._incRefCount();
  52360. }
  52361. }
  52362. };
  52363. PostProcessRenderEffect.prototype._disable = function (cameras) {
  52364. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52365. for (var i = 0; i < _cam.length; i++) {
  52366. var camera = _cam[i];
  52367. var cameraName = camera.Name;
  52368. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  52369. for (var passName in this._renderPasses) {
  52370. this._renderPasses[passName]._decRefCount();
  52371. }
  52372. }
  52373. };
  52374. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  52375. if (this._singleInstance) {
  52376. return this._postProcesses[0];
  52377. }
  52378. else {
  52379. return this._postProcesses[camera.name];
  52380. }
  52381. };
  52382. PostProcessRenderEffect.prototype._linkParameters = function () {
  52383. var _this = this;
  52384. for (var index in this._postProcesses) {
  52385. if (this.applyParameters) {
  52386. this.applyParameters(this._postProcesses[index]);
  52387. }
  52388. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  52389. _this._linkTextures(effect);
  52390. });
  52391. }
  52392. };
  52393. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  52394. for (var renderPassName in this._renderPasses) {
  52395. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  52396. }
  52397. for (var renderEffectName in this._renderEffectAsPasses) {
  52398. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  52399. }
  52400. };
  52401. return PostProcessRenderEffect;
  52402. }());
  52403. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  52404. })(BABYLON || (BABYLON = {}));
  52405. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  52406. var BABYLON;
  52407. (function (BABYLON) {
  52408. var PostProcessRenderPipeline = (function () {
  52409. function PostProcessRenderPipeline(engine, name) {
  52410. this._engine = engine;
  52411. this._name = name;
  52412. this._renderEffects = new Array();
  52413. this._renderEffectsForIsolatedPass = new Array();
  52414. this._cameras = [];
  52415. }
  52416. PostProcessRenderPipeline.prototype.getClassName = function () {
  52417. return "PostProcessRenderPipeline";
  52418. };
  52419. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  52420. get: function () {
  52421. for (var renderEffectName in this._renderEffects) {
  52422. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52423. if (!this._renderEffects[renderEffectName].isSupported) {
  52424. return false;
  52425. }
  52426. }
  52427. }
  52428. return true;
  52429. },
  52430. enumerable: true,
  52431. configurable: true
  52432. });
  52433. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  52434. this._renderEffects[renderEffect._name] = renderEffect;
  52435. };
  52436. // private
  52437. PostProcessRenderPipeline.prototype._rebuild = function () {
  52438. };
  52439. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  52440. var renderEffects = this._renderEffects[renderEffectName];
  52441. if (!renderEffects) {
  52442. return;
  52443. }
  52444. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  52445. };
  52446. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  52447. var renderEffects = this._renderEffects[renderEffectName];
  52448. if (!renderEffects) {
  52449. return;
  52450. }
  52451. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  52452. };
  52453. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  52454. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52455. var indicesToDelete = [];
  52456. var i;
  52457. for (i = 0; i < _cam.length; i++) {
  52458. var camera = _cam[i];
  52459. var cameraName = camera.name;
  52460. if (this._cameras.indexOf(camera) === -1) {
  52461. this._cameras[cameraName] = camera;
  52462. }
  52463. else if (unique) {
  52464. indicesToDelete.push(i);
  52465. }
  52466. }
  52467. for (i = 0; i < indicesToDelete.length; i++) {
  52468. cameras.splice(indicesToDelete[i], 1);
  52469. }
  52470. for (var renderEffectName in this._renderEffects) {
  52471. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52472. this._renderEffects[renderEffectName]._attachCameras(_cam);
  52473. }
  52474. }
  52475. };
  52476. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  52477. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52478. for (var renderEffectName in this._renderEffects) {
  52479. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52480. this._renderEffects[renderEffectName]._detachCameras(_cam);
  52481. }
  52482. }
  52483. for (var i = 0; i < _cam.length; i++) {
  52484. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  52485. }
  52486. };
  52487. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  52488. var _this = this;
  52489. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52490. var pass = null;
  52491. var renderEffectName;
  52492. for (renderEffectName in this._renderEffects) {
  52493. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52494. pass = this._renderEffects[renderEffectName].getPass(passName);
  52495. if (pass != null) {
  52496. break;
  52497. }
  52498. }
  52499. }
  52500. if (pass === null) {
  52501. return;
  52502. }
  52503. for (renderEffectName in this._renderEffects) {
  52504. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52505. this._renderEffects[renderEffectName]._disable(_cam);
  52506. }
  52507. }
  52508. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  52509. for (var i = 0; i < _cam.length; i++) {
  52510. var camera = _cam[i];
  52511. var cameraName = camera.name;
  52512. 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); });
  52513. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  52514. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  52515. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  52516. }
  52517. };
  52518. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  52519. var _this = this;
  52520. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52521. for (var i = 0; i < _cam.length; i++) {
  52522. var camera = _cam[i];
  52523. var cameraName = camera.name;
  52524. 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); });
  52525. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  52526. }
  52527. for (var renderEffectName in this._renderEffects) {
  52528. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52529. this._renderEffects[renderEffectName]._enable(_cam);
  52530. }
  52531. }
  52532. };
  52533. PostProcessRenderPipeline.prototype._update = function () {
  52534. for (var renderEffectName in this._renderEffects) {
  52535. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52536. this._renderEffects[renderEffectName]._update();
  52537. }
  52538. }
  52539. for (var i = 0; i < this._cameras.length; i++) {
  52540. var cameraName = this._cameras[i].name;
  52541. if (this._renderEffectsForIsolatedPass[cameraName]) {
  52542. this._renderEffectsForIsolatedPass[cameraName]._update();
  52543. }
  52544. }
  52545. };
  52546. PostProcessRenderPipeline.prototype._reset = function () {
  52547. this._renderEffects = new Array();
  52548. this._renderEffectsForIsolatedPass = new Array();
  52549. };
  52550. PostProcessRenderPipeline.prototype.dispose = function () {
  52551. // Must be implemented by children
  52552. };
  52553. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  52554. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  52555. __decorate([
  52556. BABYLON.serialize()
  52557. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  52558. return PostProcessRenderPipeline;
  52559. }());
  52560. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  52561. })(BABYLON || (BABYLON = {}));
  52562. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  52563. var BABYLON;
  52564. (function (BABYLON) {
  52565. var DepthRenderer = (function () {
  52566. function DepthRenderer(scene, type) {
  52567. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  52568. var _this = this;
  52569. this._viewMatrix = BABYLON.Matrix.Zero();
  52570. this._projectionMatrix = BABYLON.Matrix.Zero();
  52571. this._transformMatrix = BABYLON.Matrix.Zero();
  52572. this._worldViewProjection = BABYLON.Matrix.Zero();
  52573. this._scene = scene;
  52574. var engine = scene.getEngine();
  52575. // Render target
  52576. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  52577. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52578. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52579. this._depthMap.refreshRate = 1;
  52580. this._depthMap.renderParticles = false;
  52581. this._depthMap.renderList = null;
  52582. // set default depth value to 1.0 (far away)
  52583. this._depthMap.onClearObservable.add(function (engine) {
  52584. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52585. });
  52586. // Custom render function
  52587. var renderSubMesh = function (subMesh) {
  52588. var mesh = subMesh.getRenderingMesh();
  52589. var scene = _this._scene;
  52590. var engine = scene.getEngine();
  52591. // Culling
  52592. engine.setState(subMesh.getMaterial().backFaceCulling);
  52593. // Managing instances
  52594. var batch = mesh._getInstancesRenderList(subMesh._id);
  52595. if (batch.mustReturn) {
  52596. return;
  52597. }
  52598. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52599. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52600. engine.enableEffect(_this._effect);
  52601. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52602. var material = subMesh.getMaterial();
  52603. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52604. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  52605. // Alpha test
  52606. if (material && material.needAlphaTesting()) {
  52607. var alphaTexture = material.getAlphaTestTexture();
  52608. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52609. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52610. }
  52611. // Bones
  52612. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52613. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52614. }
  52615. // Draw
  52616. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52617. }
  52618. };
  52619. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52620. var index;
  52621. if (depthOnlySubMeshes.length) {
  52622. engine.setColorWrite(false);
  52623. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52624. renderSubMesh(depthOnlySubMeshes.data[index]);
  52625. }
  52626. engine.setColorWrite(true);
  52627. }
  52628. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52629. renderSubMesh(opaqueSubMeshes.data[index]);
  52630. }
  52631. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52632. renderSubMesh(alphaTestSubMeshes.data[index]);
  52633. }
  52634. };
  52635. }
  52636. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  52637. var material = subMesh.getMaterial();
  52638. if (material.disableDepthWrite) {
  52639. return false;
  52640. }
  52641. var defines = [];
  52642. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52643. var mesh = subMesh.getMesh();
  52644. var scene = mesh.getScene();
  52645. // Alpha test
  52646. if (material && material.needAlphaTesting()) {
  52647. defines.push("#define ALPHATEST");
  52648. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52649. attribs.push(BABYLON.VertexBuffer.UVKind);
  52650. defines.push("#define UV1");
  52651. }
  52652. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52653. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52654. defines.push("#define UV2");
  52655. }
  52656. }
  52657. // Bones
  52658. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52659. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52660. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52661. if (mesh.numBoneInfluencers > 4) {
  52662. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52663. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52664. }
  52665. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52666. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52667. }
  52668. else {
  52669. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52670. }
  52671. // Instances
  52672. if (useInstances) {
  52673. defines.push("#define INSTANCES");
  52674. attribs.push("world0");
  52675. attribs.push("world1");
  52676. attribs.push("world2");
  52677. attribs.push("world3");
  52678. }
  52679. // Get correct effect
  52680. var join = defines.join("\n");
  52681. if (this._cachedDefines !== join) {
  52682. this._cachedDefines = join;
  52683. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  52684. }
  52685. return this._effect.isReady();
  52686. };
  52687. DepthRenderer.prototype.getDepthMap = function () {
  52688. return this._depthMap;
  52689. };
  52690. // Methods
  52691. DepthRenderer.prototype.dispose = function () {
  52692. this._depthMap.dispose();
  52693. };
  52694. return DepthRenderer;
  52695. }());
  52696. BABYLON.DepthRenderer = DepthRenderer;
  52697. })(BABYLON || (BABYLON = {}));
  52698. //# sourceMappingURL=babylon.depthRenderer.js.map
  52699. var BABYLON;
  52700. (function (BABYLON) {
  52701. var SSAORenderingPipeline = (function (_super) {
  52702. __extends(SSAORenderingPipeline, _super);
  52703. /**
  52704. * @constructor
  52705. * @param {string} name - The rendering pipeline name
  52706. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52707. * @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 }
  52708. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52709. */
  52710. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52711. var _this = _super.call(this, scene.getEngine(), name) || this;
  52712. // Members
  52713. /**
  52714. * The PassPostProcess id in the pipeline that contains the original scene color
  52715. * @type {string}
  52716. */
  52717. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52718. /**
  52719. * The SSAO PostProcess id in the pipeline
  52720. * @type {string}
  52721. */
  52722. _this.SSAORenderEffect = "SSAORenderEffect";
  52723. /**
  52724. * The horizontal blur PostProcess id in the pipeline
  52725. * @type {string}
  52726. */
  52727. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52728. /**
  52729. * The vertical blur PostProcess id in the pipeline
  52730. * @type {string}
  52731. */
  52732. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52733. /**
  52734. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52735. * @type {string}
  52736. */
  52737. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52738. /**
  52739. * The output strength of the SSAO post-process. Default value is 1.0.
  52740. * @type {number}
  52741. */
  52742. _this.totalStrength = 1.0;
  52743. /**
  52744. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52745. * @type {number}
  52746. */
  52747. _this.radius = 0.0001;
  52748. /**
  52749. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52750. * Must not be equal to fallOff and superior to fallOff.
  52751. * Default value is 0.975
  52752. * @type {number}
  52753. */
  52754. _this.area = 0.0075;
  52755. /**
  52756. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52757. * Must not be equal to area and inferior to area.
  52758. * Default value is 0.0
  52759. * @type {number}
  52760. */
  52761. _this.fallOff = 0.000001;
  52762. /**
  52763. * The base color of the SSAO post-process
  52764. * The final result is "base + ssao" between [0, 1]
  52765. * @type {number}
  52766. */
  52767. _this.base = 0.5;
  52768. _this._firstUpdate = true;
  52769. _this._scene = scene;
  52770. // Set up assets
  52771. _this._createRandomTexture();
  52772. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52773. var ssaoRatio = ratio.ssaoRatio || ratio;
  52774. var combineRatio = ratio.combineRatio || ratio;
  52775. _this._ratio = {
  52776. ssaoRatio: ssaoRatio,
  52777. combineRatio: combineRatio
  52778. };
  52779. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52780. _this._createSSAOPostProcess(ssaoRatio);
  52781. _this._createBlurPostProcess(ssaoRatio);
  52782. _this._createSSAOCombinePostProcess(combineRatio);
  52783. // Set up pipeline
  52784. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52785. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52786. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52787. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52788. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52789. // Finish
  52790. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52791. if (cameras)
  52792. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52793. return _this;
  52794. }
  52795. // Public Methods
  52796. /**
  52797. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52798. */
  52799. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52800. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52801. for (var i = 0; i < this._scene.cameras.length; i++) {
  52802. var camera = this._scene.cameras[i];
  52803. this._originalColorPostProcess.dispose(camera);
  52804. this._ssaoPostProcess.dispose(camera);
  52805. this._blurHPostProcess.dispose(camera);
  52806. this._blurVPostProcess.dispose(camera);
  52807. this._ssaoCombinePostProcess.dispose(camera);
  52808. }
  52809. this._randomTexture.dispose();
  52810. if (disableDepthRender)
  52811. this._scene.disableDepthRenderer();
  52812. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52813. _super.prototype.dispose.call(this);
  52814. };
  52815. // Private Methods
  52816. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52817. var _this = this;
  52818. /*
  52819. var samplerOffsets = [
  52820. -8.0, -6.0, -4.0, -2.0,
  52821. 0.0,
  52822. 2.0, 4.0, 6.0, 8.0
  52823. ];
  52824. */
  52825. var samples = 16;
  52826. var samplerOffsets = [];
  52827. for (var i = -8; i < 8; i++) {
  52828. samplerOffsets.push(i * 2);
  52829. }
  52830. 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");
  52831. this._blurHPostProcess.onApply = function (effect) {
  52832. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52833. effect.setTexture("depthSampler", _this._depthTexture);
  52834. if (_this._firstUpdate) {
  52835. effect.setArray("samplerOffsets", samplerOffsets);
  52836. }
  52837. };
  52838. 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");
  52839. this._blurVPostProcess.onApply = function (effect) {
  52840. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52841. effect.setTexture("depthSampler", _this._depthTexture);
  52842. if (_this._firstUpdate) {
  52843. effect.setArray("samplerOffsets", samplerOffsets);
  52844. _this._firstUpdate = false;
  52845. }
  52846. };
  52847. };
  52848. SSAORenderingPipeline.prototype._rebuild = function () {
  52849. this._firstUpdate = true;
  52850. _super.prototype._rebuild.call(this);
  52851. };
  52852. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52853. var _this = this;
  52854. var numSamples = 16;
  52855. var sampleSphere = [
  52856. 0.5381, 0.1856, -0.4319,
  52857. 0.1379, 0.2486, 0.4430,
  52858. 0.3371, 0.5679, -0.0057,
  52859. -0.6999, -0.0451, -0.0019,
  52860. 0.0689, -0.1598, -0.8547,
  52861. 0.0560, 0.0069, -0.1843,
  52862. -0.0146, 0.1402, 0.0762,
  52863. 0.0100, -0.1924, -0.0344,
  52864. -0.3577, -0.5301, -0.4358,
  52865. -0.3169, 0.1063, 0.0158,
  52866. 0.0103, -0.5869, 0.0046,
  52867. -0.0897, -0.4940, 0.3287,
  52868. 0.7119, -0.0154, -0.0918,
  52869. -0.0533, 0.0596, -0.5411,
  52870. 0.0352, -0.0631, 0.5460,
  52871. -0.4776, 0.2847, -0.0271
  52872. ];
  52873. var samplesFactor = 1.0 / numSamples;
  52874. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52875. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52876. "area", "fallOff", "base", "range", "viewport"
  52877. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52878. var viewport = new BABYLON.Vector2(0, 0);
  52879. this._ssaoPostProcess.onApply = function (effect) {
  52880. if (_this._firstUpdate) {
  52881. effect.setArray3("sampleSphere", sampleSphere);
  52882. effect.setFloat("samplesFactor", samplesFactor);
  52883. effect.setFloat("randTextureTiles", 4.0);
  52884. }
  52885. effect.setFloat("totalStrength", _this.totalStrength);
  52886. effect.setFloat("radius", _this.radius);
  52887. effect.setFloat("area", _this.area);
  52888. effect.setFloat("fallOff", _this.fallOff);
  52889. effect.setFloat("base", _this.base);
  52890. effect.setTexture("textureSampler", _this._depthTexture);
  52891. effect.setTexture("randomSampler", _this._randomTexture);
  52892. };
  52893. };
  52894. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52895. var _this = this;
  52896. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52897. this._ssaoCombinePostProcess.onApply = function (effect) {
  52898. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52899. };
  52900. };
  52901. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52902. var size = 512;
  52903. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52904. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52905. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52906. var context = this._randomTexture.getContext();
  52907. var rand = function (min, max) {
  52908. return Math.random() * (max - min) + min;
  52909. };
  52910. var randVector = BABYLON.Vector3.Zero();
  52911. for (var x = 0; x < size; x++) {
  52912. for (var y = 0; y < size; y++) {
  52913. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52914. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52915. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52916. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52917. context.fillRect(x, y, 1, 1);
  52918. }
  52919. }
  52920. this._randomTexture.update(false);
  52921. };
  52922. __decorate([
  52923. BABYLON.serialize()
  52924. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52925. __decorate([
  52926. BABYLON.serialize()
  52927. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52928. __decorate([
  52929. BABYLON.serialize()
  52930. ], SSAORenderingPipeline.prototype, "area", void 0);
  52931. __decorate([
  52932. BABYLON.serialize()
  52933. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52934. __decorate([
  52935. BABYLON.serialize()
  52936. ], SSAORenderingPipeline.prototype, "base", void 0);
  52937. __decorate([
  52938. BABYLON.serialize()
  52939. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52940. return SSAORenderingPipeline;
  52941. }(BABYLON.PostProcessRenderPipeline));
  52942. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52943. })(BABYLON || (BABYLON = {}));
  52944. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  52945. var BABYLON;
  52946. (function (BABYLON) {
  52947. var SSAO2RenderingPipeline = (function (_super) {
  52948. __extends(SSAO2RenderingPipeline, _super);
  52949. /**
  52950. * @constructor
  52951. * @param {string} name - The rendering pipeline name
  52952. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52953. * @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 }
  52954. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52955. */
  52956. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  52957. var _this = _super.call(this, scene.getEngine(), name) || this;
  52958. // Members
  52959. /**
  52960. * The PassPostProcess id in the pipeline that contains the original scene color
  52961. * @type {string}
  52962. */
  52963. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52964. /**
  52965. * The SSAO PostProcess id in the pipeline
  52966. * @type {string}
  52967. */
  52968. _this.SSAORenderEffect = "SSAORenderEffect";
  52969. /**
  52970. * The horizontal blur PostProcess id in the pipeline
  52971. * @type {string}
  52972. */
  52973. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52974. /**
  52975. * The vertical blur PostProcess id in the pipeline
  52976. * @type {string}
  52977. */
  52978. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52979. /**
  52980. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52981. * @type {string}
  52982. */
  52983. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52984. /**
  52985. * The output strength of the SSAO post-process. Default value is 1.0.
  52986. * @type {number}
  52987. */
  52988. _this.totalStrength = 1.0;
  52989. /**
  52990. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  52991. * @type {number}
  52992. */
  52993. _this.maxZ = 100.0;
  52994. /**
  52995. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  52996. * @type {number}
  52997. */
  52998. _this.minZAspect = 0.2;
  52999. /**
  53000. * Number of samples used for the SSAO calculations. Default value is 8
  53001. * @type {number}
  53002. */
  53003. _this._samples = 8;
  53004. /**
  53005. * Are we using bilateral blur ?
  53006. * @type {boolean}
  53007. */
  53008. _this._expensiveBlur = true;
  53009. /**
  53010. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  53011. * @type {number}
  53012. */
  53013. _this.radius = 2.0;
  53014. /**
  53015. * The base color of the SSAO post-process
  53016. * The final result is "base + ssao" between [0, 1]
  53017. * @type {number}
  53018. */
  53019. _this.base = 0.1;
  53020. _this._firstUpdate = true;
  53021. _this._scene = scene;
  53022. if (!_this.isSupported) {
  53023. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  53024. return _this;
  53025. }
  53026. var ssaoRatio = ratio.ssaoRatio || ratio;
  53027. var blurRatio = ratio.blurRatio || ratio;
  53028. _this._ratio = {
  53029. ssaoRatio: ssaoRatio,
  53030. blurRatio: blurRatio
  53031. };
  53032. // Set up assets
  53033. _this._createRandomTexture();
  53034. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  53035. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  53036. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53037. _this._createSSAOPostProcess(1.0);
  53038. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  53039. _this._createSSAOCombinePostProcess(blurRatio);
  53040. // Set up pipeline
  53041. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53042. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53043. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53044. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53045. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53046. // Finish
  53047. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53048. if (cameras)
  53049. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53050. return _this;
  53051. }
  53052. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  53053. get: function () {
  53054. return this._samples;
  53055. },
  53056. set: function (n) {
  53057. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  53058. this._samples = n;
  53059. this._sampleSphere = this._generateHemisphere();
  53060. this._firstUpdate = true;
  53061. },
  53062. enumerable: true,
  53063. configurable: true
  53064. });
  53065. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  53066. get: function () {
  53067. return this._expensiveBlur;
  53068. },
  53069. set: function (b) {
  53070. 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"]);
  53071. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  53072. this._expensiveBlur = b;
  53073. this._firstUpdate = true;
  53074. },
  53075. enumerable: true,
  53076. configurable: true
  53077. });
  53078. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  53079. /**
  53080. * Support test.
  53081. * @type {boolean}
  53082. */
  53083. get: function () {
  53084. var engine = BABYLON.Engine.LastCreatedEngine;
  53085. return engine.getCaps().drawBuffersExtension;
  53086. },
  53087. enumerable: true,
  53088. configurable: true
  53089. });
  53090. // Public Methods
  53091. /**
  53092. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53093. */
  53094. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  53095. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  53096. for (var i = 0; i < this._scene.cameras.length; i++) {
  53097. var camera = this._scene.cameras[i];
  53098. this._originalColorPostProcess.dispose(camera);
  53099. this._ssaoPostProcess.dispose(camera);
  53100. this._blurHPostProcess.dispose(camera);
  53101. this._blurVPostProcess.dispose(camera);
  53102. this._ssaoCombinePostProcess.dispose(camera);
  53103. }
  53104. this._randomTexture.dispose();
  53105. if (disableGeometryBufferRenderer)
  53106. this._scene.disableGeometryBufferRenderer();
  53107. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53108. _super.prototype.dispose.call(this);
  53109. };
  53110. // Private Methods
  53111. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  53112. var _this = this;
  53113. var samples = 16;
  53114. this._samplerOffsets = [];
  53115. var expensive = this.expensiveBlur;
  53116. for (var i = -8; i < 8; i++) {
  53117. this._samplerOffsets.push(i * 2 + 0.5);
  53118. }
  53119. 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");
  53120. this._blurHPostProcess.onApply = function (effect) {
  53121. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53122. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53123. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53124. effect.setFloat("radius", _this.radius);
  53125. effect.setTexture("depthSampler", _this._depthTexture);
  53126. if (_this._firstUpdate) {
  53127. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53128. }
  53129. };
  53130. 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");
  53131. this._blurVPostProcess.onApply = function (effect) {
  53132. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53133. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53134. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53135. effect.setFloat("radius", _this.radius);
  53136. effect.setTexture("depthSampler", _this._depthTexture);
  53137. if (_this._firstUpdate) {
  53138. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53139. _this._firstUpdate = false;
  53140. }
  53141. };
  53142. };
  53143. SSAO2RenderingPipeline.prototype._rebuild = function () {
  53144. this._firstUpdate = true;
  53145. _super.prototype._rebuild.call(this);
  53146. };
  53147. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  53148. var numSamples = this.samples;
  53149. var result = [];
  53150. var vector, scale;
  53151. var rand = function (min, max) {
  53152. return Math.random() * (max - min) + min;
  53153. };
  53154. var lerp = function (start, end, percent) {
  53155. return (start + percent * (end - start));
  53156. };
  53157. var i = 0;
  53158. var normal = new BABYLON.Vector3(0, 0, 1);
  53159. while (i < numSamples) {
  53160. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  53161. vector.normalize();
  53162. scale = i / numSamples;
  53163. scale = lerp(0.1, 1.0, scale * scale);
  53164. vector.scaleInPlace(scale);
  53165. result.push(vector.x, vector.y, vector.z);
  53166. i++;
  53167. }
  53168. return result;
  53169. };
  53170. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53171. var _this = this;
  53172. var numSamples = this.samples;
  53173. this._sampleSphere = this._generateHemisphere();
  53174. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  53175. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53176. "base", "range", "projection", "near", "far", "texelSize",
  53177. "xViewport", "yViewport", "maxZ", "minZAspect"
  53178. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53179. this._ssaoPostProcess.onApply = function (effect) {
  53180. if (_this._firstUpdate) {
  53181. effect.setArray3("sampleSphere", _this._sampleSphere);
  53182. effect.setFloat("randTextureTiles", 4.0);
  53183. }
  53184. effect.setFloat("samplesFactor", 1 / _this.samples);
  53185. effect.setFloat("totalStrength", _this.totalStrength);
  53186. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  53187. effect.setFloat("radius", _this.radius);
  53188. effect.setFloat("maxZ", _this.maxZ);
  53189. effect.setFloat("minZAspect", _this.minZAspect);
  53190. effect.setFloat("base", _this.base);
  53191. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53192. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53193. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  53194. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  53195. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  53196. effect.setTexture("textureSampler", _this._depthTexture);
  53197. effect.setTexture("normalSampler", _this._normalTexture);
  53198. effect.setTexture("randomSampler", _this._randomTexture);
  53199. };
  53200. };
  53201. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53202. var _this = this;
  53203. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53204. this._ssaoCombinePostProcess.onApply = function (effect) {
  53205. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53206. };
  53207. };
  53208. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  53209. var size = 512;
  53210. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53211. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53212. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53213. var context = this._randomTexture.getContext();
  53214. var rand = function (min, max) {
  53215. return Math.random() * (max - min) + min;
  53216. };
  53217. var randVector = BABYLON.Vector3.Zero();
  53218. for (var x = 0; x < size; x++) {
  53219. for (var y = 0; y < size; y++) {
  53220. randVector.x = rand(0.0, 1.0);
  53221. randVector.y = rand(0.0, 1.0);
  53222. randVector.z = 0.0;
  53223. randVector.normalize();
  53224. randVector.scaleInPlace(255);
  53225. randVector.x = Math.floor(randVector.x);
  53226. randVector.y = Math.floor(randVector.y);
  53227. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53228. context.fillRect(x, y, 1, 1);
  53229. }
  53230. }
  53231. this._randomTexture.update(false);
  53232. };
  53233. __decorate([
  53234. BABYLON.serialize()
  53235. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  53236. __decorate([
  53237. BABYLON.serialize()
  53238. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  53239. __decorate([
  53240. BABYLON.serialize()
  53241. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  53242. __decorate([
  53243. BABYLON.serialize("samples")
  53244. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  53245. __decorate([
  53246. BABYLON.serialize("expensiveBlur")
  53247. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  53248. __decorate([
  53249. BABYLON.serialize()
  53250. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  53251. __decorate([
  53252. BABYLON.serialize()
  53253. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  53254. __decorate([
  53255. BABYLON.serialize()
  53256. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  53257. return SSAO2RenderingPipeline;
  53258. }(BABYLON.PostProcessRenderPipeline));
  53259. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  53260. })(BABYLON || (BABYLON = {}));
  53261. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  53262. // BABYLON.JS Chromatic Aberration GLSL Shader
  53263. // Author: Olivier Guyot
  53264. // Separates very slightly R, G and B colors on the edges of the screen
  53265. // Inspired by Francois Tarlier & Martins Upitis
  53266. var BABYLON;
  53267. (function (BABYLON) {
  53268. var LensRenderingPipeline = (function (_super) {
  53269. __extends(LensRenderingPipeline, _super);
  53270. /**
  53271. * @constructor
  53272. *
  53273. * Effect parameters are as follow:
  53274. * {
  53275. * chromatic_aberration: number; // from 0 to x (1 for realism)
  53276. * edge_blur: number; // from 0 to x (1 for realism)
  53277. * distortion: number; // from 0 to x (1 for realism)
  53278. * grain_amount: number; // from 0 to 1
  53279. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  53280. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  53281. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  53282. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  53283. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  53284. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  53285. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  53286. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  53287. * }
  53288. * Note: if an effect parameter is unset, effect is disabled
  53289. *
  53290. * @param {string} name - The rendering pipeline name
  53291. * @param {object} parameters - An object containing all parameters (see above)
  53292. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53293. * @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)
  53294. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53295. */
  53296. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  53297. if (ratio === void 0) { ratio = 1.0; }
  53298. var _this = _super.call(this, scene.getEngine(), name) || this;
  53299. // Lens effects can be of the following:
  53300. // - chromatic aberration (slight shift of RGB colors)
  53301. // - blur on the edge of the lens
  53302. // - lens distortion
  53303. // - depth-of-field blur & highlights enhancing
  53304. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  53305. // - grain effect (noise or custom texture)
  53306. // Two additional texture samplers are needed:
  53307. // - depth map (for depth-of-field)
  53308. // - grain texture
  53309. /**
  53310. * The chromatic aberration PostProcess id in the pipeline
  53311. * @type {string}
  53312. */
  53313. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  53314. /**
  53315. * The highlights enhancing PostProcess id in the pipeline
  53316. * @type {string}
  53317. */
  53318. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  53319. /**
  53320. * The depth-of-field PostProcess id in the pipeline
  53321. * @type {string}
  53322. */
  53323. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  53324. _this._scene = scene;
  53325. // Fetch texture samplers
  53326. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53327. if (parameters.grain_texture) {
  53328. _this._grainTexture = parameters.grain_texture;
  53329. }
  53330. else {
  53331. _this._createGrainTexture();
  53332. }
  53333. // save parameters
  53334. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  53335. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  53336. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  53337. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  53338. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  53339. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  53340. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  53341. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  53342. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  53343. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  53344. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  53345. // Create effects
  53346. _this._createChromaticAberrationPostProcess(ratio);
  53347. _this._createHighlightsPostProcess(ratio);
  53348. _this._createDepthOfFieldPostProcess(ratio / 4);
  53349. // Set up pipeline
  53350. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  53351. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  53352. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  53353. if (_this._highlightsGain === -1) {
  53354. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  53355. }
  53356. // Finish
  53357. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53358. if (cameras) {
  53359. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53360. }
  53361. return _this;
  53362. }
  53363. // public methods (self explanatory)
  53364. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  53365. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  53366. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  53367. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  53368. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  53369. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  53370. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  53371. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  53372. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  53373. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  53374. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  53375. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  53376. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  53377. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  53378. };
  53379. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  53380. this._highlightsPostProcess.updateEffect();
  53381. };
  53382. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  53383. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  53384. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  53385. this._highlightsGain = amount;
  53386. };
  53387. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  53388. if (this._highlightsGain === -1) {
  53389. this._highlightsGain = 1.0;
  53390. }
  53391. this._highlightsThreshold = amount;
  53392. };
  53393. LensRenderingPipeline.prototype.disableHighlights = function () {
  53394. this._highlightsGain = -1;
  53395. };
  53396. /**
  53397. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  53398. */
  53399. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53400. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53401. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53402. this._chromaticAberrationPostProcess = undefined;
  53403. this._highlightsPostProcess = undefined;
  53404. this._depthOfFieldPostProcess = undefined;
  53405. this._grainTexture.dispose();
  53406. if (disableDepthRender)
  53407. this._scene.disableDepthRenderer();
  53408. };
  53409. // colors shifting and distortion
  53410. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  53411. var _this = this;
  53412. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  53413. [], // samplers
  53414. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53415. this._chromaticAberrationPostProcess.onApply = function (effect) {
  53416. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  53417. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53418. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53419. };
  53420. };
  53421. // highlights enhancing
  53422. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  53423. var _this = this;
  53424. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  53425. [], // samplers
  53426. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  53427. this._highlightsPostProcess.onApply = function (effect) {
  53428. effect.setFloat('gain', _this._highlightsGain);
  53429. effect.setFloat('threshold', _this._highlightsThreshold);
  53430. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  53431. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53432. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53433. };
  53434. };
  53435. // colors shifting and distortion
  53436. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  53437. var _this = this;
  53438. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  53439. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  53440. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  53441. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53442. this._depthOfFieldPostProcess.onApply = function (effect) {
  53443. effect.setTexture("depthSampler", _this._depthTexture);
  53444. effect.setTexture("grainSampler", _this._grainTexture);
  53445. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  53446. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  53447. effect.setFloat('grain_amount', _this._grainAmount);
  53448. effect.setBool('blur_noise', _this._blurNoise);
  53449. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53450. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53451. effect.setFloat('distortion', _this._distortion);
  53452. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  53453. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  53454. effect.setFloat('aperture', _this._dofAperture);
  53455. effect.setFloat('darken', _this._dofDarken);
  53456. effect.setFloat('edge_blur', _this._edgeBlur);
  53457. effect.setBool('highlights', (_this._highlightsGain !== -1));
  53458. effect.setFloat('near', _this._scene.activeCamera.minZ);
  53459. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  53460. };
  53461. };
  53462. // creates a black and white random noise texture, 512x512
  53463. LensRenderingPipeline.prototype._createGrainTexture = function () {
  53464. var size = 512;
  53465. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53466. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53467. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53468. var context = this._grainTexture.getContext();
  53469. var rand = function (min, max) {
  53470. return Math.random() * (max - min) + min;
  53471. };
  53472. var value;
  53473. for (var x = 0; x < size; x++) {
  53474. for (var y = 0; y < size; y++) {
  53475. value = Math.floor(rand(0.42, 0.58) * 255);
  53476. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  53477. context.fillRect(x, y, 1, 1);
  53478. }
  53479. }
  53480. this._grainTexture.update(false);
  53481. };
  53482. return LensRenderingPipeline;
  53483. }(BABYLON.PostProcessRenderPipeline));
  53484. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  53485. })(BABYLON || (BABYLON = {}));
  53486. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  53487. var BABYLON;
  53488. (function (BABYLON) {
  53489. var StandardRenderingPipeline = (function (_super) {
  53490. __extends(StandardRenderingPipeline, _super);
  53491. /**
  53492. * @constructor
  53493. * @param {string} name - The rendering pipeline name
  53494. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53495. * @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)
  53496. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53497. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53498. */
  53499. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53500. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53501. var _this = _super.call(this, scene.getEngine(), name) || this;
  53502. _this.downSampleX4PostProcess = null;
  53503. _this.brightPassPostProcess = null;
  53504. _this.blurHPostProcesses = [];
  53505. _this.blurVPostProcesses = [];
  53506. _this.textureAdderPostProcess = null;
  53507. _this.volumetricLightPostProcess = null;
  53508. _this.volumetricLightSmoothXPostProcess = null;
  53509. _this.volumetricLightSmoothYPostProcess = null;
  53510. _this.volumetricLightMergePostProces = null;
  53511. _this.volumetricLightFinalPostProcess = null;
  53512. _this.luminancePostProcess = null;
  53513. _this.luminanceDownSamplePostProcesses = [];
  53514. _this.hdrPostProcess = null;
  53515. _this.textureAdderFinalPostProcess = null;
  53516. _this.lensFlareFinalPostProcess = null;
  53517. _this.hdrFinalPostProcess = null;
  53518. _this.lensFlarePostProcess = null;
  53519. _this.lensFlareComposePostProcess = null;
  53520. _this.motionBlurPostProcess = null;
  53521. _this.depthOfFieldPostProcess = null;
  53522. // Values
  53523. _this.brightThreshold = 1.0;
  53524. _this.blurWidth = 512.0;
  53525. _this.horizontalBlur = false;
  53526. _this.exposure = 1.0;
  53527. _this.lensTexture = null;
  53528. _this.volumetricLightCoefficient = 0.2;
  53529. _this.volumetricLightPower = 4.0;
  53530. _this.volumetricLightBlurScale = 64.0;
  53531. _this.sourceLight = null;
  53532. _this.hdrMinimumLuminance = 1.0;
  53533. _this.hdrDecreaseRate = 0.5;
  53534. _this.hdrIncreaseRate = 0.5;
  53535. _this.lensColorTexture = null;
  53536. _this.lensFlareStrength = 20.0;
  53537. _this.lensFlareGhostDispersal = 1.4;
  53538. _this.lensFlareHaloWidth = 0.7;
  53539. _this.lensFlareDistortionStrength = 16.0;
  53540. _this.lensStarTexture = null;
  53541. _this.lensFlareDirtTexture = null;
  53542. _this.depthOfFieldDistance = 10.0;
  53543. _this.depthOfFieldBlurWidth = 64.0;
  53544. _this.motionStrength = 1.0;
  53545. // IAnimatable
  53546. _this.animations = [];
  53547. _this._currentDepthOfFieldSource = null;
  53548. _this._hdrCurrentLuminance = 1.0;
  53549. // Getters and setters
  53550. _this._bloomEnabled = true;
  53551. _this._depthOfFieldEnabled = false;
  53552. _this._vlsEnabled = false;
  53553. _this._lensFlareEnabled = false;
  53554. _this._hdrEnabled = false;
  53555. _this._motionBlurEnabled = false;
  53556. _this._motionBlurSamples = 64.0;
  53557. _this._volumetricLightStepsCount = 50.0;
  53558. _this._cameras = cameras || [];
  53559. // Initialize
  53560. _this._scene = scene;
  53561. _this._basePostProcess = originalPostProcess;
  53562. _this._ratio = ratio;
  53563. // Misc
  53564. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53565. // Finish
  53566. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53567. _this._buildPipeline();
  53568. return _this;
  53569. }
  53570. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  53571. get: function () {
  53572. return this._bloomEnabled;
  53573. },
  53574. set: function (enabled) {
  53575. if (this._bloomEnabled === enabled) {
  53576. return;
  53577. }
  53578. this._bloomEnabled = enabled;
  53579. this._buildPipeline();
  53580. },
  53581. enumerable: true,
  53582. configurable: true
  53583. });
  53584. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  53585. get: function () {
  53586. return this._depthOfFieldEnabled;
  53587. },
  53588. set: function (enabled) {
  53589. if (this._depthOfFieldEnabled === enabled) {
  53590. return;
  53591. }
  53592. this._depthOfFieldEnabled = enabled;
  53593. this._buildPipeline();
  53594. },
  53595. enumerable: true,
  53596. configurable: true
  53597. });
  53598. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  53599. get: function () {
  53600. return this._lensFlareEnabled;
  53601. },
  53602. set: function (enabled) {
  53603. if (this._lensFlareEnabled === enabled) {
  53604. return;
  53605. }
  53606. this._lensFlareEnabled = enabled;
  53607. this._buildPipeline();
  53608. },
  53609. enumerable: true,
  53610. configurable: true
  53611. });
  53612. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  53613. get: function () {
  53614. return this._hdrEnabled;
  53615. },
  53616. set: function (enabled) {
  53617. if (this._hdrEnabled === enabled) {
  53618. return;
  53619. }
  53620. this._hdrEnabled = enabled;
  53621. this._buildPipeline();
  53622. },
  53623. enumerable: true,
  53624. configurable: true
  53625. });
  53626. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  53627. get: function () {
  53628. return this._vlsEnabled;
  53629. },
  53630. set: function (enabled) {
  53631. if (this._vlsEnabled === enabled) {
  53632. return;
  53633. }
  53634. if (enabled) {
  53635. var geometry = this._scene.enableGeometryBufferRenderer();
  53636. if (!geometry) {
  53637. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  53638. return;
  53639. }
  53640. }
  53641. this._vlsEnabled = enabled;
  53642. this._buildPipeline();
  53643. },
  53644. enumerable: true,
  53645. configurable: true
  53646. });
  53647. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  53648. get: function () {
  53649. return this._motionBlurEnabled;
  53650. },
  53651. set: function (enabled) {
  53652. if (this._motionBlurEnabled === enabled) {
  53653. return;
  53654. }
  53655. this._motionBlurEnabled = enabled;
  53656. this._buildPipeline();
  53657. },
  53658. enumerable: true,
  53659. configurable: true
  53660. });
  53661. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  53662. get: function () {
  53663. return this._volumetricLightStepsCount;
  53664. },
  53665. set: function (count) {
  53666. if (this.volumetricLightPostProcess) {
  53667. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  53668. }
  53669. this._volumetricLightStepsCount = count;
  53670. },
  53671. enumerable: true,
  53672. configurable: true
  53673. });
  53674. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  53675. get: function () {
  53676. return this._motionBlurSamples;
  53677. },
  53678. set: function (samples) {
  53679. if (this.motionBlurPostProcess) {
  53680. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  53681. }
  53682. this._motionBlurSamples = samples;
  53683. },
  53684. enumerable: true,
  53685. configurable: true
  53686. });
  53687. StandardRenderingPipeline.prototype._buildPipeline = function () {
  53688. var _this = this;
  53689. var ratio = this._ratio;
  53690. var scene = this._scene;
  53691. this._disposePostProcesses();
  53692. this._reset();
  53693. // Create pass post-process
  53694. if (!this._basePostProcess) {
  53695. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  53696. this.originalPostProcess.onApply = function (effect) {
  53697. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  53698. };
  53699. }
  53700. else {
  53701. this.originalPostProcess = this._basePostProcess;
  53702. }
  53703. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  53704. this._currentDepthOfFieldSource = this.originalPostProcess;
  53705. if (this._vlsEnabled) {
  53706. // Create volumetric light
  53707. this._createVolumetricLightPostProcess(scene, ratio);
  53708. // Create volumetric light final post-process
  53709. 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);
  53710. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  53711. }
  53712. if (this._bloomEnabled) {
  53713. // Create down sample X4 post-process
  53714. this._createDownSampleX4PostProcess(scene, ratio / 2);
  53715. // Create bright pass post-process
  53716. this._createBrightPassPostProcess(scene, ratio / 2);
  53717. // Create gaussian blur post-processes (down sampling blurs)
  53718. this._createBlurPostProcesses(scene, ratio / 4, 1);
  53719. // Create texture adder post-process
  53720. this._createTextureAdderPostProcess(scene, ratio);
  53721. // Create depth-of-field source post-process
  53722. 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);
  53723. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  53724. }
  53725. if (this._lensFlareEnabled) {
  53726. // Create lens flare post-process
  53727. this._createLensFlarePostProcess(scene, ratio);
  53728. // Create depth-of-field source post-process post lens-flare and disable it now
  53729. 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);
  53730. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  53731. }
  53732. if (this._hdrEnabled) {
  53733. // Create luminance
  53734. this._createLuminancePostProcesses(scene, this._floatTextureType);
  53735. // Create HDR
  53736. this._createHdrPostProcess(scene, ratio);
  53737. // Create depth-of-field source post-process post hdr and disable it now
  53738. 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);
  53739. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  53740. }
  53741. if (this._depthOfFieldEnabled) {
  53742. // Create gaussian blur used by depth-of-field
  53743. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  53744. // Create depth-of-field post-process
  53745. this._createDepthOfFieldPostProcess(scene, ratio);
  53746. }
  53747. if (this._motionBlurEnabled) {
  53748. // Create motion blur post-process
  53749. this._createMotionBlurPostProcess(scene, ratio);
  53750. }
  53751. if (this._cameras !== null) {
  53752. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  53753. }
  53754. };
  53755. // Down Sample X4 Post-Processs
  53756. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53757. var _this = this;
  53758. var downSampleX4Offsets = new Array(32);
  53759. 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);
  53760. this.downSampleX4PostProcess.onApply = function (effect) {
  53761. var id = 0;
  53762. for (var i = -2; i < 2; i++) {
  53763. for (var j = -2; j < 2; j++) {
  53764. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  53765. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  53766. id += 2;
  53767. }
  53768. }
  53769. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53770. };
  53771. // Add to pipeline
  53772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  53773. };
  53774. // Brightpass Post-Process
  53775. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53776. var _this = this;
  53777. var brightOffsets = new Array(8);
  53778. 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);
  53779. this.brightPassPostProcess.onApply = function (effect) {
  53780. var sU = (1.0 / _this.brightPassPostProcess.width);
  53781. var sV = (1.0 / _this.brightPassPostProcess.height);
  53782. brightOffsets[0] = -0.5 * sU;
  53783. brightOffsets[1] = 0.5 * sV;
  53784. brightOffsets[2] = 0.5 * sU;
  53785. brightOffsets[3] = 0.5 * sV;
  53786. brightOffsets[4] = -0.5 * sU;
  53787. brightOffsets[5] = -0.5 * sV;
  53788. brightOffsets[6] = 0.5 * sU;
  53789. brightOffsets[7] = -0.5 * sV;
  53790. effect.setArray2("dsOffsets", brightOffsets);
  53791. effect.setFloat("brightThreshold", _this.brightThreshold);
  53792. };
  53793. // Add to pipeline
  53794. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  53795. };
  53796. // Create blur H&V post-processes
  53797. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  53798. var _this = this;
  53799. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  53800. var engine = scene.getEngine();
  53801. 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);
  53802. 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);
  53803. blurX.onActivateObservable.add(function () {
  53804. var dw = blurX.width / engine.getRenderingCanvas().width;
  53805. blurX.kernel = _this[blurWidthKey] * dw;
  53806. });
  53807. blurY.onActivateObservable.add(function () {
  53808. var dw = blurY.height / engine.getRenderingCanvas().height;
  53809. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  53810. });
  53811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  53812. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  53813. this.blurHPostProcesses.push(blurX);
  53814. this.blurVPostProcesses.push(blurY);
  53815. };
  53816. // Create texture adder post-process
  53817. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53818. var _this = this;
  53819. 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);
  53820. this.textureAdderPostProcess.onApply = function (effect) {
  53821. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  53822. effect.setTexture("lensSampler", _this.lensTexture);
  53823. effect.setFloat("exposure", _this.exposure);
  53824. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  53825. };
  53826. // Add to pipeline
  53827. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  53828. };
  53829. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  53830. var _this = this;
  53831. var geometryRenderer = scene.enableGeometryBufferRenderer();
  53832. geometryRenderer.enablePosition = true;
  53833. var geometry = geometryRenderer.getGBuffer();
  53834. // Base post-process
  53835. 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));
  53836. var depthValues = BABYLON.Vector2.Zero();
  53837. this.volumetricLightPostProcess.onApply = function (effect) {
  53838. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  53839. var generator = _this.sourceLight.getShadowGenerator();
  53840. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  53841. effect.setTexture("positionSampler", geometry.textures[2]);
  53842. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  53843. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  53844. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  53845. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  53846. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  53847. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  53848. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  53849. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  53850. effect.setVector2("depthValues", depthValues);
  53851. }
  53852. };
  53853. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  53854. // Smooth
  53855. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  53856. // Merge
  53857. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  53858. this.volumetricLightMergePostProces.onApply = function (effect) {
  53859. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  53860. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  53861. };
  53862. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  53863. };
  53864. // Create luminance
  53865. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  53866. var _this = this;
  53867. // Create luminance
  53868. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  53869. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  53870. var offsets = [];
  53871. this.luminancePostProcess.onApply = function (effect) {
  53872. var sU = (1.0 / _this.luminancePostProcess.width);
  53873. var sV = (1.0 / _this.luminancePostProcess.height);
  53874. offsets[0] = -0.5 * sU;
  53875. offsets[1] = 0.5 * sV;
  53876. offsets[2] = 0.5 * sU;
  53877. offsets[3] = 0.5 * sV;
  53878. offsets[4] = -0.5 * sU;
  53879. offsets[5] = -0.5 * sV;
  53880. offsets[6] = 0.5 * sU;
  53881. offsets[7] = -0.5 * sV;
  53882. effect.setArray2("lumOffsets", offsets);
  53883. };
  53884. // Add to pipeline
  53885. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  53886. // Create down sample luminance
  53887. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  53888. var size = Math.pow(3, i);
  53889. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  53890. if (i === 0) {
  53891. defines += "#define FINAL_DOWN_SAMPLER";
  53892. }
  53893. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  53894. this.luminanceDownSamplePostProcesses.push(postProcess);
  53895. }
  53896. // Create callbacks and add effects
  53897. var lastLuminance = this.luminancePostProcess;
  53898. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  53899. var downSampleOffsets = new Array(18);
  53900. pp.onApply = function (effect) {
  53901. var id = 0;
  53902. for (var x = -1; x < 2; x++) {
  53903. for (var y = -1; y < 2; y++) {
  53904. downSampleOffsets[id] = x / lastLuminance.width;
  53905. downSampleOffsets[id + 1] = y / lastLuminance.height;
  53906. id += 2;
  53907. }
  53908. }
  53909. effect.setArray2("dsOffsets", downSampleOffsets);
  53910. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  53911. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  53912. lastLuminance = _this.luminancePostProcess;
  53913. }
  53914. else {
  53915. lastLuminance = pp;
  53916. }
  53917. };
  53918. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  53919. pp.onAfterRender = function (effect) {
  53920. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53921. 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);
  53922. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53923. };
  53924. }
  53925. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  53926. });
  53927. };
  53928. // Create HDR post-process
  53929. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  53930. var _this = this;
  53931. 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);
  53932. var outputLiminance = 1;
  53933. var time = 0;
  53934. var lastTime = 0;
  53935. this.hdrPostProcess.onApply = function (effect) {
  53936. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  53937. time += scene.getEngine().getDeltaTime();
  53938. if (outputLiminance < 0) {
  53939. outputLiminance = _this._hdrCurrentLuminance;
  53940. }
  53941. else {
  53942. var dt = (lastTime - time) / 1000.0;
  53943. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  53944. outputLiminance += _this.hdrDecreaseRate * dt;
  53945. }
  53946. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  53947. outputLiminance -= _this.hdrIncreaseRate * dt;
  53948. }
  53949. else {
  53950. outputLiminance = _this._hdrCurrentLuminance;
  53951. }
  53952. }
  53953. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  53954. effect.setFloat("averageLuminance", outputLiminance);
  53955. lastTime = time;
  53956. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  53957. };
  53958. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  53959. };
  53960. // Create lens flare post-process
  53961. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  53962. var _this = this;
  53963. 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);
  53964. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  53965. this._createBlurPostProcesses(scene, ratio / 4, 2);
  53966. 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);
  53967. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  53968. var resolution = new BABYLON.Vector2(0, 0);
  53969. // Lens flare
  53970. this.lensFlarePostProcess.onApply = function (effect) {
  53971. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  53972. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  53973. effect.setFloat("strength", _this.lensFlareStrength);
  53974. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  53975. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  53976. // Shift
  53977. resolution.x = _this.lensFlarePostProcess.width;
  53978. resolution.y = _this.lensFlarePostProcess.height;
  53979. effect.setVector2("resolution", resolution);
  53980. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  53981. };
  53982. // Compose
  53983. 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);
  53984. 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);
  53985. this.lensFlareComposePostProcess.onApply = function (effect) {
  53986. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  53987. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  53988. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  53989. // Lens start rotation matrix
  53990. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  53991. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  53992. 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));
  53993. camRot *= 4.0;
  53994. 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);
  53995. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  53996. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  53997. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  53998. };
  53999. };
  54000. // Create depth-of-field post-process
  54001. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54002. var _this = this;
  54003. 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);
  54004. this.depthOfFieldPostProcess.onApply = function (effect) {
  54005. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  54006. effect.setTexture("depthSampler", _this._getDepthTexture());
  54007. effect.setFloat("distance", _this.depthOfFieldDistance);
  54008. };
  54009. // Add to pipeline
  54010. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54011. };
  54012. // Create motion blur post-process
  54013. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  54014. var _this = this;
  54015. 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);
  54016. var motionScale = 0;
  54017. var prevViewProjection = BABYLON.Matrix.Identity();
  54018. var invViewProjection = BABYLON.Matrix.Identity();
  54019. var viewProjection = BABYLON.Matrix.Identity();
  54020. var screenSize = BABYLON.Vector2.Zero();
  54021. this.motionBlurPostProcess.onApply = function (effect) {
  54022. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  54023. viewProjection.invertToRef(invViewProjection);
  54024. effect.setMatrix("inverseViewProjection", invViewProjection);
  54025. effect.setMatrix("prevViewProjection", prevViewProjection);
  54026. prevViewProjection = viewProjection;
  54027. screenSize.x = _this.motionBlurPostProcess.width;
  54028. screenSize.y = _this.motionBlurPostProcess.height;
  54029. effect.setVector2("screenSize", screenSize);
  54030. motionScale = scene.getEngine().getFps() / 60.0;
  54031. effect.setFloat("motionScale", motionScale);
  54032. effect.setFloat("motionStrength", _this.motionStrength);
  54033. effect.setTexture("depthSampler", _this._getDepthTexture());
  54034. };
  54035. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  54036. };
  54037. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  54038. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  54039. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  54040. }
  54041. return this._scene.enableDepthRenderer().getDepthMap();
  54042. };
  54043. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  54044. for (var i = 0; i < this._cameras.length; i++) {
  54045. var camera = this._cameras[i];
  54046. if (this.originalPostProcess) {
  54047. this.originalPostProcess.dispose(camera);
  54048. }
  54049. if (this.downSampleX4PostProcess) {
  54050. this.downSampleX4PostProcess.dispose(camera);
  54051. }
  54052. if (this.brightPassPostProcess) {
  54053. this.brightPassPostProcess.dispose(camera);
  54054. }
  54055. if (this.textureAdderPostProcess) {
  54056. this.textureAdderPostProcess.dispose(camera);
  54057. }
  54058. if (this.textureAdderFinalPostProcess) {
  54059. this.textureAdderFinalPostProcess.dispose(camera);
  54060. }
  54061. if (this.volumetricLightPostProcess) {
  54062. this.volumetricLightPostProcess.dispose(camera);
  54063. }
  54064. if (this.volumetricLightSmoothXPostProcess) {
  54065. this.volumetricLightSmoothXPostProcess.dispose(camera);
  54066. }
  54067. if (this.volumetricLightSmoothYPostProcess) {
  54068. this.volumetricLightSmoothYPostProcess.dispose(camera);
  54069. }
  54070. if (this.volumetricLightMergePostProces) {
  54071. this.volumetricLightMergePostProces.dispose(camera);
  54072. }
  54073. if (this.volumetricLightFinalPostProcess) {
  54074. this.volumetricLightFinalPostProcess.dispose(camera);
  54075. }
  54076. if (this.lensFlarePostProcess) {
  54077. this.lensFlarePostProcess.dispose(camera);
  54078. }
  54079. if (this.lensFlareComposePostProcess) {
  54080. this.lensFlareComposePostProcess.dispose(camera);
  54081. }
  54082. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  54083. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  54084. }
  54085. if (this.luminancePostProcess) {
  54086. this.luminancePostProcess.dispose(camera);
  54087. }
  54088. if (this.hdrPostProcess) {
  54089. this.hdrPostProcess.dispose(camera);
  54090. }
  54091. if (this.hdrFinalPostProcess) {
  54092. this.hdrFinalPostProcess.dispose(camera);
  54093. }
  54094. if (this.depthOfFieldPostProcess) {
  54095. this.depthOfFieldPostProcess.dispose(camera);
  54096. }
  54097. if (this.motionBlurPostProcess) {
  54098. this.motionBlurPostProcess.dispose(camera);
  54099. }
  54100. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  54101. this.blurHPostProcesses[j].dispose(camera);
  54102. }
  54103. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  54104. this.blurVPostProcesses[j].dispose(camera);
  54105. }
  54106. }
  54107. this.originalPostProcess = null;
  54108. this.downSampleX4PostProcess = null;
  54109. this.brightPassPostProcess = null;
  54110. this.textureAdderPostProcess = null;
  54111. this.textureAdderFinalPostProcess = null;
  54112. this.volumetricLightPostProcess = null;
  54113. this.volumetricLightSmoothXPostProcess = null;
  54114. this.volumetricLightSmoothYPostProcess = null;
  54115. this.volumetricLightMergePostProces = null;
  54116. this.volumetricLightFinalPostProcess = null;
  54117. this.lensFlarePostProcess = null;
  54118. this.lensFlareComposePostProcess = null;
  54119. this.luminancePostProcess = null;
  54120. this.hdrPostProcess = null;
  54121. this.hdrFinalPostProcess = null;
  54122. this.depthOfFieldPostProcess = null;
  54123. this.motionBlurPostProcess = null;
  54124. this.luminanceDownSamplePostProcesses = [];
  54125. this.blurHPostProcesses = [];
  54126. this.blurVPostProcesses = [];
  54127. };
  54128. // Dispose
  54129. StandardRenderingPipeline.prototype.dispose = function () {
  54130. this._disposePostProcesses();
  54131. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  54132. _super.prototype.dispose.call(this);
  54133. };
  54134. // Serialize rendering pipeline
  54135. StandardRenderingPipeline.prototype.serialize = function () {
  54136. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54137. serializationObject.customType = "StandardRenderingPipeline";
  54138. return serializationObject;
  54139. };
  54140. /**
  54141. * Static members
  54142. */
  54143. // Parse serialized pipeline
  54144. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  54145. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  54146. };
  54147. // Luminance steps
  54148. StandardRenderingPipeline.LuminanceSteps = 6;
  54149. __decorate([
  54150. BABYLON.serialize()
  54151. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  54152. __decorate([
  54153. BABYLON.serialize()
  54154. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  54155. __decorate([
  54156. BABYLON.serialize()
  54157. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  54158. __decorate([
  54159. BABYLON.serialize()
  54160. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  54161. __decorate([
  54162. BABYLON.serializeAsTexture("lensTexture")
  54163. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  54164. __decorate([
  54165. BABYLON.serialize()
  54166. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  54167. __decorate([
  54168. BABYLON.serialize()
  54169. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  54170. __decorate([
  54171. BABYLON.serialize()
  54172. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  54173. __decorate([
  54174. BABYLON.serialize()
  54175. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  54176. __decorate([
  54177. BABYLON.serialize()
  54178. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  54179. __decorate([
  54180. BABYLON.serialize()
  54181. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  54182. __decorate([
  54183. BABYLON.serializeAsTexture("lensColorTexture")
  54184. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  54185. __decorate([
  54186. BABYLON.serialize()
  54187. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  54188. __decorate([
  54189. BABYLON.serialize()
  54190. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  54191. __decorate([
  54192. BABYLON.serialize()
  54193. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  54194. __decorate([
  54195. BABYLON.serialize()
  54196. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  54197. __decorate([
  54198. BABYLON.serializeAsTexture("lensStarTexture")
  54199. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  54200. __decorate([
  54201. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  54202. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  54203. __decorate([
  54204. BABYLON.serialize()
  54205. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  54206. __decorate([
  54207. BABYLON.serialize()
  54208. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  54209. __decorate([
  54210. BABYLON.serialize()
  54211. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  54212. __decorate([
  54213. BABYLON.serialize()
  54214. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  54215. __decorate([
  54216. BABYLON.serialize()
  54217. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  54218. __decorate([
  54219. BABYLON.serialize()
  54220. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  54221. __decorate([
  54222. BABYLON.serialize()
  54223. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  54224. __decorate([
  54225. BABYLON.serialize()
  54226. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  54227. __decorate([
  54228. BABYLON.serialize()
  54229. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  54230. __decorate([
  54231. BABYLON.serialize()
  54232. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  54233. __decorate([
  54234. BABYLON.serialize()
  54235. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  54236. return StandardRenderingPipeline;
  54237. }(BABYLON.PostProcessRenderPipeline));
  54238. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54239. })(BABYLON || (BABYLON = {}));
  54240. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54241. var BABYLON;
  54242. (function (BABYLON) {
  54243. var FxaaPostProcess = (function (_super) {
  54244. __extends(FxaaPostProcess, _super);
  54245. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54246. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54247. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  54248. _this.onApplyObservable.add(function (effect) {
  54249. var texelSize = _this.texelSize;
  54250. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  54251. });
  54252. return _this;
  54253. }
  54254. return FxaaPostProcess;
  54255. }(BABYLON.PostProcess));
  54256. BABYLON.FxaaPostProcess = FxaaPostProcess;
  54257. })(BABYLON || (BABYLON = {}));
  54258. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  54259. var BABYLON;
  54260. (function (BABYLON) {
  54261. var DefaultRenderingPipeline = (function (_super) {
  54262. __extends(DefaultRenderingPipeline, _super);
  54263. /**
  54264. * @constructor
  54265. * @param {string} name - The rendering pipeline name
  54266. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54267. * @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)
  54268. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54269. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  54270. */
  54271. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  54272. if (automaticBuild === void 0) { automaticBuild = true; }
  54273. var _this = _super.call(this, scene.getEngine(), name) || this;
  54274. _this.PassPostProcessId = "PassPostProcessEffect";
  54275. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  54276. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  54277. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  54278. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  54279. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  54280. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  54281. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  54282. // IAnimatable
  54283. _this.animations = [];
  54284. // Values
  54285. _this._bloomEnabled = false;
  54286. _this._fxaaEnabled = false;
  54287. _this._imageProcessingEnabled = true;
  54288. _this._bloomScale = 0.6;
  54289. _this._buildAllowed = true;
  54290. /**
  54291. * Specifies the size of the bloom blur kernel, relative to the final output size
  54292. */
  54293. _this.bloomKernel = 64;
  54294. /**
  54295. * Specifies the weight of the bloom in the final rendering
  54296. */
  54297. _this._bloomWeight = 0.15;
  54298. _this._cameras = cameras || [];
  54299. _this._buildAllowed = automaticBuild;
  54300. // Initialize
  54301. _this._scene = scene;
  54302. var caps = _this._scene.getEngine().getCaps();
  54303. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  54304. // Misc
  54305. if (_this._hdr) {
  54306. if (caps.textureHalfFloatRender) {
  54307. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54308. }
  54309. else if (caps.textureFloatRender) {
  54310. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  54311. }
  54312. }
  54313. else {
  54314. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  54315. }
  54316. // Attach
  54317. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54318. _this._buildPipeline();
  54319. return _this;
  54320. }
  54321. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  54322. get: function () {
  54323. return this._bloomWeight;
  54324. },
  54325. set: function (value) {
  54326. if (this._bloomWeight === value) {
  54327. return;
  54328. }
  54329. this._bloomWeight = value;
  54330. if (this._hdr && this.copyBack) {
  54331. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  54332. }
  54333. },
  54334. enumerable: true,
  54335. configurable: true
  54336. });
  54337. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  54338. get: function () {
  54339. return this._bloomScale;
  54340. },
  54341. set: function (value) {
  54342. if (this._bloomScale === value) {
  54343. return;
  54344. }
  54345. this._bloomScale = value;
  54346. this._buildPipeline();
  54347. },
  54348. enumerable: true,
  54349. configurable: true
  54350. });
  54351. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  54352. get: function () {
  54353. return this._bloomEnabled;
  54354. },
  54355. set: function (enabled) {
  54356. if (this._bloomEnabled === enabled) {
  54357. return;
  54358. }
  54359. this._bloomEnabled = enabled;
  54360. this._buildPipeline();
  54361. },
  54362. enumerable: true,
  54363. configurable: true
  54364. });
  54365. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  54366. get: function () {
  54367. return this._fxaaEnabled;
  54368. },
  54369. set: function (enabled) {
  54370. if (this._fxaaEnabled === enabled) {
  54371. return;
  54372. }
  54373. this._fxaaEnabled = enabled;
  54374. this._buildPipeline();
  54375. },
  54376. enumerable: true,
  54377. configurable: true
  54378. });
  54379. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  54380. get: function () {
  54381. return this._imageProcessingEnabled;
  54382. },
  54383. set: function (enabled) {
  54384. if (this._imageProcessingEnabled === enabled) {
  54385. return;
  54386. }
  54387. this._imageProcessingEnabled = enabled;
  54388. this._buildPipeline();
  54389. },
  54390. enumerable: true,
  54391. configurable: true
  54392. });
  54393. /**
  54394. * Force the compilation of the entire pipeline.
  54395. */
  54396. DefaultRenderingPipeline.prototype.prepare = function () {
  54397. var previousState = this._buildAllowed;
  54398. this._buildAllowed = true;
  54399. this._buildPipeline();
  54400. this._buildAllowed = previousState;
  54401. };
  54402. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  54403. var _this = this;
  54404. if (!this._buildAllowed) {
  54405. return;
  54406. }
  54407. var engine = this._scene.getEngine();
  54408. this._disposePostProcesses();
  54409. this._reset();
  54410. if (this.bloomEnabled) {
  54411. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54412. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  54413. if (!this._hdr) {
  54414. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54415. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  54416. this.highlights.autoClear = false;
  54417. this.highlights.alwaysForcePOT = true;
  54418. }
  54419. 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);
  54420. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  54421. this.blurX.alwaysForcePOT = true;
  54422. this.blurX.autoClear = false;
  54423. this.blurX.onActivateObservable.add(function () {
  54424. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  54425. _this.blurX.kernel = _this.bloomKernel * dw;
  54426. });
  54427. 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);
  54428. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  54429. this.blurY.alwaysForcePOT = true;
  54430. this.blurY.autoClear = false;
  54431. this.blurY.onActivateObservable.add(function () {
  54432. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  54433. _this.blurY.kernel = _this.bloomKernel * dh;
  54434. });
  54435. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54436. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  54437. this.copyBack.alwaysForcePOT = true;
  54438. if (this._hdr) {
  54439. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  54440. var w = this.bloomWeight;
  54441. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  54442. }
  54443. else {
  54444. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  54445. }
  54446. this.copyBack.autoClear = false;
  54447. }
  54448. if (this._imageProcessingEnabled) {
  54449. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54450. if (this._hdr) {
  54451. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  54452. }
  54453. else {
  54454. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  54455. }
  54456. }
  54457. if (this.fxaaEnabled) {
  54458. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54459. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  54460. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  54461. }
  54462. else {
  54463. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54464. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  54465. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  54466. }
  54467. if (this.bloomEnabled) {
  54468. if (this._hdr) {
  54469. this.copyBack.shareOutputWith(this.blurX);
  54470. if (this.imageProcessing) {
  54471. this.imageProcessing.shareOutputWith(this.pass);
  54472. this.imageProcessing.autoClear = false;
  54473. }
  54474. else if (this.fxaa) {
  54475. this.fxaa.shareOutputWith(this.pass);
  54476. }
  54477. else {
  54478. this.finalMerge.shareOutputWith(this.pass);
  54479. }
  54480. }
  54481. else {
  54482. if (this.fxaa) {
  54483. this.fxaa.shareOutputWith(this.pass);
  54484. }
  54485. else {
  54486. this.finalMerge.shareOutputWith(this.pass);
  54487. }
  54488. }
  54489. }
  54490. if (this._cameras !== null) {
  54491. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  54492. }
  54493. };
  54494. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  54495. for (var i = 0; i < this._cameras.length; i++) {
  54496. var camera = this._cameras[i];
  54497. if (this.pass) {
  54498. this.pass.dispose(camera);
  54499. }
  54500. if (this.highlights) {
  54501. this.highlights.dispose(camera);
  54502. }
  54503. if (this.blurX) {
  54504. this.blurX.dispose(camera);
  54505. }
  54506. if (this.blurY) {
  54507. this.blurY.dispose(camera);
  54508. }
  54509. if (this.copyBack) {
  54510. this.copyBack.dispose(camera);
  54511. }
  54512. if (this.imageProcessing) {
  54513. this.imageProcessing.dispose(camera);
  54514. }
  54515. if (this.fxaa) {
  54516. this.fxaa.dispose(camera);
  54517. }
  54518. if (this.finalMerge) {
  54519. this.finalMerge.dispose(camera);
  54520. }
  54521. }
  54522. this.pass = null;
  54523. this.highlights = null;
  54524. this.blurX = null;
  54525. this.blurY = null;
  54526. this.copyBack = null;
  54527. this.imageProcessing = null;
  54528. this.fxaa = null;
  54529. this.finalMerge = null;
  54530. };
  54531. // Dispose
  54532. DefaultRenderingPipeline.prototype.dispose = function () {
  54533. this._disposePostProcesses();
  54534. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  54535. _super.prototype.dispose.call(this);
  54536. };
  54537. // Serialize rendering pipeline
  54538. DefaultRenderingPipeline.prototype.serialize = function () {
  54539. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54540. serializationObject.customType = "DefaultRenderingPipeline";
  54541. return serializationObject;
  54542. };
  54543. // Parse serialized pipeline
  54544. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  54545. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  54546. };
  54547. __decorate([
  54548. BABYLON.serialize()
  54549. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  54550. __decorate([
  54551. BABYLON.serialize()
  54552. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  54553. __decorate([
  54554. BABYLON.serialize()
  54555. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  54556. __decorate([
  54557. BABYLON.serialize()
  54558. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  54559. __decorate([
  54560. BABYLON.serialize()
  54561. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  54562. __decorate([
  54563. BABYLON.serialize()
  54564. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  54565. __decorate([
  54566. BABYLON.serialize()
  54567. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  54568. __decorate([
  54569. BABYLON.serialize()
  54570. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  54571. return DefaultRenderingPipeline;
  54572. }(BABYLON.PostProcessRenderPipeline));
  54573. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  54574. })(BABYLON || (BABYLON = {}));
  54575. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  54576. var BABYLON;
  54577. (function (BABYLON) {
  54578. var GeometryBufferRenderer = (function () {
  54579. function GeometryBufferRenderer(scene, ratio) {
  54580. if (ratio === void 0) { ratio = 1; }
  54581. this._viewMatrix = BABYLON.Matrix.Zero();
  54582. this._projectionMatrix = BABYLON.Matrix.Zero();
  54583. this._transformMatrix = BABYLON.Matrix.Zero();
  54584. this._worldViewProjection = BABYLON.Matrix.Zero();
  54585. this._enablePosition = false;
  54586. this._scene = scene;
  54587. this._ratio = ratio;
  54588. // Render target
  54589. this._createRenderTargets();
  54590. }
  54591. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  54592. set: function (meshes) {
  54593. this._multiRenderTarget.renderList = meshes;
  54594. },
  54595. enumerable: true,
  54596. configurable: true
  54597. });
  54598. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  54599. get: function () {
  54600. return this._multiRenderTarget.isSupported;
  54601. },
  54602. enumerable: true,
  54603. configurable: true
  54604. });
  54605. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  54606. get: function () {
  54607. return this._enablePosition;
  54608. },
  54609. set: function (enable) {
  54610. this._enablePosition = enable;
  54611. this.dispose();
  54612. this._createRenderTargets();
  54613. },
  54614. enumerable: true,
  54615. configurable: true
  54616. });
  54617. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  54618. var material = subMesh.getMaterial();
  54619. if (material && material.disableDepthWrite) {
  54620. return false;
  54621. }
  54622. var defines = [];
  54623. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  54624. var mesh = subMesh.getMesh();
  54625. var scene = mesh.getScene();
  54626. // Alpha test
  54627. if (material && material.needAlphaTesting()) {
  54628. defines.push("#define ALPHATEST");
  54629. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54630. attribs.push(BABYLON.VertexBuffer.UVKind);
  54631. defines.push("#define UV1");
  54632. }
  54633. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54634. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54635. defines.push("#define UV2");
  54636. }
  54637. }
  54638. // Buffers
  54639. if (this._enablePosition) {
  54640. defines.push("#define POSITION");
  54641. }
  54642. // Bones
  54643. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54646. if (mesh.numBoneInfluencers > 4) {
  54647. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54648. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54649. }
  54650. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54651. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54652. }
  54653. else {
  54654. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54655. }
  54656. // Instances
  54657. if (useInstances) {
  54658. defines.push("#define INSTANCES");
  54659. attribs.push("world0");
  54660. attribs.push("world1");
  54661. attribs.push("world2");
  54662. attribs.push("world3");
  54663. }
  54664. // Get correct effect
  54665. var join = defines.join("\n");
  54666. if (this._cachedDefines !== join) {
  54667. this._cachedDefines = join;
  54668. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  54669. }
  54670. return this._effect.isReady();
  54671. };
  54672. GeometryBufferRenderer.prototype.getGBuffer = function () {
  54673. return this._multiRenderTarget;
  54674. };
  54675. // Methods
  54676. GeometryBufferRenderer.prototype.dispose = function () {
  54677. this.getGBuffer().dispose();
  54678. };
  54679. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  54680. var _this = this;
  54681. var engine = this._scene.getEngine();
  54682. var count = this._enablePosition ? 3 : 2;
  54683. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  54684. if (!this.isSupported) {
  54685. return null;
  54686. }
  54687. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54688. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54689. this._multiRenderTarget.refreshRate = 1;
  54690. this._multiRenderTarget.renderParticles = false;
  54691. this._multiRenderTarget.renderList = null;
  54692. // set default depth value to 1.0 (far away)
  54693. this._multiRenderTarget.onClearObservable.add(function (engine) {
  54694. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  54695. });
  54696. // Custom render function
  54697. var renderSubMesh = function (subMesh) {
  54698. var mesh = subMesh.getRenderingMesh();
  54699. var scene = _this._scene;
  54700. var engine = scene.getEngine();
  54701. // Culling
  54702. engine.setState(subMesh.getMaterial().backFaceCulling);
  54703. // Managing instances
  54704. var batch = mesh._getInstancesRenderList(subMesh._id);
  54705. if (batch.mustReturn) {
  54706. return;
  54707. }
  54708. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  54709. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54710. engine.enableEffect(_this._effect);
  54711. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54712. var material = subMesh.getMaterial();
  54713. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54714. _this._effect.setMatrix("view", scene.getViewMatrix());
  54715. // Alpha test
  54716. if (material && material.needAlphaTesting()) {
  54717. var alphaTexture = material.getAlphaTestTexture();
  54718. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54719. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54720. }
  54721. // Bones
  54722. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54723. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54724. }
  54725. // Draw
  54726. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54727. }
  54728. };
  54729. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  54730. var index;
  54731. if (depthOnlySubMeshes.length) {
  54732. engine.setColorWrite(false);
  54733. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  54734. renderSubMesh(depthOnlySubMeshes.data[index]);
  54735. }
  54736. engine.setColorWrite(true);
  54737. }
  54738. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54739. renderSubMesh(opaqueSubMeshes.data[index]);
  54740. }
  54741. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54742. renderSubMesh(alphaTestSubMeshes.data[index]);
  54743. }
  54744. };
  54745. };
  54746. return GeometryBufferRenderer;
  54747. }());
  54748. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  54749. })(BABYLON || (BABYLON = {}));
  54750. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  54751. var BABYLON;
  54752. (function (BABYLON) {
  54753. var RefractionPostProcess = (function (_super) {
  54754. __extends(RefractionPostProcess, _super);
  54755. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  54756. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  54757. _this.color = color;
  54758. _this.depth = depth;
  54759. _this.colorLevel = colorLevel;
  54760. _this.onActivateObservable.add(function (cam) {
  54761. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  54762. });
  54763. _this.onApplyObservable.add(function (effect) {
  54764. effect.setColor3("baseColor", _this.color);
  54765. effect.setFloat("depth", _this.depth);
  54766. effect.setFloat("colorLevel", _this.colorLevel);
  54767. effect.setTexture("refractionSampler", _this._refRexture);
  54768. });
  54769. return _this;
  54770. }
  54771. // Methods
  54772. RefractionPostProcess.prototype.dispose = function (camera) {
  54773. if (this._refRexture) {
  54774. this._refRexture.dispose();
  54775. }
  54776. _super.prototype.dispose.call(this, camera);
  54777. };
  54778. return RefractionPostProcess;
  54779. }(BABYLON.PostProcess));
  54780. BABYLON.RefractionPostProcess = RefractionPostProcess;
  54781. })(BABYLON || (BABYLON = {}));
  54782. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  54783. var BABYLON;
  54784. (function (BABYLON) {
  54785. var BlackAndWhitePostProcess = (function (_super) {
  54786. __extends(BlackAndWhitePostProcess, _super);
  54787. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  54788. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  54789. _this.degree = 1;
  54790. _this.onApplyObservable.add(function (effect) {
  54791. effect.setFloat("degree", _this.degree);
  54792. });
  54793. return _this;
  54794. }
  54795. return BlackAndWhitePostProcess;
  54796. }(BABYLON.PostProcess));
  54797. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  54798. })(BABYLON || (BABYLON = {}));
  54799. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  54800. var BABYLON;
  54801. (function (BABYLON) {
  54802. var ConvolutionPostProcess = (function (_super) {
  54803. __extends(ConvolutionPostProcess, _super);
  54804. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  54805. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  54806. _this.kernel = kernel;
  54807. _this.onApply = function (effect) {
  54808. effect.setFloat2("screenSize", _this.width, _this.height);
  54809. effect.setArray("kernel", _this.kernel);
  54810. };
  54811. return _this;
  54812. }
  54813. // Statics
  54814. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  54815. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  54816. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  54817. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  54818. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  54819. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  54820. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  54821. return ConvolutionPostProcess;
  54822. }(BABYLON.PostProcess));
  54823. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  54824. })(BABYLON || (BABYLON = {}));
  54825. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  54826. var BABYLON;
  54827. (function (BABYLON) {
  54828. var FilterPostProcess = (function (_super) {
  54829. __extends(FilterPostProcess, _super);
  54830. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  54831. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  54832. _this.kernelMatrix = kernelMatrix;
  54833. _this.onApply = function (effect) {
  54834. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  54835. };
  54836. return _this;
  54837. }
  54838. return FilterPostProcess;
  54839. }(BABYLON.PostProcess));
  54840. BABYLON.FilterPostProcess = FilterPostProcess;
  54841. })(BABYLON || (BABYLON = {}));
  54842. //# sourceMappingURL=babylon.filterPostProcess.js.map
  54843. var BABYLON;
  54844. (function (BABYLON) {
  54845. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  54846. var VolumetricLightScatteringPostProcess = (function (_super) {
  54847. __extends(VolumetricLightScatteringPostProcess, _super);
  54848. /**
  54849. * @constructor
  54850. * @param {string} name - The post-process name
  54851. * @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)
  54852. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  54853. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  54854. * @param {number} samples - The post-process quality, default 100
  54855. * @param {number} samplingMode - The post-process filtering mode
  54856. * @param {BABYLON.Engine} engine - The babylon engine
  54857. * @param {boolean} reusable - If the post-process is reusable
  54858. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  54859. */
  54860. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  54861. if (samples === void 0) { samples = 100; }
  54862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54863. 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;
  54864. _this._screenCoordinates = BABYLON.Vector2.Zero();
  54865. /**
  54866. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  54867. * @type {Vector3}
  54868. */
  54869. _this.customMeshPosition = BABYLON.Vector3.Zero();
  54870. /**
  54871. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  54872. * @type {boolean}
  54873. */
  54874. _this.useCustomMeshPosition = false;
  54875. /**
  54876. * If the post-process should inverse the light scattering direction
  54877. * @type {boolean}
  54878. */
  54879. _this.invert = true;
  54880. /**
  54881. * Array containing the excluded meshes not rendered in the internal pass
  54882. */
  54883. _this.excludedMeshes = new Array();
  54884. /**
  54885. * Controls the overall intensity of the post-process
  54886. * @type {number}
  54887. */
  54888. _this.exposure = 0.3;
  54889. /**
  54890. * Dissipates each sample's contribution in range [0, 1]
  54891. * @type {number}
  54892. */
  54893. _this.decay = 0.96815;
  54894. /**
  54895. * Controls the overall intensity of each sample
  54896. * @type {number}
  54897. */
  54898. _this.weight = 0.58767;
  54899. /**
  54900. * Controls the density of each sample
  54901. * @type {number}
  54902. */
  54903. _this.density = 0.926;
  54904. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  54905. var engine = scene.getEngine();
  54906. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  54907. // Configure mesh
  54908. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  54909. // Configure
  54910. _this._createPass(scene, ratio.passRatio || ratio);
  54911. _this.onActivate = function (camera) {
  54912. if (!_this.isSupported) {
  54913. _this.dispose(camera);
  54914. }
  54915. _this.onActivate = null;
  54916. };
  54917. _this.onApplyObservable.add(function (effect) {
  54918. _this._updateMeshScreenCoordinates(scene);
  54919. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  54920. effect.setFloat("exposure", _this.exposure);
  54921. effect.setFloat("decay", _this.decay);
  54922. effect.setFloat("weight", _this.weight);
  54923. effect.setFloat("density", _this.density);
  54924. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  54925. });
  54926. return _this;
  54927. }
  54928. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  54929. get: function () {
  54930. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54931. return false;
  54932. },
  54933. set: function (useDiffuseColor) {
  54934. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54935. },
  54936. enumerable: true,
  54937. configurable: true
  54938. });
  54939. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  54940. return "VolumetricLightScatteringPostProcess";
  54941. };
  54942. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  54943. var mesh = subMesh.getMesh();
  54944. // Render this.mesh as default
  54945. if (mesh === this.mesh) {
  54946. return mesh.material.isReady(mesh);
  54947. }
  54948. var defines = [];
  54949. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54950. var material = subMesh.getMaterial();
  54951. var needUV = false;
  54952. // Alpha test
  54953. if (material) {
  54954. if (material.needAlphaTesting()) {
  54955. defines.push("#define ALPHATEST");
  54956. }
  54957. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54958. attribs.push(BABYLON.VertexBuffer.UVKind);
  54959. defines.push("#define UV1");
  54960. }
  54961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54962. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54963. defines.push("#define UV2");
  54964. }
  54965. }
  54966. // Bones
  54967. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54970. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54971. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54972. }
  54973. else {
  54974. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54975. }
  54976. // Instances
  54977. if (useInstances) {
  54978. defines.push("#define INSTANCES");
  54979. attribs.push("world0");
  54980. attribs.push("world1");
  54981. attribs.push("world2");
  54982. attribs.push("world3");
  54983. }
  54984. // Get correct effect
  54985. var join = defines.join("\n");
  54986. if (this._cachedDefines !== join) {
  54987. this._cachedDefines = join;
  54988. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  54989. }
  54990. return this._volumetricLightScatteringPass.isReady();
  54991. };
  54992. /**
  54993. * Sets the new light position for light scattering effect
  54994. * @param {BABYLON.Vector3} The new custom light position
  54995. */
  54996. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  54997. this.customMeshPosition = position;
  54998. };
  54999. /**
  55000. * Returns the light position for light scattering effect
  55001. * @return {BABYLON.Vector3} The custom light position
  55002. */
  55003. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55004. return this.customMeshPosition;
  55005. };
  55006. /**
  55007. * Disposes the internal assets and detaches the post-process from the camera
  55008. */
  55009. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55010. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55011. if (rttIndex !== -1) {
  55012. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55013. }
  55014. this._volumetricLightScatteringRTT.dispose();
  55015. _super.prototype.dispose.call(this, camera);
  55016. };
  55017. /**
  55018. * Returns the render target texture used by the post-process
  55019. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55020. */
  55021. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55022. return this._volumetricLightScatteringRTT;
  55023. };
  55024. // Private methods
  55025. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55026. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55027. return true;
  55028. }
  55029. return false;
  55030. };
  55031. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55032. var _this = this;
  55033. var engine = scene.getEngine();
  55034. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55035. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55036. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55037. this._volumetricLightScatteringRTT.renderList = null;
  55038. this._volumetricLightScatteringRTT.renderParticles = false;
  55039. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55040. // Custom render function for submeshes
  55041. var renderSubMesh = function (subMesh) {
  55042. var mesh = subMesh.getRenderingMesh();
  55043. if (_this._meshExcluded(mesh)) {
  55044. return;
  55045. }
  55046. var scene = mesh.getScene();
  55047. var engine = scene.getEngine();
  55048. // Culling
  55049. engine.setState(subMesh.getMaterial().backFaceCulling);
  55050. // Managing instances
  55051. var batch = mesh._getInstancesRenderList(subMesh._id);
  55052. if (batch.mustReturn) {
  55053. return;
  55054. }
  55055. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55056. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55057. var effect = _this._volumetricLightScatteringPass;
  55058. if (mesh === _this.mesh) {
  55059. if (subMesh.effect) {
  55060. effect = subMesh.effect;
  55061. }
  55062. else {
  55063. effect = subMesh.getMaterial().getEffect();
  55064. }
  55065. }
  55066. engine.enableEffect(effect);
  55067. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55068. if (mesh === _this.mesh) {
  55069. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55070. }
  55071. else {
  55072. var material = subMesh.getMaterial();
  55073. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55074. // Alpha test
  55075. if (material && material.needAlphaTesting()) {
  55076. var alphaTexture = material.getAlphaTestTexture();
  55077. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55078. if (alphaTexture) {
  55079. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55080. }
  55081. }
  55082. // Bones
  55083. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55084. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55085. }
  55086. }
  55087. // Draw
  55088. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55089. }
  55090. };
  55091. // Render target texture callbacks
  55092. var savedSceneClearColor;
  55093. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55094. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55095. savedSceneClearColor = scene.clearColor;
  55096. scene.clearColor = sceneClearColor;
  55097. });
  55098. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55099. scene.clearColor = savedSceneClearColor;
  55100. });
  55101. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55102. var engine = scene.getEngine();
  55103. var index;
  55104. if (depthOnlySubMeshes.length) {
  55105. engine.setColorWrite(false);
  55106. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55107. renderSubMesh(depthOnlySubMeshes.data[index]);
  55108. }
  55109. engine.setColorWrite(true);
  55110. }
  55111. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55112. renderSubMesh(opaqueSubMeshes.data[index]);
  55113. }
  55114. engine.setAlphaTesting(true);
  55115. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55116. renderSubMesh(alphaTestSubMeshes.data[index]);
  55117. }
  55118. engine.setAlphaTesting(false);
  55119. if (transparentSubMeshes.length) {
  55120. // Sort sub meshes
  55121. for (index = 0; index < transparentSubMeshes.length; index++) {
  55122. var submesh = transparentSubMeshes.data[index];
  55123. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55124. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55125. }
  55126. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55127. sortedArray.sort(function (a, b) {
  55128. // Alpha index first
  55129. if (a._alphaIndex > b._alphaIndex) {
  55130. return 1;
  55131. }
  55132. if (a._alphaIndex < b._alphaIndex) {
  55133. return -1;
  55134. }
  55135. // Then distance to camera
  55136. if (a._distanceToCamera < b._distanceToCamera) {
  55137. return 1;
  55138. }
  55139. if (a._distanceToCamera > b._distanceToCamera) {
  55140. return -1;
  55141. }
  55142. return 0;
  55143. });
  55144. // Render sub meshes
  55145. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55146. for (index = 0; index < sortedArray.length; index++) {
  55147. renderSubMesh(sortedArray[index]);
  55148. }
  55149. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55150. }
  55151. };
  55152. };
  55153. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55154. var transform = scene.getTransformMatrix();
  55155. var meshPosition;
  55156. if (this.useCustomMeshPosition) {
  55157. meshPosition = this.customMeshPosition;
  55158. }
  55159. else if (this.attachedNode) {
  55160. meshPosition = this.attachedNode.position;
  55161. }
  55162. else {
  55163. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55164. }
  55165. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55166. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55167. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55168. if (this.invert)
  55169. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55170. };
  55171. // Static methods
  55172. /**
  55173. * Creates a default mesh for the Volumeric Light Scattering post-process
  55174. * @param {string} The mesh name
  55175. * @param {BABYLON.Scene} The scene where to create the mesh
  55176. * @return {BABYLON.Mesh} the default mesh
  55177. */
  55178. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  55179. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  55180. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55181. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  55182. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  55183. mesh.material = material;
  55184. return mesh;
  55185. };
  55186. __decorate([
  55187. BABYLON.serializeAsVector3()
  55188. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  55189. __decorate([
  55190. BABYLON.serialize()
  55191. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  55192. __decorate([
  55193. BABYLON.serialize()
  55194. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  55195. __decorate([
  55196. BABYLON.serializeAsMeshReference()
  55197. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  55198. __decorate([
  55199. BABYLON.serialize()
  55200. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  55201. __decorate([
  55202. BABYLON.serialize()
  55203. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  55204. __decorate([
  55205. BABYLON.serialize()
  55206. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  55207. __decorate([
  55208. BABYLON.serialize()
  55209. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  55210. __decorate([
  55211. BABYLON.serialize()
  55212. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  55213. return VolumetricLightScatteringPostProcess;
  55214. }(BABYLON.PostProcess));
  55215. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  55216. })(BABYLON || (BABYLON = {}));
  55217. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  55218. //
  55219. // This post-process allows the modification of rendered colors by using
  55220. // a 'look-up table' (LUT). This effect is also called Color Grading.
  55221. //
  55222. // The object needs to be provided an url to a texture containing the color
  55223. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  55224. // Use an image editing software to tweak the LUT to match your needs.
  55225. //
  55226. // For an example of a color LUT, see here:
  55227. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  55228. // For explanations on color grading, see here:
  55229. // http://udn.epicgames.com/Three/ColorGrading.html
  55230. //
  55231. var BABYLON;
  55232. (function (BABYLON) {
  55233. var ColorCorrectionPostProcess = (function (_super) {
  55234. __extends(ColorCorrectionPostProcess, _super);
  55235. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  55236. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  55237. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55238. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  55239. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55240. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55241. _this.onApply = function (effect) {
  55242. effect.setTexture("colorTable", _this._colorTableTexture);
  55243. };
  55244. return _this;
  55245. }
  55246. return ColorCorrectionPostProcess;
  55247. }(BABYLON.PostProcess));
  55248. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  55249. })(BABYLON || (BABYLON = {}));
  55250. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  55251. var BABYLON;
  55252. (function (BABYLON) {
  55253. var TonemappingOperator;
  55254. (function (TonemappingOperator) {
  55255. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  55256. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  55257. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  55258. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  55259. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  55260. ;
  55261. var TonemapPostProcess = (function (_super) {
  55262. __extends(TonemapPostProcess, _super);
  55263. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  55264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55265. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55266. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  55267. _this._operator = _operator;
  55268. _this.exposureAdjustment = exposureAdjustment;
  55269. var defines = "#define ";
  55270. if (_this._operator === TonemappingOperator.Hable)
  55271. defines += "HABLE_TONEMAPPING";
  55272. else if (_this._operator === TonemappingOperator.Reinhard)
  55273. defines += "REINHARD_TONEMAPPING";
  55274. else if (_this._operator === TonemappingOperator.HejiDawson)
  55275. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  55276. else if (_this._operator === TonemappingOperator.Photographic)
  55277. defines += "PHOTOGRAPHIC_TONEMAPPING";
  55278. //sadly a second call to create the effect.
  55279. _this.updateEffect(defines);
  55280. _this.onApply = function (effect) {
  55281. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  55282. };
  55283. return _this;
  55284. }
  55285. return TonemapPostProcess;
  55286. }(BABYLON.PostProcess));
  55287. BABYLON.TonemapPostProcess = TonemapPostProcess;
  55288. })(BABYLON || (BABYLON = {}));
  55289. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  55290. var BABYLON;
  55291. (function (BABYLON) {
  55292. var DisplayPassPostProcess = (function (_super) {
  55293. __extends(DisplayPassPostProcess, _super);
  55294. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  55295. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  55296. }
  55297. return DisplayPassPostProcess;
  55298. }(BABYLON.PostProcess));
  55299. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  55300. })(BABYLON || (BABYLON = {}));
  55301. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  55302. var BABYLON;
  55303. (function (BABYLON) {
  55304. var HighlightsPostProcess = (function (_super) {
  55305. __extends(HighlightsPostProcess, _super);
  55306. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55307. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55308. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  55309. }
  55310. return HighlightsPostProcess;
  55311. }(BABYLON.PostProcess));
  55312. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  55313. })(BABYLON || (BABYLON = {}));
  55314. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  55315. var BABYLON;
  55316. (function (BABYLON) {
  55317. var ImageProcessingPostProcess = (function (_super) {
  55318. __extends(ImageProcessingPostProcess, _super);
  55319. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55320. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55321. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  55322. _this._fromLinearSpace = true;
  55323. /**
  55324. * Defines cache preventing GC.
  55325. */
  55326. _this._defines = {
  55327. IMAGEPROCESSING: false,
  55328. VIGNETTE: false,
  55329. VIGNETTEBLENDMODEMULTIPLY: false,
  55330. VIGNETTEBLENDMODEOPAQUE: false,
  55331. TONEMAPPING: false,
  55332. CONTRAST: false,
  55333. COLORCURVES: false,
  55334. COLORGRADING: false,
  55335. FROMLINEARSPACE: false,
  55336. SAMPLER3DGREENDEPTH: false,
  55337. SAMPLER3DBGRMAP: false,
  55338. IMAGEPROCESSINGPOSTPROCESS: false,
  55339. EXPOSURE: false,
  55340. };
  55341. // Setup the default processing configuration to the scene.
  55342. _this._attachImageProcessingConfiguration(null, true);
  55343. _this.imageProcessingConfiguration.applyByPostProcess = true;
  55344. _this.onApply = function (effect) {
  55345. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  55346. };
  55347. return _this;
  55348. }
  55349. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  55350. /**
  55351. * Gets the image processing configuration used either in this material.
  55352. */
  55353. get: function () {
  55354. return this._imageProcessingConfiguration;
  55355. },
  55356. /**
  55357. * Sets the Default image processing configuration used either in the this material.
  55358. *
  55359. * If sets to null, the scene one is in use.
  55360. */
  55361. set: function (value) {
  55362. this._attachImageProcessingConfiguration(value);
  55363. },
  55364. enumerable: true,
  55365. configurable: true
  55366. });
  55367. /**
  55368. * Attaches a new image processing configuration to the PBR Material.
  55369. * @param configuration
  55370. */
  55371. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  55372. var _this = this;
  55373. if (doNotBuild === void 0) { doNotBuild = false; }
  55374. if (configuration === this._imageProcessingConfiguration) {
  55375. return;
  55376. }
  55377. // Detaches observer.
  55378. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  55379. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  55380. }
  55381. // Pick the scene configuration if needed.
  55382. if (!configuration) {
  55383. var camera = this.getCamera();
  55384. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  55385. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  55386. }
  55387. else {
  55388. this._imageProcessingConfiguration = configuration;
  55389. }
  55390. // Attaches observer.
  55391. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  55392. _this._updateParameters();
  55393. });
  55394. // Ensure the effect will be rebuilt.
  55395. if (!doNotBuild) {
  55396. this._updateParameters();
  55397. }
  55398. };
  55399. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  55400. /**
  55401. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  55402. */
  55403. get: function () {
  55404. return this.imageProcessingConfiguration.colorCurves;
  55405. },
  55406. /**
  55407. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  55408. */
  55409. set: function (value) {
  55410. this.imageProcessingConfiguration.colorCurves = value;
  55411. },
  55412. enumerable: true,
  55413. configurable: true
  55414. });
  55415. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  55416. /**
  55417. * Gets wether the color curves effect is enabled.
  55418. */
  55419. get: function () {
  55420. return this.imageProcessingConfiguration.colorCurvesEnabled;
  55421. },
  55422. /**
  55423. * Sets wether the color curves effect is enabled.
  55424. */
  55425. set: function (value) {
  55426. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  55427. },
  55428. enumerable: true,
  55429. configurable: true
  55430. });
  55431. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  55432. /**
  55433. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  55434. */
  55435. get: function () {
  55436. return this.imageProcessingConfiguration.colorGradingTexture;
  55437. },
  55438. /**
  55439. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  55440. */
  55441. set: function (value) {
  55442. this.imageProcessingConfiguration.colorGradingTexture = value;
  55443. },
  55444. enumerable: true,
  55445. configurable: true
  55446. });
  55447. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  55448. /**
  55449. * Gets wether the color grading effect is enabled.
  55450. */
  55451. get: function () {
  55452. return this.imageProcessingConfiguration.colorGradingEnabled;
  55453. },
  55454. /**
  55455. * Gets wether the color grading effect is enabled.
  55456. */
  55457. set: function (value) {
  55458. this.imageProcessingConfiguration.colorGradingEnabled = value;
  55459. },
  55460. enumerable: true,
  55461. configurable: true
  55462. });
  55463. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  55464. /**
  55465. * Gets exposure used in the effect.
  55466. */
  55467. get: function () {
  55468. return this.imageProcessingConfiguration.exposure;
  55469. },
  55470. /**
  55471. * Sets exposure used in the effect.
  55472. */
  55473. set: function (value) {
  55474. this.imageProcessingConfiguration.exposure = value;
  55475. },
  55476. enumerable: true,
  55477. configurable: true
  55478. });
  55479. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  55480. /**
  55481. * Gets wether tonemapping is enabled or not.
  55482. */
  55483. get: function () {
  55484. return this._imageProcessingConfiguration.toneMappingEnabled;
  55485. },
  55486. /**
  55487. * Sets wether tonemapping is enabled or not
  55488. */
  55489. set: function (value) {
  55490. this._imageProcessingConfiguration.toneMappingEnabled = value;
  55491. },
  55492. enumerable: true,
  55493. configurable: true
  55494. });
  55495. ;
  55496. ;
  55497. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  55498. /**
  55499. * Gets contrast used in the effect.
  55500. */
  55501. get: function () {
  55502. return this.imageProcessingConfiguration.contrast;
  55503. },
  55504. /**
  55505. * Sets contrast used in the effect.
  55506. */
  55507. set: function (value) {
  55508. this.imageProcessingConfiguration.contrast = value;
  55509. },
  55510. enumerable: true,
  55511. configurable: true
  55512. });
  55513. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  55514. /**
  55515. * Gets Vignette stretch size.
  55516. */
  55517. get: function () {
  55518. return this.imageProcessingConfiguration.vignetteStretch;
  55519. },
  55520. /**
  55521. * Sets Vignette stretch size.
  55522. */
  55523. set: function (value) {
  55524. this.imageProcessingConfiguration.vignetteStretch = value;
  55525. },
  55526. enumerable: true,
  55527. configurable: true
  55528. });
  55529. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  55530. /**
  55531. * Gets Vignette centre X Offset.
  55532. */
  55533. get: function () {
  55534. return this.imageProcessingConfiguration.vignetteCentreX;
  55535. },
  55536. /**
  55537. * Sets Vignette centre X Offset.
  55538. */
  55539. set: function (value) {
  55540. this.imageProcessingConfiguration.vignetteCentreX = value;
  55541. },
  55542. enumerable: true,
  55543. configurable: true
  55544. });
  55545. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  55546. /**
  55547. * Gets Vignette centre Y Offset.
  55548. */
  55549. get: function () {
  55550. return this.imageProcessingConfiguration.vignetteCentreY;
  55551. },
  55552. /**
  55553. * Sets Vignette centre Y Offset.
  55554. */
  55555. set: function (value) {
  55556. this.imageProcessingConfiguration.vignetteCentreY = value;
  55557. },
  55558. enumerable: true,
  55559. configurable: true
  55560. });
  55561. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  55562. /**
  55563. * Gets Vignette weight or intensity of the vignette effect.
  55564. */
  55565. get: function () {
  55566. return this.imageProcessingConfiguration.vignetteWeight;
  55567. },
  55568. /**
  55569. * Sets Vignette weight or intensity of the vignette effect.
  55570. */
  55571. set: function (value) {
  55572. this.imageProcessingConfiguration.vignetteWeight = value;
  55573. },
  55574. enumerable: true,
  55575. configurable: true
  55576. });
  55577. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  55578. /**
  55579. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  55580. * if vignetteEnabled is set to true.
  55581. */
  55582. get: function () {
  55583. return this.imageProcessingConfiguration.vignetteColor;
  55584. },
  55585. /**
  55586. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  55587. * if vignetteEnabled is set to true.
  55588. */
  55589. set: function (value) {
  55590. this.imageProcessingConfiguration.vignetteColor = value;
  55591. },
  55592. enumerable: true,
  55593. configurable: true
  55594. });
  55595. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  55596. /**
  55597. * Gets Camera field of view used by the Vignette effect.
  55598. */
  55599. get: function () {
  55600. return this.imageProcessingConfiguration.vignetteCameraFov;
  55601. },
  55602. /**
  55603. * Sets Camera field of view used by the Vignette effect.
  55604. */
  55605. set: function (value) {
  55606. this.imageProcessingConfiguration.vignetteCameraFov = value;
  55607. },
  55608. enumerable: true,
  55609. configurable: true
  55610. });
  55611. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  55612. /**
  55613. * Gets the vignette blend mode allowing different kind of effect.
  55614. */
  55615. get: function () {
  55616. return this.imageProcessingConfiguration.vignetteBlendMode;
  55617. },
  55618. /**
  55619. * Sets the vignette blend mode allowing different kind of effect.
  55620. */
  55621. set: function (value) {
  55622. this.imageProcessingConfiguration.vignetteBlendMode = value;
  55623. },
  55624. enumerable: true,
  55625. configurable: true
  55626. });
  55627. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  55628. /**
  55629. * Gets wether the vignette effect is enabled.
  55630. */
  55631. get: function () {
  55632. return this.imageProcessingConfiguration.vignetteEnabled;
  55633. },
  55634. /**
  55635. * Sets wether the vignette effect is enabled.
  55636. */
  55637. set: function (value) {
  55638. this.imageProcessingConfiguration.vignetteEnabled = value;
  55639. },
  55640. enumerable: true,
  55641. configurable: true
  55642. });
  55643. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  55644. /**
  55645. * Gets wether the input of the processing is in Gamma or Linear Space.
  55646. */
  55647. get: function () {
  55648. return this._fromLinearSpace;
  55649. },
  55650. /**
  55651. * Sets wether the input of the processing is in Gamma or Linear Space.
  55652. */
  55653. set: function (value) {
  55654. if (this._fromLinearSpace === value) {
  55655. return;
  55656. }
  55657. this._fromLinearSpace = value;
  55658. this._updateParameters();
  55659. },
  55660. enumerable: true,
  55661. configurable: true
  55662. });
  55663. ImageProcessingPostProcess.prototype.getClassName = function () {
  55664. return "ImageProcessingPostProcess";
  55665. };
  55666. ImageProcessingPostProcess.prototype._updateParameters = function () {
  55667. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  55668. this.imageProcessingConfiguration.prepareDefines(this._defines);
  55669. var defines = "";
  55670. for (var define in this._defines) {
  55671. if (this._defines[define]) {
  55672. defines += "#define " + define + ";\r\n";
  55673. }
  55674. }
  55675. var samplers = ["textureSampler"];
  55676. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  55677. var uniforms = ["scale"];
  55678. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  55679. this.updateEffect(defines, uniforms, samplers);
  55680. };
  55681. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  55682. _super.prototype.dispose.call(this, camera);
  55683. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  55684. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  55685. }
  55686. this.imageProcessingConfiguration.applyByPostProcess = false;
  55687. };
  55688. __decorate([
  55689. BABYLON.serialize()
  55690. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  55691. return ImageProcessingPostProcess;
  55692. }(BABYLON.PostProcess));
  55693. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  55694. })(BABYLON || (BABYLON = {}));
  55695. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  55696. var BABYLON;
  55697. (function (BABYLON) {
  55698. var BlurPostProcess = (function (_super) {
  55699. __extends(BlurPostProcess, _super);
  55700. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  55701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55702. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55703. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  55704. _this.direction = direction;
  55705. _this._packedFloat = false;
  55706. _this.onApplyObservable.add(function (effect) {
  55707. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  55708. });
  55709. _this.kernel = kernel;
  55710. return _this;
  55711. }
  55712. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  55713. /**
  55714. * Gets the length in pixels of the blur sample region
  55715. */
  55716. get: function () {
  55717. return this._idealKernel;
  55718. },
  55719. /**
  55720. * Sets the length in pixels of the blur sample region
  55721. */
  55722. set: function (v) {
  55723. if (this._idealKernel === v) {
  55724. return;
  55725. }
  55726. v = Math.max(v, 1);
  55727. this._idealKernel = v;
  55728. this._kernel = this._nearestBestKernel(v);
  55729. this._updateParameters();
  55730. },
  55731. enumerable: true,
  55732. configurable: true
  55733. });
  55734. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  55735. /**
  55736. * Gets wether or not the blur is unpacking/repacking floats
  55737. */
  55738. get: function () {
  55739. return this._packedFloat;
  55740. },
  55741. /**
  55742. * Sets wether or not the blur needs to unpack/repack floats
  55743. */
  55744. set: function (v) {
  55745. if (this._packedFloat === v) {
  55746. return;
  55747. }
  55748. this._packedFloat = v;
  55749. this._updateParameters();
  55750. },
  55751. enumerable: true,
  55752. configurable: true
  55753. });
  55754. BlurPostProcess.prototype._updateParameters = function () {
  55755. // Generate sampling offsets and weights
  55756. var N = this._kernel;
  55757. var centerIndex = (N - 1) / 2;
  55758. // Generate Gaussian sampling weights over kernel
  55759. var offsets = [];
  55760. var weights = [];
  55761. var totalWeight = 0;
  55762. for (var i = 0; i < N; i++) {
  55763. var u = i / (N - 1);
  55764. var w = this._gaussianWeight(u * 2.0 - 1);
  55765. offsets[i] = (i - centerIndex);
  55766. weights[i] = w;
  55767. totalWeight += w;
  55768. }
  55769. // Normalize weights
  55770. for (var i = 0; i < weights.length; i++) {
  55771. weights[i] /= totalWeight;
  55772. }
  55773. // Optimize: combine samples to take advantage of hardware linear sampling
  55774. // Walk from left to center, combining pairs (symmetrically)
  55775. var linearSamplingWeights = [];
  55776. var linearSamplingOffsets = [];
  55777. var linearSamplingMap = [];
  55778. for (var i = 0; i <= centerIndex; i += 2) {
  55779. var j = Math.min(i + 1, Math.floor(centerIndex));
  55780. var singleCenterSample = i === j;
  55781. if (singleCenterSample) {
  55782. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55783. }
  55784. else {
  55785. var sharedCell = j === centerIndex;
  55786. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  55787. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  55788. if (offsetLinear === 0) {
  55789. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55790. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  55791. }
  55792. else {
  55793. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  55794. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  55795. }
  55796. }
  55797. }
  55798. for (var i = 0; i < linearSamplingMap.length; i++) {
  55799. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  55800. linearSamplingWeights[i] = linearSamplingMap[i].w;
  55801. }
  55802. // Replace with optimized
  55803. offsets = linearSamplingOffsets;
  55804. weights = linearSamplingWeights;
  55805. // Generate shaders
  55806. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  55807. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  55808. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  55809. var defines = "";
  55810. for (var i = 0; i < varyingCount; i++) {
  55811. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  55812. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  55813. }
  55814. var depCount = 0;
  55815. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  55816. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  55817. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  55818. depCount++;
  55819. }
  55820. if (this.packedFloat) {
  55821. defines += "#define PACKEDFLOAT 1";
  55822. }
  55823. this.updateEffect(defines, null, null, {
  55824. varyingCount: varyingCount,
  55825. depCount: depCount
  55826. });
  55827. };
  55828. /**
  55829. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  55830. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  55831. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  55832. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  55833. * The gaps between physical kernels are compensated for in the weighting of the samples
  55834. * @param idealKernel Ideal blur kernel.
  55835. * @return Nearest best kernel.
  55836. */
  55837. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  55838. var v = Math.round(idealKernel);
  55839. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  55840. var k = _a[_i];
  55841. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  55842. return Math.max(k, 3);
  55843. }
  55844. }
  55845. return Math.max(v, 3);
  55846. };
  55847. /**
  55848. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  55849. * @param x The point on the Gaussian distribution to sample.
  55850. * @return the value of the Gaussian function at x.
  55851. */
  55852. BlurPostProcess.prototype._gaussianWeight = function (x) {
  55853. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  55854. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  55855. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  55856. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  55857. // truncated at around 1.3% of peak strength.
  55858. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  55859. var sigma = (1 / 3);
  55860. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  55861. var exponent = -((x * x) / (2.0 * sigma * sigma));
  55862. var weight = (1.0 / denominator) * Math.exp(exponent);
  55863. return weight;
  55864. };
  55865. /**
  55866. * Generates a string that can be used as a floating point number in GLSL.
  55867. * @param x Value to print.
  55868. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  55869. * @return GLSL float string.
  55870. */
  55871. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  55872. if (decimalFigures === void 0) { decimalFigures = 8; }
  55873. return x.toFixed(decimalFigures).replace(/0+$/, '');
  55874. };
  55875. return BlurPostProcess;
  55876. }(BABYLON.PostProcess));
  55877. BABYLON.BlurPostProcess = BlurPostProcess;
  55878. })(BABYLON || (BABYLON = {}));
  55879. //# sourceMappingURL=babylon.blurPostProcess.js.map
  55880. /// <reference path="..\babylon.node.ts" />
  55881. var BABYLON;
  55882. (function (BABYLON) {
  55883. var Bone = (function (_super) {
  55884. __extends(Bone, _super);
  55885. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  55886. if (parentBone === void 0) { parentBone = null; }
  55887. var _this = _super.call(this, name, skeleton.getScene()) || this;
  55888. _this.name = name;
  55889. _this.children = new Array();
  55890. _this.animations = new Array();
  55891. _this._worldTransform = new BABYLON.Matrix();
  55892. _this._absoluteTransform = new BABYLON.Matrix();
  55893. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  55894. _this._scaleMatrix = BABYLON.Matrix.Identity();
  55895. _this._scaleVector = BABYLON.Vector3.One();
  55896. _this._negateScaleChildren = BABYLON.Vector3.One();
  55897. _this._scalingDeterminant = 1;
  55898. _this._skeleton = skeleton;
  55899. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  55900. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  55901. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  55902. _this._index = index;
  55903. skeleton.bones.push(_this);
  55904. _this.setParent(parentBone, false);
  55905. _this._updateDifferenceMatrix();
  55906. return _this;
  55907. }
  55908. Object.defineProperty(Bone.prototype, "_matrix", {
  55909. get: function () {
  55910. return this._localMatrix;
  55911. },
  55912. set: function (val) {
  55913. if (this._localMatrix) {
  55914. this._localMatrix.copyFrom(val);
  55915. }
  55916. else {
  55917. this._localMatrix = val;
  55918. }
  55919. },
  55920. enumerable: true,
  55921. configurable: true
  55922. });
  55923. // Members
  55924. Bone.prototype.getSkeleton = function () {
  55925. return this._skeleton;
  55926. };
  55927. Bone.prototype.getParent = function () {
  55928. return this._parent;
  55929. };
  55930. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  55931. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  55932. if (this._parent === parent) {
  55933. return;
  55934. }
  55935. if (this._parent) {
  55936. var index = this._parent.children.indexOf(this);
  55937. if (index !== -1) {
  55938. this._parent.children.splice(index);
  55939. }
  55940. }
  55941. this._parent = parent;
  55942. if (this._parent) {
  55943. this._parent.children.push(this);
  55944. }
  55945. if (updateDifferenceMatrix) {
  55946. this._updateDifferenceMatrix();
  55947. }
  55948. };
  55949. Bone.prototype.getLocalMatrix = function () {
  55950. return this._localMatrix;
  55951. };
  55952. Bone.prototype.getBaseMatrix = function () {
  55953. return this._baseMatrix;
  55954. };
  55955. Bone.prototype.getRestPose = function () {
  55956. return this._restPose;
  55957. };
  55958. Bone.prototype.returnToRest = function () {
  55959. this.updateMatrix(this._restPose.clone());
  55960. };
  55961. Bone.prototype.getWorldMatrix = function () {
  55962. return this._worldTransform;
  55963. };
  55964. Bone.prototype.getInvertedAbsoluteTransform = function () {
  55965. return this._invertedAbsoluteTransform;
  55966. };
  55967. Bone.prototype.getAbsoluteTransform = function () {
  55968. return this._absoluteTransform;
  55969. };
  55970. Object.defineProperty(Bone.prototype, "position", {
  55971. // Properties (matches AbstractMesh properties)
  55972. get: function () {
  55973. return this.getPosition();
  55974. },
  55975. set: function (newPosition) {
  55976. this.setPosition(newPosition);
  55977. },
  55978. enumerable: true,
  55979. configurable: true
  55980. });
  55981. Object.defineProperty(Bone.prototype, "rotation", {
  55982. get: function () {
  55983. return this.getRotation();
  55984. },
  55985. set: function (newRotation) {
  55986. this.setRotation(newRotation);
  55987. },
  55988. enumerable: true,
  55989. configurable: true
  55990. });
  55991. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  55992. get: function () {
  55993. return this.getRotationQuaternion();
  55994. },
  55995. set: function (newRotation) {
  55996. this.setRotationQuaternion(newRotation);
  55997. },
  55998. enumerable: true,
  55999. configurable: true
  56000. });
  56001. Object.defineProperty(Bone.prototype, "scaling", {
  56002. get: function () {
  56003. return this.getScale();
  56004. },
  56005. set: function (newScaling) {
  56006. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  56007. },
  56008. enumerable: true,
  56009. configurable: true
  56010. });
  56011. // Methods
  56012. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  56013. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  56014. this._baseMatrix = matrix.clone();
  56015. this._localMatrix = matrix.clone();
  56016. this._skeleton._markAsDirty();
  56017. if (updateDifferenceMatrix) {
  56018. this._updateDifferenceMatrix();
  56019. }
  56020. };
  56021. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  56022. if (!rootMatrix) {
  56023. rootMatrix = this._baseMatrix;
  56024. }
  56025. if (this._parent) {
  56026. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  56027. }
  56028. else {
  56029. this._absoluteTransform.copyFrom(rootMatrix);
  56030. }
  56031. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  56032. for (var index = 0; index < this.children.length; index++) {
  56033. this.children[index]._updateDifferenceMatrix();
  56034. }
  56035. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  56036. };
  56037. Bone.prototype.markAsDirty = function () {
  56038. this._currentRenderId++;
  56039. this._skeleton._markAsDirty();
  56040. };
  56041. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  56042. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  56043. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  56044. // all animation may be coming from a library skeleton, so may need to create animation
  56045. if (this.animations.length === 0) {
  56046. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  56047. this.animations[0].setKeys([]);
  56048. }
  56049. // get animation info / verify there is such a range from the source bone
  56050. var sourceRange = source.animations[0].getRange(rangeName);
  56051. if (!sourceRange) {
  56052. return false;
  56053. }
  56054. var from = sourceRange.from;
  56055. var to = sourceRange.to;
  56056. var sourceKeys = source.animations[0].getKeys();
  56057. // rescaling prep
  56058. var sourceBoneLength = source.length;
  56059. var sourceParent = source.getParent();
  56060. var parent = this.getParent();
  56061. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  56062. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  56063. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  56064. var destKeys = this.animations[0].getKeys();
  56065. // loop vars declaration
  56066. var orig;
  56067. var origTranslation;
  56068. var mat;
  56069. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  56070. orig = sourceKeys[key];
  56071. if (orig.frame >= from && orig.frame <= to) {
  56072. if (rescaleAsRequired) {
  56073. mat = orig.value.clone();
  56074. // scale based on parent ratio, when bone has parent
  56075. if (parentScalingReqd) {
  56076. origTranslation = mat.getTranslation();
  56077. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  56078. // scale based on skeleton dimension ratio when root bone, and value is passed
  56079. }
  56080. else if (dimensionsScalingReqd) {
  56081. origTranslation = mat.getTranslation();
  56082. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  56083. // use original when root bone, and no data for skelDimensionsRatio
  56084. }
  56085. else {
  56086. mat = orig.value;
  56087. }
  56088. }
  56089. else {
  56090. mat = orig.value;
  56091. }
  56092. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  56093. }
  56094. }
  56095. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  56096. return true;
  56097. };
  56098. /**
  56099. * Translate the bone in local or world space.
  56100. * @param vec The amount to translate the bone.
  56101. * @param space The space that the translation is in.
  56102. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56103. */
  56104. Bone.prototype.translate = function (vec, space, mesh) {
  56105. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56106. var lm = this.getLocalMatrix();
  56107. if (space == BABYLON.Space.LOCAL) {
  56108. lm.m[12] += vec.x;
  56109. lm.m[13] += vec.y;
  56110. lm.m[14] += vec.z;
  56111. }
  56112. else {
  56113. var wm;
  56114. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56115. if (mesh) {
  56116. wm = mesh.getWorldMatrix();
  56117. }
  56118. this._skeleton.computeAbsoluteTransforms();
  56119. var tmat = Bone._tmpMats[0];
  56120. var tvec = Bone._tmpVecs[0];
  56121. if (mesh) {
  56122. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56123. tmat.multiplyToRef(wm, tmat);
  56124. }
  56125. else {
  56126. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56127. }
  56128. tmat.m[12] = 0;
  56129. tmat.m[13] = 0;
  56130. tmat.m[14] = 0;
  56131. tmat.invert();
  56132. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  56133. lm.m[12] += tvec.x;
  56134. lm.m[13] += tvec.y;
  56135. lm.m[14] += tvec.z;
  56136. }
  56137. this.markAsDirty();
  56138. };
  56139. /**
  56140. * Set the postion of the bone in local or world space.
  56141. * @param position The position to set the bone.
  56142. * @param space The space that the position is in.
  56143. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56144. */
  56145. Bone.prototype.setPosition = function (position, space, mesh) {
  56146. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56147. var lm = this.getLocalMatrix();
  56148. if (space == BABYLON.Space.LOCAL) {
  56149. lm.m[12] = position.x;
  56150. lm.m[13] = position.y;
  56151. lm.m[14] = position.z;
  56152. }
  56153. else {
  56154. var wm;
  56155. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56156. if (mesh) {
  56157. wm = mesh.getWorldMatrix();
  56158. }
  56159. this._skeleton.computeAbsoluteTransforms();
  56160. var tmat = Bone._tmpMats[0];
  56161. var vec = Bone._tmpVecs[0];
  56162. if (mesh) {
  56163. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56164. tmat.multiplyToRef(wm, tmat);
  56165. }
  56166. else {
  56167. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56168. }
  56169. tmat.invert();
  56170. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  56171. lm.m[12] = vec.x;
  56172. lm.m[13] = vec.y;
  56173. lm.m[14] = vec.z;
  56174. }
  56175. this.markAsDirty();
  56176. };
  56177. /**
  56178. * Set the absolute postion of the bone (world space).
  56179. * @param position The position to set the bone.
  56180. * @param mesh The mesh that this bone is attached to.
  56181. */
  56182. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  56183. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  56184. };
  56185. /**
  56186. * Set the scale of the bone on the x, y and z axes.
  56187. * @param x The scale of the bone on the x axis.
  56188. * @param x The scale of the bone on the y axis.
  56189. * @param z The scale of the bone on the z axis.
  56190. * @param scaleChildren Set this to true if children of the bone should be scaled.
  56191. */
  56192. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  56193. if (scaleChildren === void 0) { scaleChildren = false; }
  56194. if (this.animations[0] && !this.animations[0].isStopped()) {
  56195. if (!scaleChildren) {
  56196. this._negateScaleChildren.x = 1 / x;
  56197. this._negateScaleChildren.y = 1 / y;
  56198. this._negateScaleChildren.z = 1 / z;
  56199. }
  56200. this._syncScaleVector();
  56201. }
  56202. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  56203. };
  56204. /**
  56205. * Scale the bone on the x, y and z axes.
  56206. * @param x The amount to scale the bone on the x axis.
  56207. * @param x The amount to scale the bone on the y axis.
  56208. * @param z The amount to scale the bone on the z axis.
  56209. * @param scaleChildren Set this to true if children of the bone should be scaled.
  56210. */
  56211. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  56212. if (scaleChildren === void 0) { scaleChildren = false; }
  56213. var locMat = this.getLocalMatrix();
  56214. var origLocMat = Bone._tmpMats[0];
  56215. origLocMat.copyFrom(locMat);
  56216. var origLocMatInv = Bone._tmpMats[1];
  56217. origLocMatInv.copyFrom(origLocMat);
  56218. origLocMatInv.invert();
  56219. var scaleMat = Bone._tmpMats[2];
  56220. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  56221. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  56222. this._scaleVector.x *= x;
  56223. this._scaleVector.y *= y;
  56224. this._scaleVector.z *= z;
  56225. locMat.multiplyToRef(origLocMatInv, locMat);
  56226. locMat.multiplyToRef(scaleMat, locMat);
  56227. locMat.multiplyToRef(origLocMat, locMat);
  56228. var parent = this.getParent();
  56229. if (parent) {
  56230. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  56231. }
  56232. else {
  56233. this.getAbsoluteTransform().copyFrom(locMat);
  56234. }
  56235. var len = this.children.length;
  56236. scaleMat.invert();
  56237. for (var i = 0; i < len; i++) {
  56238. var child = this.children[i];
  56239. var cm = child.getLocalMatrix();
  56240. cm.multiplyToRef(scaleMat, cm);
  56241. var lm = child.getLocalMatrix();
  56242. lm.m[12] *= x;
  56243. lm.m[13] *= y;
  56244. lm.m[14] *= z;
  56245. }
  56246. this.computeAbsoluteTransforms();
  56247. if (scaleChildren) {
  56248. for (var i = 0; i < len; i++) {
  56249. this.children[i].scale(x, y, z, scaleChildren);
  56250. }
  56251. }
  56252. this.markAsDirty();
  56253. };
  56254. /**
  56255. * Set the yaw, pitch, and roll of the bone in local or world space.
  56256. * @param yaw The rotation of the bone on the y axis.
  56257. * @param pitch The rotation of the bone on the x axis.
  56258. * @param roll The rotation of the bone on the z axis.
  56259. * @param space The space that the axes of rotation are in.
  56260. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56261. */
  56262. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  56263. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56264. var rotMat = Bone._tmpMats[0];
  56265. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  56266. var rotMatInv = Bone._tmpMats[1];
  56267. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56268. rotMatInv.multiplyToRef(rotMat, rotMat);
  56269. this._rotateWithMatrix(rotMat, space, mesh);
  56270. };
  56271. /**
  56272. * Rotate the bone on an axis in local or world space.
  56273. * @param axis The axis to rotate the bone on.
  56274. * @param amount The amount to rotate the bone.
  56275. * @param space The space that the axis is in.
  56276. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56277. */
  56278. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  56279. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56280. var rmat = Bone._tmpMats[0];
  56281. rmat.m[12] = 0;
  56282. rmat.m[13] = 0;
  56283. rmat.m[14] = 0;
  56284. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  56285. this._rotateWithMatrix(rmat, space, mesh);
  56286. };
  56287. /**
  56288. * Set the rotation of the bone to a particular axis angle in local or world space.
  56289. * @param axis The axis to rotate the bone on.
  56290. * @param angle The angle that the bone should be rotated to.
  56291. * @param space The space that the axis is in.
  56292. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56293. */
  56294. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  56295. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56296. var rotMat = Bone._tmpMats[0];
  56297. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  56298. var rotMatInv = Bone._tmpMats[1];
  56299. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56300. rotMatInv.multiplyToRef(rotMat, rotMat);
  56301. this._rotateWithMatrix(rotMat, space, mesh);
  56302. };
  56303. /**
  56304. * Set the euler rotation of the bone in local of world space.
  56305. * @param rotation The euler rotation that the bone should be set to.
  56306. * @param space The space that the rotation is in.
  56307. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56308. */
  56309. Bone.prototype.setRotation = function (rotation, space, mesh) {
  56310. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56311. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  56312. };
  56313. /**
  56314. * Set the quaternion rotation of the bone in local of world space.
  56315. * @param quat The quaternion rotation that the bone should be set to.
  56316. * @param space The space that the rotation is in.
  56317. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56318. */
  56319. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  56320. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56321. var rotMatInv = Bone._tmpMats[0];
  56322. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56323. var rotMat = Bone._tmpMats[1];
  56324. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  56325. rotMatInv.multiplyToRef(rotMat, rotMat);
  56326. this._rotateWithMatrix(rotMat, space, mesh);
  56327. };
  56328. /**
  56329. * Set the rotation matrix of the bone in local of world space.
  56330. * @param rotMat The rotation matrix that the bone should be set to.
  56331. * @param space The space that the rotation is in.
  56332. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56333. */
  56334. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  56335. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56336. var rotMatInv = Bone._tmpMats[0];
  56337. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56338. var rotMat2 = Bone._tmpMats[1];
  56339. rotMat2.copyFrom(rotMat);
  56340. rotMatInv.multiplyToRef(rotMat, rotMat2);
  56341. this._rotateWithMatrix(rotMat2, space, mesh);
  56342. };
  56343. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  56344. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56345. var lmat = this.getLocalMatrix();
  56346. var lx = lmat.m[12];
  56347. var ly = lmat.m[13];
  56348. var lz = lmat.m[14];
  56349. var parent = this.getParent();
  56350. var parentScale = Bone._tmpMats[3];
  56351. var parentScaleInv = Bone._tmpMats[4];
  56352. if (parent) {
  56353. if (space == BABYLON.Space.WORLD) {
  56354. if (mesh) {
  56355. parentScale.copyFrom(mesh.getWorldMatrix());
  56356. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  56357. }
  56358. else {
  56359. parentScale.copyFrom(parent.getAbsoluteTransform());
  56360. }
  56361. }
  56362. else {
  56363. parentScale = parent._scaleMatrix;
  56364. }
  56365. parentScaleInv.copyFrom(parentScale);
  56366. parentScaleInv.invert();
  56367. lmat.multiplyToRef(parentScale, lmat);
  56368. lmat.multiplyToRef(rmat, lmat);
  56369. lmat.multiplyToRef(parentScaleInv, lmat);
  56370. }
  56371. else {
  56372. if (space == BABYLON.Space.WORLD && mesh) {
  56373. parentScale.copyFrom(mesh.getWorldMatrix());
  56374. parentScaleInv.copyFrom(parentScale);
  56375. parentScaleInv.invert();
  56376. lmat.multiplyToRef(parentScale, lmat);
  56377. lmat.multiplyToRef(rmat, lmat);
  56378. lmat.multiplyToRef(parentScaleInv, lmat);
  56379. }
  56380. else {
  56381. lmat.multiplyToRef(rmat, lmat);
  56382. }
  56383. }
  56384. lmat.m[12] = lx;
  56385. lmat.m[13] = ly;
  56386. lmat.m[14] = lz;
  56387. this.computeAbsoluteTransforms();
  56388. this.markAsDirty();
  56389. };
  56390. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  56391. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56392. if (space == BABYLON.Space.WORLD) {
  56393. var scaleMatrix = Bone._tmpMats[2];
  56394. scaleMatrix.copyFrom(this._scaleMatrix);
  56395. rotMatInv.copyFrom(this.getAbsoluteTransform());
  56396. if (mesh) {
  56397. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  56398. var meshScale = Bone._tmpMats[3];
  56399. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  56400. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  56401. }
  56402. rotMatInv.invert();
  56403. scaleMatrix.m[0] *= this._scalingDeterminant;
  56404. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  56405. }
  56406. else {
  56407. rotMatInv.copyFrom(this.getLocalMatrix());
  56408. rotMatInv.invert();
  56409. var scaleMatrix = Bone._tmpMats[2];
  56410. scaleMatrix.copyFrom(this._scaleMatrix);
  56411. if (this._parent) {
  56412. var pscaleMatrix = Bone._tmpMats[3];
  56413. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  56414. pscaleMatrix.invert();
  56415. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  56416. }
  56417. else {
  56418. scaleMatrix.m[0] *= this._scalingDeterminant;
  56419. }
  56420. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  56421. }
  56422. };
  56423. /**
  56424. * Get the scale of the bone
  56425. * @returns the scale of the bone
  56426. */
  56427. Bone.prototype.getScale = function () {
  56428. return this._scaleVector.clone();
  56429. };
  56430. /**
  56431. * Copy the scale of the bone to a vector3.
  56432. * @param result The vector3 to copy the scale to
  56433. */
  56434. Bone.prototype.getScaleToRef = function (result) {
  56435. result.copyFrom(this._scaleVector);
  56436. };
  56437. /**
  56438. * Get the position of the bone in local or world space.
  56439. * @param space The space that the returned position is in.
  56440. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56441. * @returns The position of the bone
  56442. */
  56443. Bone.prototype.getPosition = function (space, mesh) {
  56444. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56445. var pos = BABYLON.Vector3.Zero();
  56446. this.getPositionToRef(space, mesh, pos);
  56447. return pos;
  56448. };
  56449. /**
  56450. * Copy the position of the bone to a vector3 in local or world space.
  56451. * @param space The space that the returned position is in.
  56452. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56453. * @param result The vector3 to copy the position to.
  56454. */
  56455. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  56456. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56457. if (space == BABYLON.Space.LOCAL) {
  56458. var lm = this.getLocalMatrix();
  56459. result.x = lm.m[12];
  56460. result.y = lm.m[13];
  56461. result.z = lm.m[14];
  56462. }
  56463. else {
  56464. var wm;
  56465. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56466. if (mesh) {
  56467. wm = mesh.getWorldMatrix();
  56468. }
  56469. this._skeleton.computeAbsoluteTransforms();
  56470. var tmat = Bone._tmpMats[0];
  56471. if (mesh) {
  56472. tmat.copyFrom(this.getAbsoluteTransform());
  56473. tmat.multiplyToRef(wm, tmat);
  56474. }
  56475. else {
  56476. tmat = this.getAbsoluteTransform();
  56477. }
  56478. result.x = tmat.m[12];
  56479. result.y = tmat.m[13];
  56480. result.z = tmat.m[14];
  56481. }
  56482. };
  56483. /**
  56484. * Get the absolute position of the bone (world space).
  56485. * @param mesh The mesh that this bone is attached to.
  56486. * @returns The absolute position of the bone
  56487. */
  56488. Bone.prototype.getAbsolutePosition = function (mesh) {
  56489. var pos = BABYLON.Vector3.Zero();
  56490. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  56491. return pos;
  56492. };
  56493. /**
  56494. * Copy the absolute position of the bone (world space) to the result param.
  56495. * @param mesh The mesh that this bone is attached to.
  56496. * @param result The vector3 to copy the absolute position to.
  56497. */
  56498. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  56499. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  56500. };
  56501. /**
  56502. * Compute the absolute transforms of this bone and its children.
  56503. */
  56504. Bone.prototype.computeAbsoluteTransforms = function () {
  56505. if (this._parent) {
  56506. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  56507. }
  56508. else {
  56509. this._absoluteTransform.copyFrom(this._localMatrix);
  56510. var poseMatrix = this._skeleton.getPoseMatrix();
  56511. if (poseMatrix) {
  56512. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  56513. }
  56514. }
  56515. var children = this.children;
  56516. var len = children.length;
  56517. for (var i = 0; i < len; i++) {
  56518. children[i].computeAbsoluteTransforms();
  56519. }
  56520. };
  56521. Bone.prototype._syncScaleVector = function () {
  56522. var lm = this.getLocalMatrix();
  56523. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  56524. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  56525. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  56526. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  56527. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  56528. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  56529. this._scaleVector.x = xs * Math.sqrt(xsq);
  56530. this._scaleVector.y = ys * Math.sqrt(ysq);
  56531. this._scaleVector.z = zs * Math.sqrt(zsq);
  56532. if (this._parent) {
  56533. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  56534. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  56535. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  56536. }
  56537. 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);
  56538. };
  56539. /**
  56540. * Get the world direction from an axis that is in the local space of the bone.
  56541. * @param localAxis The local direction that is used to compute the world direction.
  56542. * @param mesh The mesh that this bone is attached to.
  56543. * @returns The world direction
  56544. */
  56545. Bone.prototype.getDirection = function (localAxis, mesh) {
  56546. var result = BABYLON.Vector3.Zero();
  56547. this.getDirectionToRef(localAxis, mesh, result);
  56548. return result;
  56549. };
  56550. /**
  56551. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  56552. * @param localAxis The local direction that is used to compute the world direction.
  56553. * @param mesh The mesh that this bone is attached to.
  56554. * @param result The vector3 that the world direction will be copied to.
  56555. */
  56556. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  56557. var wm;
  56558. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56559. if (mesh) {
  56560. wm = mesh.getWorldMatrix();
  56561. }
  56562. this._skeleton.computeAbsoluteTransforms();
  56563. var mat = Bone._tmpMats[0];
  56564. mat.copyFrom(this.getAbsoluteTransform());
  56565. if (mesh) {
  56566. mat.multiplyToRef(wm, mat);
  56567. }
  56568. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  56569. result.normalize();
  56570. };
  56571. /**
  56572. * Get the euler rotation of the bone in local or world space.
  56573. * @param space The space that the rotation should be in.
  56574. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56575. * @returns The euler rotation
  56576. */
  56577. Bone.prototype.getRotation = function (space, mesh) {
  56578. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56579. var result = BABYLON.Vector3.Zero();
  56580. this.getRotationToRef(space, mesh, result);
  56581. return result;
  56582. };
  56583. /**
  56584. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  56585. * @param space The space that the rotation should be in.
  56586. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56587. * @param result The vector3 that the rotation should be copied to.
  56588. */
  56589. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  56590. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56591. var quat = Bone._tmpQuat;
  56592. this.getRotationQuaternionToRef(space, mesh, quat);
  56593. quat.toEulerAnglesToRef(result);
  56594. };
  56595. /**
  56596. * Get the quaternion rotation of the bone in either local or world space.
  56597. * @param space The space that the rotation should be in.
  56598. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56599. * @returns The quaternion rotation
  56600. */
  56601. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  56602. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56603. var result = BABYLON.Quaternion.Identity();
  56604. this.getRotationQuaternionToRef(space, mesh, result);
  56605. return result;
  56606. };
  56607. /**
  56608. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  56609. * @param space The space that the rotation should be in.
  56610. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56611. * @param result The quaternion that the rotation should be copied to.
  56612. */
  56613. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  56614. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56615. if (space == BABYLON.Space.LOCAL) {
  56616. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56617. }
  56618. else {
  56619. var mat = Bone._tmpMats[0];
  56620. var amat = this.getAbsoluteTransform();
  56621. if (mesh) {
  56622. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56623. }
  56624. else {
  56625. mat.copyFrom(amat);
  56626. }
  56627. mat.m[0] *= this._scalingDeterminant;
  56628. mat.m[1] *= this._scalingDeterminant;
  56629. mat.m[2] *= this._scalingDeterminant;
  56630. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56631. }
  56632. };
  56633. /**
  56634. * Get the rotation matrix of the bone in local or world space.
  56635. * @param space The space that the rotation should be in.
  56636. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56637. * @returns The rotation matrix
  56638. */
  56639. Bone.prototype.getRotationMatrix = function (space, mesh) {
  56640. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56641. var result = BABYLON.Matrix.Identity();
  56642. this.getRotationMatrixToRef(space, mesh, result);
  56643. return result;
  56644. };
  56645. /**
  56646. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  56647. * @param space The space that the rotation should be in.
  56648. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56649. * @param result The quaternion that the rotation should be copied to.
  56650. */
  56651. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  56652. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56653. if (space == BABYLON.Space.LOCAL) {
  56654. this.getLocalMatrix().getRotationMatrixToRef(result);
  56655. }
  56656. else {
  56657. var mat = Bone._tmpMats[0];
  56658. var amat = this.getAbsoluteTransform();
  56659. if (mesh) {
  56660. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56661. }
  56662. else {
  56663. mat.copyFrom(amat);
  56664. }
  56665. mat.m[0] *= this._scalingDeterminant;
  56666. mat.m[1] *= this._scalingDeterminant;
  56667. mat.m[2] *= this._scalingDeterminant;
  56668. mat.getRotationMatrixToRef(result);
  56669. }
  56670. };
  56671. /**
  56672. * Get the world position of a point that is in the local space of the bone.
  56673. * @param position The local position
  56674. * @param mesh The mesh that this bone is attached to.
  56675. * @returns The world position
  56676. */
  56677. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  56678. var result = BABYLON.Vector3.Zero();
  56679. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  56680. return result;
  56681. };
  56682. /**
  56683. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  56684. * @param position The local position
  56685. * @param mesh The mesh that this bone is attached to.
  56686. * @param result The vector3 that the world position should be copied to.
  56687. */
  56688. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  56689. var wm;
  56690. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56691. if (mesh) {
  56692. wm = mesh.getWorldMatrix();
  56693. }
  56694. this._skeleton.computeAbsoluteTransforms();
  56695. var tmat = Bone._tmpMats[0];
  56696. if (mesh) {
  56697. tmat.copyFrom(this.getAbsoluteTransform());
  56698. tmat.multiplyToRef(wm, tmat);
  56699. }
  56700. else {
  56701. tmat = this.getAbsoluteTransform();
  56702. }
  56703. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56704. };
  56705. /**
  56706. * Get the local position of a point that is in world space.
  56707. * @param position The world position
  56708. * @param mesh The mesh that this bone is attached to.
  56709. * @returns The local position
  56710. */
  56711. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  56712. var result = BABYLON.Vector3.Zero();
  56713. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  56714. return result;
  56715. };
  56716. /**
  56717. * Get the local position of a point that is in world space and copy it to the result param.
  56718. * @param position The world position
  56719. * @param mesh The mesh that this bone is attached to.
  56720. * @param result The vector3 that the local position should be copied to.
  56721. */
  56722. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  56723. var wm;
  56724. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56725. if (mesh) {
  56726. wm = mesh.getWorldMatrix();
  56727. }
  56728. this._skeleton.computeAbsoluteTransforms();
  56729. var tmat = Bone._tmpMats[0];
  56730. tmat.copyFrom(this.getAbsoluteTransform());
  56731. if (mesh) {
  56732. tmat.multiplyToRef(wm, tmat);
  56733. }
  56734. tmat.invert();
  56735. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56736. };
  56737. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56738. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  56739. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56740. return Bone;
  56741. }(BABYLON.Node));
  56742. BABYLON.Bone = Bone;
  56743. })(BABYLON || (BABYLON = {}));
  56744. //# sourceMappingURL=babylon.bone.js.map
  56745. var BABYLON;
  56746. (function (BABYLON) {
  56747. var BoneIKController = (function () {
  56748. function BoneIKController(mesh, bone, options) {
  56749. this.targetPosition = BABYLON.Vector3.Zero();
  56750. this.poleTargetPosition = BABYLON.Vector3.Zero();
  56751. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  56752. this.poleAngle = 0;
  56753. this.slerpAmount = 1;
  56754. this._bone1Quat = BABYLON.Quaternion.Identity();
  56755. this._bone1Mat = BABYLON.Matrix.Identity();
  56756. this._bone2Ang = Math.PI;
  56757. this._maxAngle = Math.PI;
  56758. this._rightHandedSystem = false;
  56759. this._bendAxis = BABYLON.Vector3.Right();
  56760. this._slerping = false;
  56761. this._adjustRoll = 0;
  56762. this._bone2 = bone;
  56763. this._bone1 = bone.getParent();
  56764. this.mesh = mesh;
  56765. var bonePos = bone.getPosition();
  56766. if (bone.getAbsoluteTransform().determinant() > 0) {
  56767. this._rightHandedSystem = true;
  56768. this._bendAxis.x = 0;
  56769. this._bendAxis.y = 0;
  56770. this._bendAxis.z = -1;
  56771. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  56772. this._adjustRoll = Math.PI * .5;
  56773. this._bendAxis.z = 1;
  56774. }
  56775. }
  56776. if (this._bone1.length) {
  56777. var boneScale1 = this._bone1.getScale();
  56778. var boneScale2 = this._bone2.getScale();
  56779. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  56780. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  56781. }
  56782. else if (this._bone1.children[0]) {
  56783. mesh.computeWorldMatrix(true);
  56784. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  56785. var pos2 = this._bone2.getAbsolutePosition(mesh);
  56786. var pos3 = this._bone1.getAbsolutePosition(mesh);
  56787. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  56788. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  56789. }
  56790. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  56791. this.maxAngle = Math.PI;
  56792. if (options) {
  56793. if (options.targetMesh) {
  56794. this.targetMesh = options.targetMesh;
  56795. this.targetMesh.computeWorldMatrix(true);
  56796. }
  56797. if (options.poleTargetMesh) {
  56798. this.poleTargetMesh = options.poleTargetMesh;
  56799. this.poleTargetMesh.computeWorldMatrix(true);
  56800. }
  56801. else if (options.poleTargetBone) {
  56802. this.poleTargetBone = options.poleTargetBone;
  56803. }
  56804. else if (this._bone1.getParent()) {
  56805. this.poleTargetBone = this._bone1.getParent();
  56806. }
  56807. if (options.poleTargetLocalOffset) {
  56808. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  56809. }
  56810. if (options.poleAngle) {
  56811. this.poleAngle = options.poleAngle;
  56812. }
  56813. if (options.bendAxis) {
  56814. this._bendAxis.copyFrom(options.bendAxis);
  56815. }
  56816. if (options.maxAngle) {
  56817. this.maxAngle = options.maxAngle;
  56818. }
  56819. if (options.slerpAmount) {
  56820. this.slerpAmount = options.slerpAmount;
  56821. }
  56822. }
  56823. }
  56824. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  56825. get: function () {
  56826. return this._maxAngle;
  56827. },
  56828. set: function (value) {
  56829. this._setMaxAngle(value);
  56830. },
  56831. enumerable: true,
  56832. configurable: true
  56833. });
  56834. BoneIKController.prototype._setMaxAngle = function (ang) {
  56835. if (ang < 0) {
  56836. ang = 0;
  56837. }
  56838. if (ang > Math.PI || ang == undefined) {
  56839. ang = Math.PI;
  56840. }
  56841. this._maxAngle = ang;
  56842. var a = this._bone1Length;
  56843. var b = this._bone2Length;
  56844. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  56845. };
  56846. BoneIKController.prototype.update = function () {
  56847. var bone1 = this._bone1;
  56848. var target = this.targetPosition;
  56849. var poleTarget = this.poleTargetPosition;
  56850. var mat1 = BoneIKController._tmpMats[0];
  56851. var mat2 = BoneIKController._tmpMats[1];
  56852. if (this.targetMesh) {
  56853. target.copyFrom(this.targetMesh.getAbsolutePosition());
  56854. }
  56855. if (this.poleTargetBone) {
  56856. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  56857. }
  56858. else if (this.poleTargetMesh) {
  56859. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  56860. }
  56861. var bonePos = BoneIKController._tmpVecs[0];
  56862. var zaxis = BoneIKController._tmpVecs[1];
  56863. var xaxis = BoneIKController._tmpVecs[2];
  56864. var yaxis = BoneIKController._tmpVecs[3];
  56865. var upAxis = BoneIKController._tmpVecs[4];
  56866. var _tmpQuat = BoneIKController._tmpQuat;
  56867. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  56868. poleTarget.subtractToRef(bonePos, upAxis);
  56869. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  56870. upAxis.y = 1;
  56871. }
  56872. else {
  56873. upAxis.normalize();
  56874. }
  56875. target.subtractToRef(bonePos, yaxis);
  56876. yaxis.normalize();
  56877. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  56878. zaxis.normalize();
  56879. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  56880. xaxis.normalize();
  56881. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  56882. var a = this._bone1Length;
  56883. var b = this._bone2Length;
  56884. var c = BABYLON.Vector3.Distance(bonePos, target);
  56885. if (this._maxReach > 0) {
  56886. c = Math.min(this._maxReach, c);
  56887. }
  56888. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  56889. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  56890. if (acosa > 1) {
  56891. acosa = 1;
  56892. }
  56893. if (acosb > 1) {
  56894. acosb = 1;
  56895. }
  56896. if (acosa < -1) {
  56897. acosa = -1;
  56898. }
  56899. if (acosb < -1) {
  56900. acosb = -1;
  56901. }
  56902. var angA = Math.acos(acosa);
  56903. var angB = Math.acos(acosb);
  56904. var angC = -angA - angB;
  56905. if (this._rightHandedSystem) {
  56906. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  56907. mat2.multiplyToRef(mat1, mat1);
  56908. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  56909. mat2.multiplyToRef(mat1, mat1);
  56910. }
  56911. else {
  56912. var _tmpVec = BoneIKController._tmpVecs[5];
  56913. _tmpVec.copyFrom(this._bendAxis);
  56914. _tmpVec.x *= -1;
  56915. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  56916. mat2.multiplyToRef(mat1, mat1);
  56917. }
  56918. if (this.poleAngle) {
  56919. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  56920. mat1.multiplyToRef(mat2, mat1);
  56921. }
  56922. if (this.slerpAmount < 1) {
  56923. if (!this._slerping) {
  56924. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  56925. }
  56926. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  56927. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  56928. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  56929. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  56930. this._slerping = true;
  56931. }
  56932. else {
  56933. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  56934. this._bone1Mat.copyFrom(mat1);
  56935. this._slerping = false;
  56936. }
  56937. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  56938. this._bone2Ang = angC;
  56939. };
  56940. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56941. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  56942. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56943. return BoneIKController;
  56944. }());
  56945. BABYLON.BoneIKController = BoneIKController;
  56946. })(BABYLON || (BABYLON = {}));
  56947. //# sourceMappingURL=babylon.boneIKController.js.map
  56948. var BABYLON;
  56949. (function (BABYLON) {
  56950. var BoneLookController = (function () {
  56951. /**
  56952. * Create a BoneLookController
  56953. * @param mesh the mesh that the bone belongs to
  56954. * @param bone the bone that will be looking to the target
  56955. * @param target the target Vector3 to look at
  56956. * @param settings optional settings:
  56957. * - maxYaw: the maximum angle the bone will yaw to
  56958. * - minYaw: the minimum angle the bone will yaw to
  56959. * - maxPitch: the maximum angle the bone will pitch to
  56960. * - minPitch: the minimum angle the bone will yaw to
  56961. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  56962. * - upAxis: the up axis of the coordinate system
  56963. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  56964. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  56965. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  56966. * - adjustYaw: used to make an adjustment to the yaw of the bone
  56967. * - adjustPitch: used to make an adjustment to the pitch of the bone
  56968. * - adjustRoll: used to make an adjustment to the roll of the bone
  56969. **/
  56970. function BoneLookController(mesh, bone, target, options) {
  56971. /**
  56972. * The up axis of the coordinate system that is used when the bone is rotated.
  56973. */
  56974. this.upAxis = BABYLON.Vector3.Up();
  56975. /**
  56976. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  56977. */
  56978. this.upAxisSpace = BABYLON.Space.LOCAL;
  56979. /**
  56980. * Used to make an adjustment to the yaw of the bone.
  56981. */
  56982. this.adjustYaw = 0;
  56983. /**
  56984. * Used to make an adjustment to the pitch of the bone.
  56985. */
  56986. this.adjustPitch = 0;
  56987. /**
  56988. * Used to make an adjustment to the roll of the bone.
  56989. */
  56990. this.adjustRoll = 0;
  56991. /**
  56992. * 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).
  56993. */
  56994. this.slerpAmount = 1;
  56995. this._boneQuat = BABYLON.Quaternion.Identity();
  56996. this._slerping = false;
  56997. this._firstFrameSkipped = false;
  56998. this._fowardAxis = BABYLON.Vector3.Forward();
  56999. this.mesh = mesh;
  57000. this.bone = bone;
  57001. this.target = target;
  57002. if (options) {
  57003. if (options.adjustYaw) {
  57004. this.adjustYaw = options.adjustYaw;
  57005. }
  57006. if (options.adjustPitch) {
  57007. this.adjustPitch = options.adjustPitch;
  57008. }
  57009. if (options.adjustRoll) {
  57010. this.adjustRoll = options.adjustRoll;
  57011. }
  57012. if (options.maxYaw != null) {
  57013. this.maxYaw = options.maxYaw;
  57014. }
  57015. else {
  57016. this.maxYaw = Math.PI;
  57017. }
  57018. if (options.minYaw != null) {
  57019. this.minYaw = options.minYaw;
  57020. }
  57021. else {
  57022. this.minYaw = -Math.PI;
  57023. }
  57024. if (options.maxPitch != null) {
  57025. this.maxPitch = options.maxPitch;
  57026. }
  57027. else {
  57028. this.maxPitch = Math.PI;
  57029. }
  57030. if (options.minPitch != null) {
  57031. this.minPitch = options.minPitch;
  57032. }
  57033. else {
  57034. this.minPitch = -Math.PI;
  57035. }
  57036. if (options.slerpAmount != null) {
  57037. this.slerpAmount = options.slerpAmount;
  57038. }
  57039. if (options.upAxis != null) {
  57040. this.upAxis = options.upAxis;
  57041. }
  57042. if (options.upAxisSpace != null) {
  57043. this.upAxisSpace = options.upAxisSpace;
  57044. }
  57045. if (options.yawAxis != null || options.pitchAxis != null) {
  57046. var newYawAxis = BABYLON.Axis.Y;
  57047. var newPitchAxis = BABYLON.Axis.X;
  57048. if (options.yawAxis != null) {
  57049. newYawAxis = options.yawAxis.clone();
  57050. newYawAxis.normalize();
  57051. }
  57052. if (options.pitchAxis != null) {
  57053. newPitchAxis = options.pitchAxis.clone();
  57054. newPitchAxis.normalize();
  57055. }
  57056. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  57057. this._transformYawPitch = BABYLON.Matrix.Identity();
  57058. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  57059. this._transformYawPitchInv = this._transformYawPitch.clone();
  57060. this._transformYawPitch.invert();
  57061. }
  57062. }
  57063. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  57064. this.upAxisSpace = BABYLON.Space.LOCAL;
  57065. }
  57066. }
  57067. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  57068. /**
  57069. * Get/set the minimum yaw angle that the bone can look to.
  57070. */
  57071. get: function () {
  57072. return this._minYaw;
  57073. },
  57074. set: function (value) {
  57075. this._minYaw = value;
  57076. this._minYawSin = Math.sin(value);
  57077. this._minYawCos = Math.cos(value);
  57078. if (this._maxYaw != null) {
  57079. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57080. this._yawRange = this._maxYaw - this._minYaw;
  57081. }
  57082. },
  57083. enumerable: true,
  57084. configurable: true
  57085. });
  57086. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  57087. /**
  57088. * Get/set the maximum yaw angle that the bone can look to.
  57089. */
  57090. get: function () {
  57091. return this._maxYaw;
  57092. },
  57093. set: function (value) {
  57094. this._maxYaw = value;
  57095. this._maxYawSin = Math.sin(value);
  57096. this._maxYawCos = Math.cos(value);
  57097. if (this._minYaw != null) {
  57098. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57099. this._yawRange = this._maxYaw - this._minYaw;
  57100. }
  57101. },
  57102. enumerable: true,
  57103. configurable: true
  57104. });
  57105. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  57106. /**
  57107. * Get/set the minimum pitch angle that the bone can look to.
  57108. */
  57109. get: function () {
  57110. return this._minPitch;
  57111. },
  57112. set: function (value) {
  57113. this._minPitch = value;
  57114. this._minPitchTan = Math.tan(value);
  57115. },
  57116. enumerable: true,
  57117. configurable: true
  57118. });
  57119. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  57120. /**
  57121. * Get/set the maximum pitch angle that the bone can look to.
  57122. */
  57123. get: function () {
  57124. return this._maxPitch;
  57125. },
  57126. set: function (value) {
  57127. this._maxPitch = value;
  57128. this._maxPitchTan = Math.tan(value);
  57129. },
  57130. enumerable: true,
  57131. configurable: true
  57132. });
  57133. /**
  57134. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  57135. */
  57136. BoneLookController.prototype.update = function () {
  57137. //skip the first frame when slerping so that the mesh rotation is correct
  57138. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  57139. this._firstFrameSkipped = true;
  57140. return;
  57141. }
  57142. var bone = this.bone;
  57143. var bonePos = BoneLookController._tmpVecs[0];
  57144. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  57145. var target = this.target;
  57146. var _tmpMat1 = BoneLookController._tmpMats[0];
  57147. var _tmpMat2 = BoneLookController._tmpMats[1];
  57148. var mesh = this.mesh;
  57149. var parentBone = bone.getParent();
  57150. var upAxis = BoneLookController._tmpVecs[1];
  57151. upAxis.copyFrom(this.upAxis);
  57152. if (this.upAxisSpace == BABYLON.Space.BONE) {
  57153. if (this._transformYawPitch) {
  57154. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  57155. }
  57156. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  57157. }
  57158. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  57159. mesh.getDirectionToRef(upAxis, upAxis);
  57160. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  57161. upAxis.normalize();
  57162. }
  57163. }
  57164. var checkYaw = false;
  57165. var checkPitch = false;
  57166. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  57167. checkYaw = true;
  57168. }
  57169. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  57170. checkPitch = true;
  57171. }
  57172. if (checkYaw || checkPitch) {
  57173. var spaceMat = BoneLookController._tmpMats[2];
  57174. var spaceMatInv = BoneLookController._tmpMats[3];
  57175. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  57176. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  57177. }
  57178. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  57179. spaceMat.copyFrom(mesh.getWorldMatrix());
  57180. }
  57181. else {
  57182. var forwardAxis = BoneLookController._tmpVecs[2];
  57183. forwardAxis.copyFrom(this._fowardAxis);
  57184. if (this._transformYawPitch) {
  57185. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  57186. }
  57187. if (parentBone) {
  57188. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  57189. }
  57190. else {
  57191. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  57192. }
  57193. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  57194. rightAxis.normalize();
  57195. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  57196. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  57197. }
  57198. spaceMat.invertToRef(spaceMatInv);
  57199. var xzlen;
  57200. if (checkPitch) {
  57201. var localTarget = BoneLookController._tmpVecs[3];
  57202. target.subtractToRef(bonePos, localTarget);
  57203. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  57204. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57205. var pitch = Math.atan2(localTarget.y, xzlen);
  57206. var newPitch = pitch;
  57207. if (pitch > this._maxPitch) {
  57208. localTarget.y = this._maxPitchTan * xzlen;
  57209. newPitch = this._maxPitch;
  57210. }
  57211. else if (pitch < this._minPitch) {
  57212. localTarget.y = this._minPitchTan * xzlen;
  57213. newPitch = this._minPitch;
  57214. }
  57215. if (pitch != newPitch) {
  57216. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  57217. localTarget.addInPlace(bonePos);
  57218. target = localTarget;
  57219. }
  57220. }
  57221. if (checkYaw) {
  57222. var localTarget = BoneLookController._tmpVecs[4];
  57223. target.subtractToRef(bonePos, localTarget);
  57224. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  57225. var yaw = Math.atan2(localTarget.x, localTarget.z);
  57226. var newYaw = yaw;
  57227. if (yaw > this._maxYaw || yaw < this._minYaw) {
  57228. if (xzlen == null) {
  57229. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57230. }
  57231. if (this._yawRange > Math.PI) {
  57232. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  57233. localTarget.z = this._maxYawCos * xzlen;
  57234. localTarget.x = this._maxYawSin * xzlen;
  57235. newYaw = this._maxYaw;
  57236. }
  57237. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  57238. localTarget.z = this._minYawCos * xzlen;
  57239. localTarget.x = this._minYawSin * xzlen;
  57240. newYaw = this._minYaw;
  57241. }
  57242. }
  57243. else {
  57244. if (yaw > this._maxYaw) {
  57245. localTarget.z = this._maxYawCos * xzlen;
  57246. localTarget.x = this._maxYawSin * xzlen;
  57247. newYaw = this._maxYaw;
  57248. }
  57249. else if (yaw < this._minYaw) {
  57250. localTarget.z = this._minYawCos * xzlen;
  57251. localTarget.x = this._minYawSin * xzlen;
  57252. newYaw = this._minYaw;
  57253. }
  57254. }
  57255. }
  57256. if (this._slerping && this._yawRange > Math.PI) {
  57257. //are we going to be crossing into the min/max region?
  57258. var boneFwd = BoneLookController._tmpVecs[8];
  57259. boneFwd.copyFrom(BABYLON.Axis.Z);
  57260. if (this._transformYawPitch) {
  57261. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  57262. }
  57263. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  57264. this._boneQuat.toRotationMatrix(boneRotMat);
  57265. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  57266. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  57267. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  57268. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  57269. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  57270. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  57271. if (angBtwTar > angBtwMidYaw) {
  57272. if (xzlen == null) {
  57273. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57274. }
  57275. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  57276. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  57277. if (angBtwMin < angBtwMax) {
  57278. newYaw = boneYaw + Math.PI * .75;
  57279. localTarget.z = Math.cos(newYaw) * xzlen;
  57280. localTarget.x = Math.sin(newYaw) * xzlen;
  57281. }
  57282. else {
  57283. newYaw = boneYaw - Math.PI * .75;
  57284. localTarget.z = Math.cos(newYaw) * xzlen;
  57285. localTarget.x = Math.sin(newYaw) * xzlen;
  57286. }
  57287. }
  57288. }
  57289. if (yaw != newYaw) {
  57290. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  57291. localTarget.addInPlace(bonePos);
  57292. target = localTarget;
  57293. }
  57294. }
  57295. }
  57296. var zaxis = BoneLookController._tmpVecs[5];
  57297. var xaxis = BoneLookController._tmpVecs[6];
  57298. var yaxis = BoneLookController._tmpVecs[7];
  57299. var _tmpQuat = BoneLookController._tmpQuat;
  57300. target.subtractToRef(bonePos, zaxis);
  57301. zaxis.normalize();
  57302. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  57303. xaxis.normalize();
  57304. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  57305. yaxis.normalize();
  57306. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  57307. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  57308. return;
  57309. }
  57310. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  57311. return;
  57312. }
  57313. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  57314. return;
  57315. }
  57316. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  57317. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  57318. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  57319. }
  57320. if (this.slerpAmount < 1) {
  57321. if (!this._slerping) {
  57322. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  57323. }
  57324. if (this._transformYawPitch) {
  57325. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  57326. }
  57327. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  57328. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  57329. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  57330. this._slerping = true;
  57331. }
  57332. else {
  57333. if (this._transformYawPitch) {
  57334. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  57335. }
  57336. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  57337. this._slerping = false;
  57338. }
  57339. };
  57340. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  57341. var angDiff = ang2 - ang1;
  57342. angDiff %= Math.PI * 2;
  57343. if (angDiff > Math.PI) {
  57344. angDiff -= Math.PI * 2;
  57345. }
  57346. else if (angDiff < -Math.PI) {
  57347. angDiff += Math.PI * 2;
  57348. }
  57349. return angDiff;
  57350. };
  57351. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  57352. ang1 %= (2 * Math.PI);
  57353. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  57354. ang2 %= (2 * Math.PI);
  57355. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  57356. var ab = 0;
  57357. if (ang1 < ang2) {
  57358. ab = ang2 - ang1;
  57359. }
  57360. else {
  57361. ab = ang1 - ang2;
  57362. }
  57363. if (ab > Math.PI) {
  57364. ab = Math.PI * 2 - ab;
  57365. }
  57366. return ab;
  57367. };
  57368. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  57369. ang %= (2 * Math.PI);
  57370. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  57371. ang1 %= (2 * Math.PI);
  57372. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  57373. ang2 %= (2 * Math.PI);
  57374. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  57375. if (ang1 < ang2) {
  57376. if (ang > ang1 && ang < ang2) {
  57377. return true;
  57378. }
  57379. }
  57380. else {
  57381. if (ang > ang2 && ang < ang1) {
  57382. return true;
  57383. }
  57384. }
  57385. return false;
  57386. };
  57387. 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()];
  57388. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  57389. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57390. return BoneLookController;
  57391. }());
  57392. BABYLON.BoneLookController = BoneLookController;
  57393. })(BABYLON || (BABYLON = {}));
  57394. //# sourceMappingURL=babylon.boneLookController.js.map
  57395. var BABYLON;
  57396. (function (BABYLON) {
  57397. var Skeleton = (function () {
  57398. function Skeleton(name, id, scene) {
  57399. this.name = name;
  57400. this.id = id;
  57401. this.bones = new Array();
  57402. this.needInitialSkinMatrix = false;
  57403. this._isDirty = true;
  57404. this._meshesWithPoseMatrix = new Array();
  57405. this._identity = BABYLON.Matrix.Identity();
  57406. this._ranges = {};
  57407. this._lastAbsoluteTransformsUpdateId = -1;
  57408. // Events
  57409. /**
  57410. * An event triggered before computing the skeleton's matrices
  57411. * @type {BABYLON.Observable}
  57412. */
  57413. this.onBeforeComputeObservable = new BABYLON.Observable();
  57414. this.bones = [];
  57415. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57416. scene.skeletons.push(this);
  57417. //make sure it will recalculate the matrix next time prepare is called.
  57418. this._isDirty = true;
  57419. }
  57420. // Members
  57421. Skeleton.prototype.getTransformMatrices = function (mesh) {
  57422. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  57423. return mesh._bonesTransformMatrices;
  57424. }
  57425. if (!this._transformMatrices) {
  57426. this.prepare();
  57427. }
  57428. return this._transformMatrices;
  57429. };
  57430. Skeleton.prototype.getScene = function () {
  57431. return this._scene;
  57432. };
  57433. // Methods
  57434. /**
  57435. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  57436. */
  57437. Skeleton.prototype.toString = function (fullDetails) {
  57438. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  57439. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  57440. if (fullDetails) {
  57441. ret += ", Ranges: {";
  57442. var first = true;
  57443. for (var name_1 in this._ranges) {
  57444. if (first) {
  57445. ret += ", ";
  57446. first = false;
  57447. }
  57448. ret += name_1;
  57449. }
  57450. ret += "}";
  57451. }
  57452. return ret;
  57453. };
  57454. /**
  57455. * Get bone's index searching by name
  57456. * @param {string} name is bone's name to search for
  57457. * @return {number} Indice of the bone. Returns -1 if not found
  57458. */
  57459. Skeleton.prototype.getBoneIndexByName = function (name) {
  57460. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  57461. if (this.bones[boneIndex].name === name) {
  57462. return boneIndex;
  57463. }
  57464. }
  57465. return -1;
  57466. };
  57467. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  57468. // check name not already in use
  57469. if (!this._ranges[name]) {
  57470. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  57471. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57472. if (this.bones[i].animations[0]) {
  57473. this.bones[i].animations[0].createRange(name, from, to);
  57474. }
  57475. }
  57476. }
  57477. };
  57478. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  57479. if (deleteFrames === void 0) { deleteFrames = true; }
  57480. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57481. if (this.bones[i].animations[0]) {
  57482. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  57483. }
  57484. }
  57485. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  57486. };
  57487. Skeleton.prototype.getAnimationRange = function (name) {
  57488. return this._ranges[name];
  57489. };
  57490. /**
  57491. * Returns as an Array, all AnimationRanges defined on this skeleton
  57492. */
  57493. Skeleton.prototype.getAnimationRanges = function () {
  57494. var animationRanges = [];
  57495. var name;
  57496. var i = 0;
  57497. for (name in this._ranges) {
  57498. animationRanges[i] = this._ranges[name];
  57499. i++;
  57500. }
  57501. return animationRanges;
  57502. };
  57503. /**
  57504. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  57505. */
  57506. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  57507. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  57508. if (this._ranges[name] || !source.getAnimationRange(name)) {
  57509. return false;
  57510. }
  57511. var ret = true;
  57512. var frameOffset = this._getHighestAnimationFrame() + 1;
  57513. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  57514. var boneDict = {};
  57515. var sourceBones = source.bones;
  57516. var nBones;
  57517. var i;
  57518. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  57519. boneDict[sourceBones[i].name] = sourceBones[i];
  57520. }
  57521. if (this.bones.length !== sourceBones.length) {
  57522. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  57523. ret = false;
  57524. }
  57525. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  57526. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  57527. var boneName = this.bones[i].name;
  57528. var sourceBone = boneDict[boneName];
  57529. if (sourceBone) {
  57530. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  57531. }
  57532. else {
  57533. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  57534. ret = false;
  57535. }
  57536. }
  57537. // do not call createAnimationRange(), since it also is done to bones, which was already done
  57538. var range = source.getAnimationRange(name);
  57539. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  57540. return ret;
  57541. };
  57542. Skeleton.prototype.returnToRest = function () {
  57543. for (var index = 0; index < this.bones.length; index++) {
  57544. this.bones[index].returnToRest();
  57545. }
  57546. };
  57547. Skeleton.prototype._getHighestAnimationFrame = function () {
  57548. var ret = 0;
  57549. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57550. if (this.bones[i].animations[0]) {
  57551. var highest = this.bones[i].animations[0].getHighestFrame();
  57552. if (ret < highest) {
  57553. ret = highest;
  57554. }
  57555. }
  57556. }
  57557. return ret;
  57558. };
  57559. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  57560. var range = this.getAnimationRange(name);
  57561. if (!range) {
  57562. return null;
  57563. }
  57564. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  57565. };
  57566. Skeleton.prototype._markAsDirty = function () {
  57567. this._isDirty = true;
  57568. };
  57569. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  57570. this._meshesWithPoseMatrix.push(mesh);
  57571. };
  57572. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  57573. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  57574. if (index > -1) {
  57575. this._meshesWithPoseMatrix.splice(index, 1);
  57576. }
  57577. };
  57578. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  57579. this.onBeforeComputeObservable.notifyObservers(this);
  57580. for (var index = 0; index < this.bones.length; index++) {
  57581. var bone = this.bones[index];
  57582. var parentBone = bone.getParent();
  57583. if (parentBone) {
  57584. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  57585. }
  57586. else {
  57587. if (initialSkinMatrix) {
  57588. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  57589. }
  57590. else {
  57591. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  57592. }
  57593. }
  57594. if (bone._index !== -1) {
  57595. var mappedIndex = bone._index === undefined ? index : bone._index;
  57596. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  57597. }
  57598. }
  57599. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  57600. };
  57601. Skeleton.prototype.prepare = function () {
  57602. if (!this._isDirty) {
  57603. return;
  57604. }
  57605. if (this.needInitialSkinMatrix) {
  57606. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  57607. var mesh = this._meshesWithPoseMatrix[index];
  57608. var poseMatrix = mesh.getPoseMatrix();
  57609. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  57610. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  57611. }
  57612. if (this._synchronizedWithMesh !== mesh) {
  57613. this._synchronizedWithMesh = mesh;
  57614. // Prepare bones
  57615. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  57616. var bone = this.bones[boneIndex];
  57617. if (!bone.getParent()) {
  57618. var matrix = bone.getBaseMatrix();
  57619. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  57620. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  57621. }
  57622. }
  57623. }
  57624. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  57625. }
  57626. }
  57627. else {
  57628. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  57629. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  57630. }
  57631. this._computeTransformMatrices(this._transformMatrices, null);
  57632. }
  57633. this._isDirty = false;
  57634. this._scene._activeBones.addCount(this.bones.length, false);
  57635. };
  57636. Skeleton.prototype.getAnimatables = function () {
  57637. if (!this._animatables || this._animatables.length !== this.bones.length) {
  57638. this._animatables = [];
  57639. for (var index = 0; index < this.bones.length; index++) {
  57640. this._animatables.push(this.bones[index]);
  57641. }
  57642. }
  57643. return this._animatables;
  57644. };
  57645. Skeleton.prototype.clone = function (name, id) {
  57646. var result = new Skeleton(name, id || name, this._scene);
  57647. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57648. for (var index = 0; index < this.bones.length; index++) {
  57649. var source = this.bones[index];
  57650. var parentBone = null;
  57651. if (source.getParent()) {
  57652. var parentIndex = this.bones.indexOf(source.getParent());
  57653. parentBone = result.bones[parentIndex];
  57654. }
  57655. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  57656. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  57657. }
  57658. if (this._ranges) {
  57659. result._ranges = {};
  57660. for (var rangeName in this._ranges) {
  57661. result._ranges[rangeName] = this._ranges[rangeName].clone();
  57662. }
  57663. }
  57664. this._isDirty = true;
  57665. return result;
  57666. };
  57667. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  57668. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  57669. this.bones.forEach(function (bone) {
  57670. bone.animations.forEach(function (animation) {
  57671. animation.enableBlending = true;
  57672. animation.blendingSpeed = blendingSpeed;
  57673. });
  57674. });
  57675. };
  57676. Skeleton.prototype.dispose = function () {
  57677. this._meshesWithPoseMatrix = [];
  57678. // Animations
  57679. this.getScene().stopAnimation(this);
  57680. // Remove from scene
  57681. this.getScene().removeSkeleton(this);
  57682. };
  57683. Skeleton.prototype.serialize = function () {
  57684. var serializationObject = {};
  57685. serializationObject.name = this.name;
  57686. serializationObject.id = this.id;
  57687. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  57688. serializationObject.bones = [];
  57689. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57690. for (var index = 0; index < this.bones.length; index++) {
  57691. var bone = this.bones[index];
  57692. var serializedBone = {
  57693. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  57694. name: bone.name,
  57695. matrix: bone.getBaseMatrix().toArray(),
  57696. rest: bone.getRestPose().toArray()
  57697. };
  57698. serializationObject.bones.push(serializedBone);
  57699. if (bone.length) {
  57700. serializedBone.length = bone.length;
  57701. }
  57702. if (bone.animations && bone.animations.length > 0) {
  57703. serializedBone.animation = bone.animations[0].serialize();
  57704. }
  57705. serializationObject.ranges = [];
  57706. for (var name in this._ranges) {
  57707. var range = {};
  57708. range.name = name;
  57709. range.from = this._ranges[name].from;
  57710. range.to = this._ranges[name].to;
  57711. serializationObject.ranges.push(range);
  57712. }
  57713. }
  57714. return serializationObject;
  57715. };
  57716. Skeleton.Parse = function (parsedSkeleton, scene) {
  57717. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  57718. if (parsedSkeleton.dimensionsAtRest) {
  57719. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  57720. }
  57721. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  57722. var index;
  57723. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  57724. var parsedBone = parsedSkeleton.bones[index];
  57725. var parentBone = null;
  57726. if (parsedBone.parentBoneIndex > -1) {
  57727. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  57728. }
  57729. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  57730. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  57731. if (parsedBone.length) {
  57732. bone.length = parsedBone.length;
  57733. }
  57734. if (parsedBone.animation) {
  57735. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  57736. }
  57737. }
  57738. // placed after bones, so createAnimationRange can cascade down
  57739. if (parsedSkeleton.ranges) {
  57740. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  57741. var data = parsedSkeleton.ranges[index];
  57742. skeleton.createAnimationRange(data.name, data.from, data.to);
  57743. }
  57744. }
  57745. return skeleton;
  57746. };
  57747. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  57748. if (forceUpdate === void 0) { forceUpdate = false; }
  57749. var renderId = this._scene.getRenderId();
  57750. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  57751. this.bones[0].computeAbsoluteTransforms();
  57752. this._lastAbsoluteTransformsUpdateId = renderId;
  57753. }
  57754. };
  57755. Skeleton.prototype.getPoseMatrix = function () {
  57756. var poseMatrix;
  57757. if (this._meshesWithPoseMatrix.length > 0) {
  57758. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  57759. }
  57760. return poseMatrix;
  57761. };
  57762. Skeleton.prototype.sortBones = function () {
  57763. var bones = new Array();
  57764. var visited = new Array(this.bones.length);
  57765. for (var index = 0; index < this.bones.length; index++) {
  57766. this._sortBones(index, bones, visited);
  57767. }
  57768. this.bones = bones;
  57769. };
  57770. Skeleton.prototype._sortBones = function (index, bones, visited) {
  57771. if (visited[index]) {
  57772. return;
  57773. }
  57774. visited[index] = true;
  57775. var bone = this.bones[index];
  57776. if (bone._index === undefined) {
  57777. bone._index = index;
  57778. }
  57779. var parentBone = bone.getParent();
  57780. if (parentBone) {
  57781. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  57782. }
  57783. bones.push(bone);
  57784. };
  57785. return Skeleton;
  57786. }());
  57787. BABYLON.Skeleton = Skeleton;
  57788. })(BABYLON || (BABYLON = {}));
  57789. //# sourceMappingURL=babylon.skeleton.js.map
  57790. var BABYLON;
  57791. (function (BABYLON) {
  57792. var SphericalPolynomial = (function () {
  57793. function SphericalPolynomial() {
  57794. this.x = BABYLON.Vector3.Zero();
  57795. this.y = BABYLON.Vector3.Zero();
  57796. this.z = BABYLON.Vector3.Zero();
  57797. this.xx = BABYLON.Vector3.Zero();
  57798. this.yy = BABYLON.Vector3.Zero();
  57799. this.zz = BABYLON.Vector3.Zero();
  57800. this.xy = BABYLON.Vector3.Zero();
  57801. this.yz = BABYLON.Vector3.Zero();
  57802. this.zx = BABYLON.Vector3.Zero();
  57803. }
  57804. SphericalPolynomial.prototype.addAmbient = function (color) {
  57805. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  57806. this.xx = this.xx.add(colorVector);
  57807. this.yy = this.yy.add(colorVector);
  57808. this.zz = this.zz.add(colorVector);
  57809. };
  57810. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  57811. var result = new SphericalPolynomial();
  57812. result.x = harmonics.L11.scale(1.02333);
  57813. result.y = harmonics.L1_1.scale(1.02333);
  57814. result.z = harmonics.L10.scale(1.02333);
  57815. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  57816. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  57817. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  57818. result.yz = harmonics.L2_1.scale(0.858086);
  57819. result.zx = harmonics.L21.scale(0.858086);
  57820. result.xy = harmonics.L2_2.scale(0.858086);
  57821. result.scale(1.0 / Math.PI);
  57822. return result;
  57823. };
  57824. SphericalPolynomial.prototype.scale = function (scale) {
  57825. this.x = this.x.scale(scale);
  57826. this.y = this.y.scale(scale);
  57827. this.z = this.z.scale(scale);
  57828. this.xx = this.xx.scale(scale);
  57829. this.yy = this.yy.scale(scale);
  57830. this.zz = this.zz.scale(scale);
  57831. this.yz = this.yz.scale(scale);
  57832. this.zx = this.zx.scale(scale);
  57833. this.xy = this.xy.scale(scale);
  57834. };
  57835. return SphericalPolynomial;
  57836. }());
  57837. BABYLON.SphericalPolynomial = SphericalPolynomial;
  57838. var SphericalHarmonics = (function () {
  57839. function SphericalHarmonics() {
  57840. this.L00 = BABYLON.Vector3.Zero();
  57841. this.L1_1 = BABYLON.Vector3.Zero();
  57842. this.L10 = BABYLON.Vector3.Zero();
  57843. this.L11 = BABYLON.Vector3.Zero();
  57844. this.L2_2 = BABYLON.Vector3.Zero();
  57845. this.L2_1 = BABYLON.Vector3.Zero();
  57846. this.L20 = BABYLON.Vector3.Zero();
  57847. this.L21 = BABYLON.Vector3.Zero();
  57848. this.L22 = BABYLON.Vector3.Zero();
  57849. }
  57850. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  57851. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  57852. var c = colorVector.scale(deltaSolidAngle);
  57853. this.L00 = this.L00.add(c.scale(0.282095));
  57854. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  57855. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  57856. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  57857. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  57858. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  57859. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  57860. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  57861. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  57862. };
  57863. SphericalHarmonics.prototype.scale = function (scale) {
  57864. this.L00 = this.L00.scale(scale);
  57865. this.L1_1 = this.L1_1.scale(scale);
  57866. this.L10 = this.L10.scale(scale);
  57867. this.L11 = this.L11.scale(scale);
  57868. this.L2_2 = this.L2_2.scale(scale);
  57869. this.L2_1 = this.L2_1.scale(scale);
  57870. this.L20 = this.L20.scale(scale);
  57871. this.L21 = this.L21.scale(scale);
  57872. this.L22 = this.L22.scale(scale);
  57873. };
  57874. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  57875. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  57876. //
  57877. // E_lm = A_l * L_lm
  57878. //
  57879. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  57880. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  57881. // the scaling factors are given in equation 9.
  57882. // Constant (Band 0)
  57883. this.L00 = this.L00.scale(3.141593);
  57884. // Linear (Band 1)
  57885. this.L1_1 = this.L1_1.scale(2.094395);
  57886. this.L10 = this.L10.scale(2.094395);
  57887. this.L11 = this.L11.scale(2.094395);
  57888. // Quadratic (Band 2)
  57889. this.L2_2 = this.L2_2.scale(0.785398);
  57890. this.L2_1 = this.L2_1.scale(0.785398);
  57891. this.L20 = this.L20.scale(0.785398);
  57892. this.L21 = this.L21.scale(0.785398);
  57893. this.L22 = this.L22.scale(0.785398);
  57894. };
  57895. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  57896. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  57897. // L = (1/pi) * E * rho
  57898. //
  57899. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  57900. this.scale(1.0 / Math.PI);
  57901. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  57902. // (The pixel shader must apply albedo after texture fetches, etc).
  57903. };
  57904. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  57905. var result = new SphericalHarmonics();
  57906. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  57907. result.L1_1 = polynomial.y.scale(0.977204);
  57908. result.L10 = polynomial.z.scale(0.977204);
  57909. result.L11 = polynomial.x.scale(0.977204);
  57910. result.L2_2 = polynomial.xy.scale(1.16538);
  57911. result.L2_1 = polynomial.yz.scale(1.16538);
  57912. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  57913. result.L21 = polynomial.zx.scale(1.16538);
  57914. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  57915. result.scale(Math.PI);
  57916. return result;
  57917. };
  57918. return SphericalHarmonics;
  57919. }());
  57920. BABYLON.SphericalHarmonics = SphericalHarmonics;
  57921. })(BABYLON || (BABYLON = {}));
  57922. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  57923. var BABYLON;
  57924. (function (BABYLON) {
  57925. var Internals;
  57926. (function (Internals) {
  57927. var FileFaceOrientation = (function () {
  57928. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  57929. this.name = name;
  57930. this.worldAxisForNormal = worldAxisForNormal;
  57931. this.worldAxisForFileX = worldAxisForFileX;
  57932. this.worldAxisForFileY = worldAxisForFileY;
  57933. }
  57934. return FileFaceOrientation;
  57935. }());
  57936. ;
  57937. /**
  57938. * Helper class dealing with the extraction of spherical polynomial dataArray
  57939. * from a cube map.
  57940. */
  57941. var CubeMapToSphericalPolynomialTools = (function () {
  57942. function CubeMapToSphericalPolynomialTools() {
  57943. }
  57944. /**
  57945. * Converts a texture to the according Spherical Polynomial data.
  57946. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57947. *
  57948. * @param texture The texture to extract the information from.
  57949. * @return The Spherical Polynomial data.
  57950. */
  57951. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  57952. if (!texture.isCube) {
  57953. // Only supports cube Textures currently.
  57954. return null;
  57955. }
  57956. var size = texture.getSize().width;
  57957. var right = texture.readPixels(0);
  57958. var left = texture.readPixels(1);
  57959. var up;
  57960. var down;
  57961. if (texture.isRenderTarget) {
  57962. up = texture.readPixels(3);
  57963. down = texture.readPixels(2);
  57964. }
  57965. else {
  57966. up = texture.readPixels(2);
  57967. down = texture.readPixels(3);
  57968. }
  57969. var front = texture.readPixels(4);
  57970. var back = texture.readPixels(5);
  57971. var gammaSpace = texture.gammaSpace;
  57972. // Always read as RGBA.
  57973. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  57974. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57975. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57976. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57977. }
  57978. var cubeInfo = {
  57979. size: size,
  57980. right: right,
  57981. left: left,
  57982. up: up,
  57983. down: down,
  57984. front: front,
  57985. back: back,
  57986. format: format,
  57987. type: type,
  57988. gammaSpace: gammaSpace,
  57989. };
  57990. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  57991. };
  57992. /**
  57993. * Converts a cubemap to the according Spherical Polynomial data.
  57994. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57995. *
  57996. * @param cubeInfo The Cube map to extract the information from.
  57997. * @return The Spherical Polynomial data.
  57998. */
  57999. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  58000. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  58001. var totalSolidAngle = 0.0;
  58002. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  58003. var du = 2.0 / cubeInfo.size;
  58004. var dv = du;
  58005. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  58006. var minUV = du * 0.5 - 1.0;
  58007. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58008. var fileFace = this.FileFaces[faceIndex];
  58009. var dataArray = cubeInfo[fileFace.name];
  58010. var v = minUV;
  58011. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  58012. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  58013. // Because SP is still linear, so summation is fine in that basis.
  58014. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  58015. for (var y = 0; y < cubeInfo.size; y++) {
  58016. var u = minUV;
  58017. for (var x = 0; x < cubeInfo.size; x++) {
  58018. // World direction (not normalised)
  58019. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  58020. worldDirection.normalize();
  58021. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  58022. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  58023. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  58024. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  58025. // Handle Integer types.
  58026. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58027. r /= 255;
  58028. g /= 255;
  58029. b /= 255;
  58030. }
  58031. // Handle Gamma space textures.
  58032. if (cubeInfo.gammaSpace) {
  58033. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  58034. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  58035. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  58036. }
  58037. var color = new BABYLON.Color3(r, g, b);
  58038. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58039. totalSolidAngle += deltaSolidAngle;
  58040. u += du;
  58041. }
  58042. v += dv;
  58043. }
  58044. }
  58045. // Solid angle for entire sphere is 4*pi
  58046. var sphereSolidAngle = 4.0 * Math.PI;
  58047. // Adjust the solid angle to allow for how many faces we processed.
  58048. var facesProcessed = 6.0;
  58049. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  58050. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  58051. // This is needed because the numerical integration over the cube uses a
  58052. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  58053. // and also to compensate for accumulative error due to float precision in the summation.
  58054. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  58055. sphericalHarmonics.scale(correctionFactor);
  58056. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  58057. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  58058. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  58059. };
  58060. CubeMapToSphericalPolynomialTools.FileFaces = [
  58061. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  58062. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  58063. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  58064. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  58065. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  58066. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  58067. ];
  58068. return CubeMapToSphericalPolynomialTools;
  58069. }());
  58070. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  58071. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58072. })(BABYLON || (BABYLON = {}));
  58073. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  58074. var BABYLON;
  58075. (function (BABYLON) {
  58076. var Internals;
  58077. (function (Internals) {
  58078. /**
  58079. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  58080. */
  58081. var PanoramaToCubeMapTools = (function () {
  58082. function PanoramaToCubeMapTools() {
  58083. }
  58084. /**
  58085. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  58086. *
  58087. * @param float32Array The source data.
  58088. * @param inputWidth The width of the input panorama.
  58089. * @param inputhHeight The height of the input panorama.
  58090. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  58091. * @return The cubemap data
  58092. */
  58093. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  58094. if (!float32Array) {
  58095. throw "ConvertPanoramaToCubemap: input cannot be null";
  58096. }
  58097. if (float32Array.length != inputWidth * inputHeight * 3) {
  58098. throw "ConvertPanoramaToCubemap: input size is wrong";
  58099. }
  58100. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  58101. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  58102. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  58103. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  58104. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  58105. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  58106. return {
  58107. front: textureFront,
  58108. back: textureBack,
  58109. left: textureLeft,
  58110. right: textureRight,
  58111. up: textureUp,
  58112. down: textureDown,
  58113. size: size,
  58114. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  58115. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  58116. gammaSpace: false,
  58117. };
  58118. };
  58119. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  58120. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  58121. var textureArray = new Float32Array(buffer);
  58122. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  58123. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  58124. var dy = 1 / texSize;
  58125. var fy = 0;
  58126. for (var y = 0; y < texSize; y++) {
  58127. var xv1 = faceData[0];
  58128. var xv2 = faceData[2];
  58129. for (var x = 0; x < texSize; x++) {
  58130. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  58131. v.normalize();
  58132. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  58133. // 3 channels per pixels
  58134. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  58135. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  58136. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  58137. xv1 = xv1.add(rotDX1);
  58138. xv2 = xv2.add(rotDX2);
  58139. }
  58140. fy += dy;
  58141. }
  58142. return textureArray;
  58143. };
  58144. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  58145. var theta = Math.atan2(vDir.z, vDir.x);
  58146. var phi = Math.acos(vDir.y);
  58147. while (theta < -Math.PI)
  58148. theta += 2 * Math.PI;
  58149. while (theta > Math.PI)
  58150. theta -= 2 * Math.PI;
  58151. var dx = theta / Math.PI;
  58152. var dy = phi / Math.PI;
  58153. // recenter.
  58154. dx = dx * 0.5 + 0.5;
  58155. var px = Math.round(dx * inputWidth);
  58156. if (px < 0)
  58157. px = 0;
  58158. else if (px >= inputWidth)
  58159. px = inputWidth - 1;
  58160. var py = Math.round(dy * inputHeight);
  58161. if (py < 0)
  58162. py = 0;
  58163. else if (py >= inputHeight)
  58164. py = inputHeight - 1;
  58165. var inputY = (inputHeight - py - 1);
  58166. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  58167. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  58168. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  58169. return {
  58170. r: r,
  58171. g: g,
  58172. b: b
  58173. };
  58174. };
  58175. PanoramaToCubeMapTools.FACE_FRONT = [
  58176. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58177. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58178. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58179. new BABYLON.Vector3(1.0, 1.0, -1.0)
  58180. ];
  58181. PanoramaToCubeMapTools.FACE_BACK = [
  58182. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58183. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58184. new BABYLON.Vector3(1.0, 1.0, 1.0),
  58185. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  58186. ];
  58187. PanoramaToCubeMapTools.FACE_RIGHT = [
  58188. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58189. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58190. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58191. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58192. ];
  58193. PanoramaToCubeMapTools.FACE_LEFT = [
  58194. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58195. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58196. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58197. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  58198. ];
  58199. PanoramaToCubeMapTools.FACE_DOWN = [
  58200. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58201. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58202. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58203. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58204. ];
  58205. PanoramaToCubeMapTools.FACE_UP = [
  58206. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58207. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58208. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58209. new BABYLON.Vector3(1.0, -1.0, -1.0)
  58210. ];
  58211. return PanoramaToCubeMapTools;
  58212. }());
  58213. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  58214. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58215. })(BABYLON || (BABYLON = {}));
  58216. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  58217. var BABYLON;
  58218. (function (BABYLON) {
  58219. var Internals;
  58220. (function (Internals) {
  58221. ;
  58222. /**
  58223. * This groups tools to convert HDR texture to native colors array.
  58224. */
  58225. var HDRTools = (function () {
  58226. function HDRTools() {
  58227. }
  58228. HDRTools.Ldexp = function (mantissa, exponent) {
  58229. if (exponent > 1023) {
  58230. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  58231. }
  58232. if (exponent < -1074) {
  58233. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  58234. }
  58235. return mantissa * Math.pow(2, exponent);
  58236. };
  58237. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  58238. if (exponent > 0) {
  58239. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  58240. float32array[index + 0] = red * exponent;
  58241. float32array[index + 1] = green * exponent;
  58242. float32array[index + 2] = blue * exponent;
  58243. }
  58244. else {
  58245. float32array[index + 0] = 0;
  58246. float32array[index + 1] = 0;
  58247. float32array[index + 2] = 0;
  58248. }
  58249. };
  58250. HDRTools.readStringLine = function (uint8array, startIndex) {
  58251. var line = "";
  58252. var character = "";
  58253. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  58254. character = String.fromCharCode(uint8array[i]);
  58255. if (character == "\n") {
  58256. break;
  58257. }
  58258. line += character;
  58259. }
  58260. return line;
  58261. };
  58262. /**
  58263. * Reads header information from an RGBE texture stored in a native array.
  58264. * More information on this format are available here:
  58265. * https://en.wikipedia.org/wiki/RGBE_image_format
  58266. *
  58267. * @param uint8array The binary file stored in native array.
  58268. * @return The header information.
  58269. */
  58270. HDRTools.RGBE_ReadHeader = function (uint8array) {
  58271. var height = 0;
  58272. var width = 0;
  58273. var line = this.readStringLine(uint8array, 0);
  58274. if (line[0] != '#' || line[1] != '?') {
  58275. throw "Bad HDR Format.";
  58276. }
  58277. var endOfHeader = false;
  58278. var findFormat = false;
  58279. var lineIndex = 0;
  58280. do {
  58281. lineIndex += (line.length + 1);
  58282. line = this.readStringLine(uint8array, lineIndex);
  58283. if (line == "FORMAT=32-bit_rle_rgbe") {
  58284. findFormat = true;
  58285. }
  58286. else if (line.length == 0) {
  58287. endOfHeader = true;
  58288. }
  58289. } while (!endOfHeader);
  58290. if (!findFormat) {
  58291. throw "HDR Bad header format, unsupported FORMAT";
  58292. }
  58293. lineIndex += (line.length + 1);
  58294. line = this.readStringLine(uint8array, lineIndex);
  58295. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  58296. var match = sizeRegexp.exec(line);
  58297. // TODO. Support +Y and -X if needed.
  58298. if (match.length < 3) {
  58299. throw "HDR Bad header format, no size";
  58300. }
  58301. width = parseInt(match[2]);
  58302. height = parseInt(match[1]);
  58303. if (width < 8 || width > 0x7fff) {
  58304. throw "HDR Bad header format, unsupported size";
  58305. }
  58306. lineIndex += (line.length + 1);
  58307. return {
  58308. height: height,
  58309. width: width,
  58310. dataPosition: lineIndex
  58311. };
  58312. };
  58313. /**
  58314. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  58315. * This RGBE texture needs to store the information as a panorama.
  58316. *
  58317. * More information on this format are available here:
  58318. * https://en.wikipedia.org/wiki/RGBE_image_format
  58319. *
  58320. * @param buffer The binary file stored in an array buffer.
  58321. * @param size The expected size of the extracted cubemap.
  58322. * @return The Cube Map information.
  58323. */
  58324. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  58325. var uint8array = new Uint8Array(buffer);
  58326. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  58327. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58328. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  58329. return cubeMapData;
  58330. };
  58331. /**
  58332. * Returns the pixels data extracted from an RGBE texture.
  58333. * This pixels will be stored left to right up to down in the R G B order in one array.
  58334. *
  58335. * More information on this format are available here:
  58336. * https://en.wikipedia.org/wiki/RGBE_image_format
  58337. *
  58338. * @param uint8array The binary file stored in an array buffer.
  58339. * @param hdrInfo The header information of the file.
  58340. * @return The pixels data in RGB right to left up to down order.
  58341. */
  58342. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  58343. // Keep for multi format supports.
  58344. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58345. };
  58346. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  58347. var num_scanlines = hdrInfo.height;
  58348. var scanline_width = hdrInfo.width;
  58349. var a, b, c, d, count;
  58350. var dataIndex = hdrInfo.dataPosition;
  58351. var index = 0, endIndex = 0, i = 0;
  58352. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  58353. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  58354. // 3 channels of 4 bytes per pixel in float.
  58355. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  58356. var resultArray = new Float32Array(resultBuffer);
  58357. // read in each successive scanline
  58358. while (num_scanlines > 0) {
  58359. a = uint8array[dataIndex++];
  58360. b = uint8array[dataIndex++];
  58361. c = uint8array[dataIndex++];
  58362. d = uint8array[dataIndex++];
  58363. if (a != 2 || b != 2 || (c & 0x80)) {
  58364. // this file is not run length encoded
  58365. throw "HDR Bad header format, not RLE";
  58366. }
  58367. if (((c << 8) | d) != scanline_width) {
  58368. throw "HDR Bad header format, wrong scan line width";
  58369. }
  58370. index = 0;
  58371. // read each of the four channels for the scanline into the buffer
  58372. for (i = 0; i < 4; i++) {
  58373. endIndex = (i + 1) * scanline_width;
  58374. while (index < endIndex) {
  58375. a = uint8array[dataIndex++];
  58376. b = uint8array[dataIndex++];
  58377. if (a > 128) {
  58378. // a run of the same value
  58379. count = a - 128;
  58380. if ((count == 0) || (count > endIndex - index)) {
  58381. throw "HDR Bad Format, bad scanline data (run)";
  58382. }
  58383. while (count-- > 0) {
  58384. scanLineArray[index++] = b;
  58385. }
  58386. }
  58387. else {
  58388. // a non-run
  58389. count = a;
  58390. if ((count == 0) || (count > endIndex - index)) {
  58391. throw "HDR Bad Format, bad scanline data (non-run)";
  58392. }
  58393. scanLineArray[index++] = b;
  58394. if (--count > 0) {
  58395. for (var j = 0; j < count; j++) {
  58396. scanLineArray[index++] = uint8array[dataIndex++];
  58397. }
  58398. }
  58399. }
  58400. }
  58401. }
  58402. // now convert data from buffer into floats
  58403. for (i = 0; i < scanline_width; i++) {
  58404. a = scanLineArray[i];
  58405. b = scanLineArray[i + scanline_width];
  58406. c = scanLineArray[i + 2 * scanline_width];
  58407. d = scanLineArray[i + 3 * scanline_width];
  58408. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  58409. }
  58410. num_scanlines--;
  58411. }
  58412. return resultArray;
  58413. };
  58414. return HDRTools;
  58415. }());
  58416. Internals.HDRTools = HDRTools;
  58417. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58418. })(BABYLON || (BABYLON = {}));
  58419. //# sourceMappingURL=babylon.hdr.js.map
  58420. var BABYLON;
  58421. (function (BABYLON) {
  58422. /**
  58423. * This represents a texture coming from an HDR input.
  58424. *
  58425. * The only supported format is currently panorama picture stored in RGBE format.
  58426. * Example of such files can be found on HDRLib: http://hdrlib.com/
  58427. */
  58428. var HDRCubeTexture = (function (_super) {
  58429. __extends(HDRCubeTexture, _super);
  58430. /**
  58431. * Instantiates an HDRTexture from the following parameters.
  58432. *
  58433. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  58434. * @param scene The scene the texture will be used in
  58435. * @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.
  58436. * @param noMipmap Forces to not generate the mipmap if true
  58437. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  58438. * @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)
  58439. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  58440. */
  58441. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  58442. if (noMipmap === void 0) { noMipmap = false; }
  58443. if (generateHarmonics === void 0) { generateHarmonics = true; }
  58444. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  58445. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  58446. if (onLoad === void 0) { onLoad = null; }
  58447. if (onError === void 0) { onError = null; }
  58448. var _this = _super.call(this, scene) || this;
  58449. _this._useInGammaSpace = false;
  58450. _this._generateHarmonics = true;
  58451. _this._isBABYLONPreprocessed = false;
  58452. _this._onLoad = null;
  58453. _this._onError = null;
  58454. /**
  58455. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  58456. */
  58457. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58458. /**
  58459. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  58460. * This is usefull at run time to apply the good shader.
  58461. */
  58462. _this.isPMREM = false;
  58463. _this._isBlocking = true;
  58464. if (!url) {
  58465. return _this;
  58466. }
  58467. _this.name = url;
  58468. _this.url = url;
  58469. _this.hasAlpha = false;
  58470. _this.isCube = true;
  58471. _this._textureMatrix = BABYLON.Matrix.Identity();
  58472. _this._onLoad = onLoad;
  58473. _this._onError = onError;
  58474. _this.gammaSpace = false;
  58475. if (size) {
  58476. _this._isBABYLONPreprocessed = false;
  58477. _this._noMipmap = noMipmap;
  58478. _this._size = size;
  58479. _this._useInGammaSpace = useInGammaSpace;
  58480. _this._usePMREMGenerator = usePMREMGenerator &&
  58481. scene.getEngine().getCaps().textureLOD &&
  58482. _this.getScene().getEngine().getCaps().textureFloat &&
  58483. !_this._useInGammaSpace;
  58484. }
  58485. else {
  58486. _this._isBABYLONPreprocessed = true;
  58487. _this._noMipmap = false;
  58488. _this._useInGammaSpace = false;
  58489. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  58490. _this.getScene().getEngine().getCaps().textureFloat &&
  58491. !_this._useInGammaSpace;
  58492. }
  58493. _this.isPMREM = _this._usePMREMGenerator;
  58494. _this._texture = _this._getFromCache(url, _this._noMipmap);
  58495. if (!_this._texture) {
  58496. if (!scene.useDelayedTextureLoading) {
  58497. _this.loadTexture();
  58498. }
  58499. else {
  58500. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58501. }
  58502. }
  58503. return _this;
  58504. }
  58505. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  58506. /**
  58507. * Gets wether or not the texture is blocking during loading.
  58508. */
  58509. get: function () {
  58510. return this._isBlocking;
  58511. },
  58512. /**
  58513. * Sets wether or not the texture is blocking during loading.
  58514. */
  58515. set: function (value) {
  58516. this._isBlocking = value;
  58517. },
  58518. enumerable: true,
  58519. configurable: true
  58520. });
  58521. /**
  58522. * Occurs when the file is a preprocessed .babylon.hdr file.
  58523. */
  58524. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  58525. var _this = this;
  58526. var mipLevels = 0;
  58527. var floatArrayView = null;
  58528. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  58529. var mips = [];
  58530. var startIndex = 30;
  58531. for (var level = 0; level < mipLevels; level++) {
  58532. mips.push([]);
  58533. // Fill each pixel of the mip level.
  58534. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  58535. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58536. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  58537. mips[level].push(faceData);
  58538. startIndex += faceSize;
  58539. }
  58540. }
  58541. return mips;
  58542. } : null;
  58543. var callback = function (buffer) {
  58544. // Create Native Array Views
  58545. var intArrayView = new Int32Array(buffer);
  58546. floatArrayView = new Float32Array(buffer);
  58547. // Fill header.
  58548. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  58549. _this._size = intArrayView[1]; // CubeMap max mip face size.
  58550. // Update Texture Information.
  58551. _this._texture.updateSize(_this._size, _this._size);
  58552. // Fill polynomial information.
  58553. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  58554. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  58555. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  58556. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  58557. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  58558. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  58559. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  58560. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  58561. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  58562. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  58563. _this.sphericalPolynomial = sphericalPolynomial;
  58564. // Fill pixel data.
  58565. mipLevels = intArrayView[29]; // Number of mip levels.
  58566. var startIndex = 30;
  58567. var data = [];
  58568. var faceSize = Math.pow(_this._size, 2) * 3;
  58569. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58570. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  58571. startIndex += faceSize;
  58572. }
  58573. var results = [];
  58574. var byteArray = null;
  58575. // Push each faces.
  58576. for (var k = 0; k < 6; k++) {
  58577. var dataFace = null;
  58578. // To be deprecated.
  58579. if (version === 1) {
  58580. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  58581. dataFace = data[j];
  58582. }
  58583. // If special cases.
  58584. if (!mipmapGenerator) {
  58585. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58586. // 3 channels of 1 bytes per pixel in bytes.
  58587. var byteBuffer = new ArrayBuffer(faceSize);
  58588. byteArray = new Uint8Array(byteBuffer);
  58589. }
  58590. for (var i = 0; i < _this._size * _this._size; i++) {
  58591. // Put in gamma space if requested.
  58592. if (_this._useInGammaSpace) {
  58593. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58594. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58595. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58596. }
  58597. // Convert to int texture for fallback.
  58598. if (byteArray) {
  58599. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58600. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58601. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58602. // May use luminance instead if the result is not accurate.
  58603. var max = Math.max(Math.max(r, g), b);
  58604. if (max > 255) {
  58605. var scale = 255 / max;
  58606. r *= scale;
  58607. g *= scale;
  58608. b *= scale;
  58609. }
  58610. byteArray[(i * 3) + 0] = r;
  58611. byteArray[(i * 3) + 1] = g;
  58612. byteArray[(i * 3) + 2] = b;
  58613. }
  58614. }
  58615. }
  58616. // Fill the array accordingly.
  58617. if (byteArray) {
  58618. results.push(byteArray);
  58619. }
  58620. else {
  58621. results.push(dataFace);
  58622. }
  58623. }
  58624. return results;
  58625. };
  58626. 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);
  58627. };
  58628. /**
  58629. * Occurs when the file is raw .hdr file.
  58630. */
  58631. HDRCubeTexture.prototype.loadHDRTexture = function () {
  58632. var _this = this;
  58633. var callback = function (buffer) {
  58634. // Extract the raw linear data.
  58635. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  58636. // Generate harmonics if needed.
  58637. if (_this._generateHarmonics) {
  58638. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  58639. _this.sphericalPolynomial = sphericalPolynomial;
  58640. }
  58641. var results = [];
  58642. var byteArray = null;
  58643. // Push each faces.
  58644. for (var j = 0; j < 6; j++) {
  58645. // Create uintarray fallback.
  58646. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58647. // 3 channels of 1 bytes per pixel in bytes.
  58648. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  58649. byteArray = new Uint8Array(byteBuffer);
  58650. }
  58651. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  58652. // If special cases.
  58653. if (_this._useInGammaSpace || byteArray) {
  58654. for (var i = 0; i < _this._size * _this._size; i++) {
  58655. // Put in gamma space if requested.
  58656. if (_this._useInGammaSpace) {
  58657. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58658. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58659. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58660. }
  58661. // Convert to int texture for fallback.
  58662. if (byteArray) {
  58663. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58664. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58665. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58666. // May use luminance instead if the result is not accurate.
  58667. var max = Math.max(Math.max(r, g), b);
  58668. if (max > 255) {
  58669. var scale = 255 / max;
  58670. r *= scale;
  58671. g *= scale;
  58672. b *= scale;
  58673. }
  58674. byteArray[(i * 3) + 0] = r;
  58675. byteArray[(i * 3) + 1] = g;
  58676. byteArray[(i * 3) + 2] = b;
  58677. }
  58678. }
  58679. }
  58680. if (byteArray) {
  58681. results.push(byteArray);
  58682. }
  58683. else {
  58684. results.push(dataFace);
  58685. }
  58686. }
  58687. return results;
  58688. };
  58689. var mipmapGenerator = null;
  58690. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  58691. // if (!this._noMipmap &&
  58692. // this._usePMREMGenerator) {
  58693. // mipmapGenerator = (data: ArrayBufferView[]) => {
  58694. // // Custom setup of the generator matching with the PBR shader values.
  58695. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  58696. // this._size,
  58697. // this._size,
  58698. // 0,
  58699. // 3,
  58700. // this.getScene().getEngine().getCaps().textureFloat,
  58701. // 2048,
  58702. // 0.25,
  58703. // false,
  58704. // true);
  58705. // return generator.filterCubeMap();
  58706. // };
  58707. // }
  58708. 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);
  58709. };
  58710. /**
  58711. * Starts the loading process of the texture.
  58712. */
  58713. HDRCubeTexture.prototype.loadTexture = function () {
  58714. if (this._isBABYLONPreprocessed) {
  58715. this.loadBabylonTexture();
  58716. }
  58717. else {
  58718. this.loadHDRTexture();
  58719. }
  58720. };
  58721. HDRCubeTexture.prototype.clone = function () {
  58722. var size = this._isBABYLONPreprocessed ? null : this._size;
  58723. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  58724. // Base texture
  58725. newTexture.level = this.level;
  58726. newTexture.wrapU = this.wrapU;
  58727. newTexture.wrapV = this.wrapV;
  58728. newTexture.coordinatesIndex = this.coordinatesIndex;
  58729. newTexture.coordinatesMode = this.coordinatesMode;
  58730. return newTexture;
  58731. };
  58732. // Methods
  58733. HDRCubeTexture.prototype.delayLoad = function () {
  58734. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58735. return;
  58736. }
  58737. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58738. this._texture = this._getFromCache(this.url, this._noMipmap);
  58739. if (!this._texture) {
  58740. this.loadTexture();
  58741. }
  58742. };
  58743. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  58744. return this._textureMatrix;
  58745. };
  58746. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58747. this._textureMatrix = value;
  58748. };
  58749. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58750. var texture = null;
  58751. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58752. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  58753. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  58754. texture.name = parsedTexture.name;
  58755. texture.hasAlpha = parsedTexture.hasAlpha;
  58756. texture.level = parsedTexture.level;
  58757. texture.coordinatesMode = parsedTexture.coordinatesMode;
  58758. texture.isBlocking = parsedTexture.isBlocking;
  58759. }
  58760. return texture;
  58761. };
  58762. HDRCubeTexture.prototype.serialize = function () {
  58763. if (!this.name) {
  58764. return null;
  58765. }
  58766. var serializationObject = {};
  58767. serializationObject.name = this.name;
  58768. serializationObject.hasAlpha = this.hasAlpha;
  58769. serializationObject.isCube = true;
  58770. serializationObject.level = this.level;
  58771. serializationObject.size = this._size;
  58772. serializationObject.coordinatesMode = this.coordinatesMode;
  58773. serializationObject.useInGammaSpace = this._useInGammaSpace;
  58774. serializationObject.generateHarmonics = this._generateHarmonics;
  58775. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  58776. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  58777. serializationObject.customType = "BABYLON.HDRCubeTexture";
  58778. serializationObject.noMipmap = this._noMipmap;
  58779. serializationObject.isBlocking = this._isBlocking;
  58780. return serializationObject;
  58781. };
  58782. /**
  58783. * Saves as a file the data contained in the texture in a binary format.
  58784. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58785. * as the spherical used in the lighting.
  58786. * @param url The HDR file url.
  58787. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58788. * @param onError Method called if any error happens during download.
  58789. * @return The packed binary data.
  58790. */
  58791. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  58792. if (onError === void 0) { onError = null; }
  58793. var callback = function (buffer) {
  58794. var data = new Blob([buffer], { type: 'application/octet-stream' });
  58795. // Returns a URL you can use as a href.
  58796. var objUrl = window.URL.createObjectURL(data);
  58797. // Simulates a link to it and click to dowload.
  58798. var a = document.createElement("a");
  58799. document.body.appendChild(a);
  58800. a.style.display = "none";
  58801. a.href = objUrl;
  58802. a.download = "envmap.babylon.hdr";
  58803. a.click();
  58804. };
  58805. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  58806. };
  58807. /**
  58808. * Serializes the data contained in the texture in a binary format.
  58809. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58810. * as the spherical used in the lighting.
  58811. * @param url The HDR file url.
  58812. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58813. * @param onError Method called if any error happens during download.
  58814. * @return The packed binary data.
  58815. */
  58816. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  58817. if (onError === void 0) { onError = null; }
  58818. // Needs the url tho create the texture.
  58819. if (!url) {
  58820. return null;
  58821. }
  58822. // Check Power of two size.
  58823. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  58824. return null;
  58825. }
  58826. // Coming Back in 3.1.
  58827. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  58828. return null;
  58829. };
  58830. HDRCubeTexture._facesMapping = [
  58831. "right",
  58832. "left",
  58833. "up",
  58834. "down",
  58835. "front",
  58836. "back"
  58837. ];
  58838. return HDRCubeTexture;
  58839. }(BABYLON.BaseTexture));
  58840. BABYLON.HDRCubeTexture = HDRCubeTexture;
  58841. })(BABYLON || (BABYLON = {}));
  58842. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  58843. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  58844. // Huge respect for a such great lib.
  58845. // Earcut license:
  58846. // Copyright (c) 2016, Mapbox
  58847. //
  58848. // Permission to use, copy, modify, and/or distribute this software for any purpose
  58849. // with or without fee is hereby granted, provided that the above copyright notice
  58850. // and this permission notice appear in all copies.
  58851. //
  58852. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  58853. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  58854. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  58855. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  58856. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  58857. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  58858. // THIS SOFTWARE.
  58859. var Earcut;
  58860. (function (Earcut) {
  58861. /**
  58862. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  58863. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  58864. * @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).
  58865. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  58866. */
  58867. function earcut(data, holeIndices, dim) {
  58868. dim = dim || 2;
  58869. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  58870. if (!outerNode)
  58871. return triangles;
  58872. var minX, minY, maxX, maxY, x, y, size;
  58873. if (hasHoles)
  58874. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  58875. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  58876. if (data.length > 80 * dim) {
  58877. minX = maxX = data[0];
  58878. minY = maxY = data[1];
  58879. for (var i = dim; i < outerLen; i += dim) {
  58880. x = data[i];
  58881. y = data[i + 1];
  58882. if (x < minX)
  58883. minX = x;
  58884. if (y < minY)
  58885. minY = y;
  58886. if (x > maxX)
  58887. maxX = x;
  58888. if (y > maxY)
  58889. maxY = y;
  58890. }
  58891. // minX, minY and size are later used to transform coords into integers for z-order calculation
  58892. size = Math.max(maxX - minX, maxY - minY);
  58893. }
  58894. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  58895. return triangles;
  58896. }
  58897. Earcut.earcut = earcut;
  58898. // create a circular doubly linked list from polygon points in the specified winding order
  58899. function linkedList(data, start, end, dim, clockwise) {
  58900. var i, last;
  58901. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  58902. for (i = start; i < end; i += dim)
  58903. last = insertNode(i, data[i], data[i + 1], last);
  58904. }
  58905. else {
  58906. for (i = end - dim; i >= start; i -= dim)
  58907. last = insertNode(i, data[i], data[i + 1], last);
  58908. }
  58909. if (last && equals(last, last.next)) {
  58910. removeNode(last);
  58911. last = last.next;
  58912. }
  58913. return last;
  58914. }
  58915. // eliminate colinear or duplicate points
  58916. function filterPoints(start, end) {
  58917. if (!start)
  58918. return start;
  58919. if (!end)
  58920. end = start;
  58921. var p = start, again;
  58922. do {
  58923. again = false;
  58924. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  58925. removeNode(p);
  58926. p = end = p.prev;
  58927. if (p === p.next)
  58928. return null;
  58929. again = true;
  58930. }
  58931. else {
  58932. p = p.next;
  58933. }
  58934. } while (again || p !== end);
  58935. return end;
  58936. }
  58937. // main ear slicing loop which triangulates a polygon (given as a linked list)
  58938. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  58939. if (!ear)
  58940. return;
  58941. // interlink polygon nodes in z-order
  58942. if (!pass && size)
  58943. indexCurve(ear, minX, minY, size);
  58944. var stop = ear, prev, next;
  58945. // iterate through ears, slicing them one by one
  58946. while (ear.prev !== ear.next) {
  58947. prev = ear.prev;
  58948. next = ear.next;
  58949. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  58950. // cut off the triangle
  58951. triangles.push(prev.i / dim);
  58952. triangles.push(ear.i / dim);
  58953. triangles.push(next.i / dim);
  58954. removeNode(ear);
  58955. // skipping the next vertice leads to less sliver triangles
  58956. ear = next.next;
  58957. stop = next.next;
  58958. continue;
  58959. }
  58960. ear = next;
  58961. // if we looped through the whole remaining polygon and can't find any more ears
  58962. if (ear === stop) {
  58963. // try filtering points and slicing again
  58964. if (!pass) {
  58965. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  58966. // if this didn't work, try curing all small self-intersections locally
  58967. }
  58968. else if (pass === 1) {
  58969. ear = cureLocalIntersections(ear, triangles, dim);
  58970. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  58971. // as a last resort, try splitting the remaining polygon into two
  58972. }
  58973. else if (pass === 2) {
  58974. splitEarcut(ear, triangles, dim, minX, minY, size);
  58975. }
  58976. break;
  58977. }
  58978. }
  58979. }
  58980. // check whether a polygon node forms a valid ear with adjacent nodes
  58981. function isEar(ear) {
  58982. var a = ear.prev, b = ear, c = ear.next;
  58983. if (area(a, b, c) >= 0)
  58984. return false; // reflex, can't be an ear
  58985. // now make sure we don't have other points inside the potential ear
  58986. var p = ear.next.next;
  58987. while (p !== ear.prev) {
  58988. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58989. area(p.prev, p, p.next) >= 0)
  58990. return false;
  58991. p = p.next;
  58992. }
  58993. return true;
  58994. }
  58995. function isEarHashed(ear, minX, minY, size) {
  58996. var a = ear.prev, b = ear, c = ear.next;
  58997. if (area(a, b, c) >= 0)
  58998. return false; // reflex, can't be an ear
  58999. // triangle bbox; min & max are calculated like this for speed
  59000. 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);
  59001. // z-order range for the current triangle bbox;
  59002. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  59003. // first look for points inside the triangle in increasing z-order
  59004. var p = ear.nextZ;
  59005. while (p && p.z <= maxZ) {
  59006. if (p !== ear.prev &&
  59007. p !== ear.next &&
  59008. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59009. area(p.prev, p, p.next) >= 0)
  59010. return false;
  59011. p = p.nextZ;
  59012. }
  59013. // then look for points in decreasing z-order
  59014. p = ear.prevZ;
  59015. while (p && p.z >= minZ) {
  59016. if (p !== ear.prev &&
  59017. p !== ear.next &&
  59018. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59019. area(p.prev, p, p.next) >= 0)
  59020. return false;
  59021. p = p.prevZ;
  59022. }
  59023. return true;
  59024. }
  59025. // go through all polygon nodes and cure small local self-intersections
  59026. function cureLocalIntersections(start, triangles, dim) {
  59027. var p = start;
  59028. do {
  59029. var a = p.prev, b = p.next.next;
  59030. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  59031. triangles.push(a.i / dim);
  59032. triangles.push(p.i / dim);
  59033. triangles.push(b.i / dim);
  59034. // remove two nodes involved
  59035. removeNode(p);
  59036. removeNode(p.next);
  59037. p = start = b;
  59038. }
  59039. p = p.next;
  59040. } while (p !== start);
  59041. return p;
  59042. }
  59043. // try splitting polygon into two and triangulate them independently
  59044. function splitEarcut(start, triangles, dim, minX, minY, size) {
  59045. // look for a valid diagonal that divides the polygon into two
  59046. var a = start;
  59047. do {
  59048. var b = a.next.next;
  59049. while (b !== a.prev) {
  59050. if (a.i !== b.i && isValidDiagonal(a, b)) {
  59051. // split the polygon in two by the diagonal
  59052. var c = splitPolygon(a, b);
  59053. // filter colinear points around the cuts
  59054. a = filterPoints(a, a.next);
  59055. c = filterPoints(c, c.next);
  59056. // run earcut on each half
  59057. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  59058. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  59059. return;
  59060. }
  59061. b = b.next;
  59062. }
  59063. a = a.next;
  59064. } while (a !== start);
  59065. }
  59066. // link every hole into the outer loop, producing a single-ring polygon without holes
  59067. function eliminateHoles(data, holeIndices, outerNode, dim) {
  59068. var queue = [], i, len, start, end, list;
  59069. for (i = 0, len = holeIndices.length; i < len; i++) {
  59070. start = holeIndices[i] * dim;
  59071. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  59072. list = linkedList(data, start, end, dim, false);
  59073. if (list === list.next)
  59074. list.steiner = true;
  59075. queue.push(getLeftmost(list));
  59076. }
  59077. queue.sort(compareX);
  59078. // process holes from left to right
  59079. for (i = 0; i < queue.length; i++) {
  59080. eliminateHole(queue[i], outerNode);
  59081. outerNode = filterPoints(outerNode, outerNode.next);
  59082. }
  59083. return outerNode;
  59084. }
  59085. function compareX(a, b) {
  59086. return a.x - b.x;
  59087. }
  59088. // find a bridge between vertices that connects hole with an outer ring and and link it
  59089. function eliminateHole(hole, outerNode) {
  59090. outerNode = findHoleBridge(hole, outerNode);
  59091. if (outerNode) {
  59092. var b = splitPolygon(outerNode, hole);
  59093. filterPoints(b, b.next);
  59094. }
  59095. }
  59096. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  59097. function findHoleBridge(hole, outerNode) {
  59098. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  59099. // find a segment intersected by a ray from the hole's leftmost point to the left;
  59100. // segment's endpoint with lesser x will be potential connection point
  59101. do {
  59102. if (hy <= p.y && hy >= p.next.y) {
  59103. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  59104. if (x <= hx && x > qx) {
  59105. qx = x;
  59106. if (x === hx) {
  59107. if (hy === p.y)
  59108. return p;
  59109. if (hy === p.next.y)
  59110. return p.next;
  59111. }
  59112. m = p.x < p.next.x ? p : p.next;
  59113. }
  59114. }
  59115. p = p.next;
  59116. } while (p !== outerNode);
  59117. if (!m)
  59118. return null;
  59119. if (hx === qx)
  59120. return m.prev; // hole touches outer segment; pick lower endpoint
  59121. // look for points inside the triangle of hole point, segment intersection and endpoint;
  59122. // if there are no points found, we have a valid connection;
  59123. // otherwise choose the point of the minimum angle with the ray as connection point
  59124. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  59125. p = m.next;
  59126. while (p !== stop) {
  59127. if (hx >= p.x &&
  59128. p.x >= mx &&
  59129. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  59130. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  59131. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  59132. m = p;
  59133. tanMin = tan;
  59134. }
  59135. }
  59136. p = p.next;
  59137. }
  59138. return m;
  59139. }
  59140. // interlink polygon nodes in z-order
  59141. function indexCurve(start, minX, minY, size) {
  59142. var p = start;
  59143. do {
  59144. if (p.z === null)
  59145. p.z = zOrder(p.x, p.y, minX, minY, size);
  59146. p.prevZ = p.prev;
  59147. p.nextZ = p.next;
  59148. p = p.next;
  59149. } while (p !== start);
  59150. p.prevZ.nextZ = null;
  59151. p.prevZ = null;
  59152. sortLinked(p);
  59153. }
  59154. // Simon Tatham's linked list merge sort algorithm
  59155. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  59156. function sortLinked(list) {
  59157. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  59158. do {
  59159. p = list;
  59160. list = null;
  59161. tail = null;
  59162. numMerges = 0;
  59163. while (p) {
  59164. numMerges++;
  59165. q = p;
  59166. pSize = 0;
  59167. for (i = 0; i < inSize; i++) {
  59168. pSize++;
  59169. q = q.nextZ;
  59170. if (!q)
  59171. break;
  59172. }
  59173. qSize = inSize;
  59174. while (pSize > 0 || (qSize > 0 && q)) {
  59175. if (pSize === 0) {
  59176. e = q;
  59177. q = q.nextZ;
  59178. qSize--;
  59179. }
  59180. else if (qSize === 0 || !q) {
  59181. e = p;
  59182. p = p.nextZ;
  59183. pSize--;
  59184. }
  59185. else if (p.z <= q.z) {
  59186. e = p;
  59187. p = p.nextZ;
  59188. pSize--;
  59189. }
  59190. else {
  59191. e = q;
  59192. q = q.nextZ;
  59193. qSize--;
  59194. }
  59195. if (tail)
  59196. tail.nextZ = e;
  59197. else
  59198. list = e;
  59199. e.prevZ = tail;
  59200. tail = e;
  59201. }
  59202. p = q;
  59203. }
  59204. tail.nextZ = null;
  59205. inSize *= 2;
  59206. } while (numMerges > 1);
  59207. return list;
  59208. }
  59209. // z-order of a point given coords and size of the data bounding box
  59210. function zOrder(x, y, minX, minY, size) {
  59211. // coords are transformed into non-negative 15-bit integer range
  59212. x = 32767 * (x - minX) / size;
  59213. y = 32767 * (y - minY) / size;
  59214. x = (x | (x << 8)) & 0x00FF00FF;
  59215. x = (x | (x << 4)) & 0x0F0F0F0F;
  59216. x = (x | (x << 2)) & 0x33333333;
  59217. x = (x | (x << 1)) & 0x55555555;
  59218. y = (y | (y << 8)) & 0x00FF00FF;
  59219. y = (y | (y << 4)) & 0x0F0F0F0F;
  59220. y = (y | (y << 2)) & 0x33333333;
  59221. y = (y | (y << 1)) & 0x55555555;
  59222. return x | (y << 1);
  59223. }
  59224. // find the leftmost node of a polygon ring
  59225. function getLeftmost(start) {
  59226. var p = start, leftmost = start;
  59227. do {
  59228. if (p.x < leftmost.x)
  59229. leftmost = p;
  59230. p = p.next;
  59231. } while (p !== start);
  59232. return leftmost;
  59233. }
  59234. // check if a point lies within a convex triangle
  59235. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  59236. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  59237. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  59238. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  59239. }
  59240. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  59241. function isValidDiagonal(a, b) {
  59242. return a.next.i !== b.i &&
  59243. a.prev.i !== b.i &&
  59244. !intersectsPolygon(a, b) &&
  59245. locallyInside(a, b) &&
  59246. locallyInside(b, a) &&
  59247. middleInside(a, b);
  59248. }
  59249. // signed area of a triangle
  59250. function area(p, q, r) {
  59251. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  59252. }
  59253. // check if two points are equal
  59254. function equals(p1, p2) {
  59255. return p1.x === p2.x && p1.y === p2.y;
  59256. }
  59257. // check if two segments intersect
  59258. function intersects(p1, q1, p2, q2) {
  59259. if ((equals(p1, q1) && equals(p2, q2)) ||
  59260. (equals(p1, q2) && equals(p2, q1)))
  59261. return true;
  59262. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  59263. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  59264. }
  59265. // check if a polygon diagonal intersects any polygon segments
  59266. function intersectsPolygon(a, b) {
  59267. var p = a;
  59268. do {
  59269. if (p.i !== a.i &&
  59270. p.next.i !== a.i &&
  59271. p.i !== b.i &&
  59272. p.next.i !== b.i &&
  59273. intersects(p, p.next, a, b))
  59274. return true;
  59275. p = p.next;
  59276. } while (p !== a);
  59277. return false;
  59278. }
  59279. // check if a polygon diagonal is locally inside the polygon
  59280. function locallyInside(a, b) {
  59281. return area(a.prev, a, a.next) < 0
  59282. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  59283. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  59284. }
  59285. // check if the middle point of a polygon diagonal is inside the polygon
  59286. function middleInside(a, b) {
  59287. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  59288. do {
  59289. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  59290. inside = !inside;
  59291. p = p.next;
  59292. } while (p !== a);
  59293. return inside;
  59294. }
  59295. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  59296. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  59297. function splitPolygon(a, b) {
  59298. 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;
  59299. a.next = b;
  59300. b.prev = a;
  59301. a2.next = an;
  59302. an.prev = a2;
  59303. b2.next = a2;
  59304. a2.prev = b2;
  59305. bp.next = b2;
  59306. b2.prev = bp;
  59307. return b2;
  59308. }
  59309. // create a node and optionally link it with previous one (in a circular doubly linked list)
  59310. function insertNode(i, x, y, last) {
  59311. var p = new Node(i, x, y);
  59312. if (!last) {
  59313. p.prev = p;
  59314. p.next = p;
  59315. }
  59316. else {
  59317. p.next = last.next;
  59318. p.prev = last;
  59319. last.next.prev = p;
  59320. last.next = p;
  59321. }
  59322. return p;
  59323. }
  59324. function removeNode(p) {
  59325. p.next.prev = p.prev;
  59326. p.prev.next = p.next;
  59327. if (p.prevZ)
  59328. p.prevZ.nextZ = p.nextZ;
  59329. if (p.nextZ)
  59330. p.nextZ.prevZ = p.prevZ;
  59331. }
  59332. function Node(i, x, y) {
  59333. // vertice index in coordinates array
  59334. this.i = i;
  59335. // vertex coordinates
  59336. this.x = x;
  59337. this.y = y;
  59338. // previous and next vertice nodes in a polygon ring
  59339. this.prev = null;
  59340. this.next = null;
  59341. // z-order curve value
  59342. this.z = null;
  59343. // previous and next nodes in z-order
  59344. this.prevZ = null;
  59345. this.nextZ = null;
  59346. // indicates whether this is a steiner point
  59347. this.steiner = false;
  59348. }
  59349. /**
  59350. * return a percentage difference between the polygon area and its triangulation area;
  59351. * used to verify correctness of triangulation
  59352. */
  59353. function deviation(data, holeIndices, dim, triangles) {
  59354. var hasHoles = holeIndices && holeIndices.length;
  59355. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  59356. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  59357. if (hasHoles) {
  59358. for (var i = 0, len = holeIndices.length; i < len; i++) {
  59359. var start = holeIndices[i] * dim;
  59360. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  59361. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  59362. }
  59363. }
  59364. var trianglesArea = 0;
  59365. for (i = 0; i < triangles.length; i += 3) {
  59366. var a = triangles[i] * dim;
  59367. var b = triangles[i + 1] * dim;
  59368. var c = triangles[i + 2] * dim;
  59369. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  59370. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  59371. }
  59372. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  59373. }
  59374. Earcut.deviation = deviation;
  59375. ;
  59376. function signedArea(data, start, end, dim) {
  59377. var sum = 0;
  59378. for (var i = start, j = end - dim; i < end; i += dim) {
  59379. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  59380. j = i;
  59381. }
  59382. return sum;
  59383. }
  59384. /**
  59385. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  59386. */
  59387. function flatten(data) {
  59388. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  59389. for (var i = 0; i < data.length; i++) {
  59390. for (var j = 0; j < data[i].length; j++) {
  59391. for (var d = 0; d < dim; d++)
  59392. result.vertices.push(data[i][j][d]);
  59393. }
  59394. if (i > 0) {
  59395. holeIndex += data[i - 1].length;
  59396. result.holes.push(holeIndex);
  59397. }
  59398. }
  59399. return result;
  59400. }
  59401. Earcut.flatten = flatten;
  59402. ;
  59403. })(Earcut || (Earcut = {}));
  59404. //# sourceMappingURL=babylon.earcut.js.map
  59405. /// <reference path="..\Math\babylon.math.ts" />
  59406. var BABYLON;
  59407. (function (BABYLON) {
  59408. var IndexedVector2 = (function (_super) {
  59409. __extends(IndexedVector2, _super);
  59410. function IndexedVector2(original, index) {
  59411. var _this = _super.call(this, original.x, original.y) || this;
  59412. _this.index = index;
  59413. return _this;
  59414. }
  59415. return IndexedVector2;
  59416. }(BABYLON.Vector2));
  59417. var PolygonPoints = (function () {
  59418. function PolygonPoints() {
  59419. this.elements = new Array();
  59420. }
  59421. PolygonPoints.prototype.add = function (originalPoints) {
  59422. var _this = this;
  59423. var result = new Array();
  59424. originalPoints.forEach(function (point) {
  59425. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  59426. var newPoint = new IndexedVector2(point, _this.elements.length);
  59427. result.push(newPoint);
  59428. _this.elements.push(newPoint);
  59429. }
  59430. });
  59431. return result;
  59432. };
  59433. PolygonPoints.prototype.computeBounds = function () {
  59434. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  59435. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  59436. this.elements.forEach(function (point) {
  59437. // x
  59438. if (point.x < lmin.x) {
  59439. lmin.x = point.x;
  59440. }
  59441. else if (point.x > lmax.x) {
  59442. lmax.x = point.x;
  59443. }
  59444. // y
  59445. if (point.y < lmin.y) {
  59446. lmin.y = point.y;
  59447. }
  59448. else if (point.y > lmax.y) {
  59449. lmax.y = point.y;
  59450. }
  59451. });
  59452. return {
  59453. min: lmin,
  59454. max: lmax,
  59455. width: lmax.x - lmin.x,
  59456. height: lmax.y - lmin.y
  59457. };
  59458. };
  59459. return PolygonPoints;
  59460. }());
  59461. var Polygon = (function () {
  59462. function Polygon() {
  59463. }
  59464. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  59465. return [
  59466. new BABYLON.Vector2(xmin, ymin),
  59467. new BABYLON.Vector2(xmax, ymin),
  59468. new BABYLON.Vector2(xmax, ymax),
  59469. new BABYLON.Vector2(xmin, ymax)
  59470. ];
  59471. };
  59472. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  59473. if (cx === void 0) { cx = 0; }
  59474. if (cy === void 0) { cy = 0; }
  59475. if (numberOfSides === void 0) { numberOfSides = 32; }
  59476. var result = new Array();
  59477. var angle = 0;
  59478. var increment = (Math.PI * 2) / numberOfSides;
  59479. for (var i = 0; i < numberOfSides; i++) {
  59480. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  59481. angle -= increment;
  59482. }
  59483. return result;
  59484. };
  59485. Polygon.Parse = function (input) {
  59486. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  59487. var i, result = [];
  59488. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  59489. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  59490. }
  59491. return result;
  59492. };
  59493. Polygon.StartingAt = function (x, y) {
  59494. return BABYLON.Path2.StartingAt(x, y);
  59495. };
  59496. return Polygon;
  59497. }());
  59498. BABYLON.Polygon = Polygon;
  59499. var PolygonMeshBuilder = (function () {
  59500. function PolygonMeshBuilder(name, contours, scene) {
  59501. this._points = new PolygonPoints();
  59502. this._outlinepoints = new PolygonPoints();
  59503. this._holes = [];
  59504. this._epoints = new Array();
  59505. this._eholes = new Array();
  59506. this._name = name;
  59507. this._scene = scene;
  59508. var points;
  59509. if (contours instanceof BABYLON.Path2) {
  59510. points = contours.getPoints();
  59511. }
  59512. else {
  59513. points = contours;
  59514. }
  59515. this._addToepoint(points);
  59516. this._points.add(points);
  59517. this._outlinepoints.add(points);
  59518. }
  59519. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  59520. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  59521. var p = points_1[_i];
  59522. this._epoints.push(p.x, p.y);
  59523. }
  59524. };
  59525. PolygonMeshBuilder.prototype.addHole = function (hole) {
  59526. this._points.add(hole);
  59527. var holepoints = new PolygonPoints();
  59528. holepoints.add(hole);
  59529. this._holes.push(holepoints);
  59530. this._eholes.push(this._epoints.length / 2);
  59531. this._addToepoint(hole);
  59532. return this;
  59533. };
  59534. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  59535. var _this = this;
  59536. if (updatable === void 0) { updatable = false; }
  59537. var result = new BABYLON.Mesh(this._name, this._scene);
  59538. var normals = [];
  59539. var positions = [];
  59540. var uvs = [];
  59541. var bounds = this._points.computeBounds();
  59542. this._points.elements.forEach(function (p) {
  59543. normals.push(0, 1.0, 0);
  59544. positions.push(p.x, 0, p.y);
  59545. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  59546. });
  59547. var indices = [];
  59548. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  59549. for (var i = 0; i < res.length; i++) {
  59550. indices.push(res[i]);
  59551. }
  59552. if (depth > 0) {
  59553. var positionscount = (positions.length / 3); //get the current pointcount
  59554. this._points.elements.forEach(function (p) {
  59555. normals.push(0, -1.0, 0);
  59556. positions.push(p.x, -depth, p.y);
  59557. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  59558. });
  59559. var totalCount = indices.length;
  59560. for (var i = 0; i < totalCount; i += 3) {
  59561. var i0 = indices[i + 0];
  59562. var i1 = indices[i + 1];
  59563. var i2 = indices[i + 2];
  59564. indices.push(i2 + positionscount);
  59565. indices.push(i1 + positionscount);
  59566. indices.push(i0 + positionscount);
  59567. }
  59568. //Add the sides
  59569. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  59570. this._holes.forEach(function (hole) {
  59571. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  59572. });
  59573. }
  59574. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  59575. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  59576. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  59577. result.setIndices(indices);
  59578. return result;
  59579. };
  59580. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  59581. var StartIndex = positions.length / 3;
  59582. var ulength = 0;
  59583. for (var i = 0; i < points.elements.length; i++) {
  59584. var p = points.elements[i];
  59585. var p1;
  59586. if ((i + 1) > points.elements.length - 1) {
  59587. p1 = points.elements[0];
  59588. }
  59589. else {
  59590. p1 = points.elements[i + 1];
  59591. }
  59592. positions.push(p.x, 0, p.y);
  59593. positions.push(p.x, -depth, p.y);
  59594. positions.push(p1.x, 0, p1.y);
  59595. positions.push(p1.x, -depth, p1.y);
  59596. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  59597. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  59598. var v3 = v2.subtract(v1);
  59599. var v4 = new BABYLON.Vector3(0, 1, 0);
  59600. var vn = BABYLON.Vector3.Cross(v3, v4);
  59601. vn = vn.normalize();
  59602. uvs.push(ulength / bounds.width, 0);
  59603. uvs.push(ulength / bounds.width, 1);
  59604. ulength += v3.length();
  59605. uvs.push((ulength / bounds.width), 0);
  59606. uvs.push((ulength / bounds.width), 1);
  59607. if (!flip) {
  59608. normals.push(-vn.x, -vn.y, -vn.z);
  59609. normals.push(-vn.x, -vn.y, -vn.z);
  59610. normals.push(-vn.x, -vn.y, -vn.z);
  59611. normals.push(-vn.x, -vn.y, -vn.z);
  59612. indices.push(StartIndex);
  59613. indices.push(StartIndex + 1);
  59614. indices.push(StartIndex + 2);
  59615. indices.push(StartIndex + 1);
  59616. indices.push(StartIndex + 3);
  59617. indices.push(StartIndex + 2);
  59618. }
  59619. else {
  59620. normals.push(vn.x, vn.y, vn.z);
  59621. normals.push(vn.x, vn.y, vn.z);
  59622. normals.push(vn.x, vn.y, vn.z);
  59623. normals.push(vn.x, vn.y, vn.z);
  59624. indices.push(StartIndex);
  59625. indices.push(StartIndex + 2);
  59626. indices.push(StartIndex + 1);
  59627. indices.push(StartIndex + 1);
  59628. indices.push(StartIndex + 2);
  59629. indices.push(StartIndex + 3);
  59630. }
  59631. StartIndex += 4;
  59632. }
  59633. ;
  59634. };
  59635. return PolygonMeshBuilder;
  59636. }());
  59637. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  59638. })(BABYLON || (BABYLON = {}));
  59639. //# sourceMappingURL=babylon.polygonMesh.js.map
  59640. var BABYLON;
  59641. (function (BABYLON) {
  59642. // Unique ID when we import meshes from Babylon to CSG
  59643. var currentCSGMeshId = 0;
  59644. // # class Vertex
  59645. // Represents a vertex of a polygon. Use your own vertex class instead of this
  59646. // one to provide additional features like texture coordinates and vertex
  59647. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  59648. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  59649. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  59650. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  59651. // is not used anywhere else.
  59652. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  59653. var Vertex = (function () {
  59654. function Vertex(pos, normal, uv) {
  59655. this.pos = pos;
  59656. this.normal = normal;
  59657. this.uv = uv;
  59658. }
  59659. Vertex.prototype.clone = function () {
  59660. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  59661. };
  59662. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  59663. // orientation of a polygon is flipped.
  59664. Vertex.prototype.flip = function () {
  59665. this.normal = this.normal.scale(-1);
  59666. };
  59667. // Create a new vertex between this vertex and `other` by linearly
  59668. // interpolating all properties using a parameter of `t`. Subclasses should
  59669. // override this to interpolate additional properties.
  59670. Vertex.prototype.interpolate = function (other, t) {
  59671. 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));
  59672. };
  59673. return Vertex;
  59674. }());
  59675. // # class Plane
  59676. // Represents a plane in 3D space.
  59677. var Plane = (function () {
  59678. function Plane(normal, w) {
  59679. this.normal = normal;
  59680. this.w = w;
  59681. }
  59682. Plane.FromPoints = function (a, b, c) {
  59683. var v0 = c.subtract(a);
  59684. var v1 = b.subtract(a);
  59685. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  59686. return null;
  59687. }
  59688. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  59689. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  59690. };
  59691. Plane.prototype.clone = function () {
  59692. return new Plane(this.normal.clone(), this.w);
  59693. };
  59694. Plane.prototype.flip = function () {
  59695. this.normal.scaleInPlace(-1);
  59696. this.w = -this.w;
  59697. };
  59698. // Split `polygon` by this plane if needed, then put the polygon or polygon
  59699. // fragments in the appropriate lists. Coplanar polygons go into either
  59700. // `coplanarFront` or `coplanarBack` depending on their orientation with
  59701. // respect to this plane. Polygons in front or in back of this plane go into
  59702. // either `front` or `back`.
  59703. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  59704. var COPLANAR = 0;
  59705. var FRONT = 1;
  59706. var BACK = 2;
  59707. var SPANNING = 3;
  59708. // Classify each point as well as the entire polygon into one of the above
  59709. // four classes.
  59710. var polygonType = 0;
  59711. var types = [];
  59712. var i;
  59713. var t;
  59714. for (i = 0; i < polygon.vertices.length; i++) {
  59715. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  59716. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  59717. polygonType |= type;
  59718. types.push(type);
  59719. }
  59720. // Put the polygon in the correct list, splitting it when necessary.
  59721. switch (polygonType) {
  59722. case COPLANAR:
  59723. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  59724. break;
  59725. case FRONT:
  59726. front.push(polygon);
  59727. break;
  59728. case BACK:
  59729. back.push(polygon);
  59730. break;
  59731. case SPANNING:
  59732. var f = [], b = [];
  59733. for (i = 0; i < polygon.vertices.length; i++) {
  59734. var j = (i + 1) % polygon.vertices.length;
  59735. var ti = types[i], tj = types[j];
  59736. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  59737. if (ti !== BACK)
  59738. f.push(vi);
  59739. if (ti !== FRONT)
  59740. b.push(ti !== BACK ? vi.clone() : vi);
  59741. if ((ti | tj) === SPANNING) {
  59742. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  59743. var v = vi.interpolate(vj, t);
  59744. f.push(v);
  59745. b.push(v.clone());
  59746. }
  59747. }
  59748. var poly;
  59749. if (f.length >= 3) {
  59750. poly = new Polygon(f, polygon.shared);
  59751. if (poly.plane)
  59752. front.push(poly);
  59753. }
  59754. if (b.length >= 3) {
  59755. poly = new Polygon(b, polygon.shared);
  59756. if (poly.plane)
  59757. back.push(poly);
  59758. }
  59759. break;
  59760. }
  59761. };
  59762. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  59763. // point is on the plane.
  59764. Plane.EPSILON = 1e-5;
  59765. return Plane;
  59766. }());
  59767. // # class Polygon
  59768. // Represents a convex polygon. The vertices used to initialize a polygon must
  59769. // be coplanar and form a convex loop.
  59770. //
  59771. // Each convex polygon has a `shared` property, which is shared between all
  59772. // polygons that are clones of each other or were split from the same polygon.
  59773. // This can be used to define per-polygon properties (such as surface color).
  59774. var Polygon = (function () {
  59775. function Polygon(vertices, shared) {
  59776. this.vertices = vertices;
  59777. this.shared = shared;
  59778. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  59779. }
  59780. Polygon.prototype.clone = function () {
  59781. var vertices = this.vertices.map(function (v) { return v.clone(); });
  59782. return new Polygon(vertices, this.shared);
  59783. };
  59784. Polygon.prototype.flip = function () {
  59785. this.vertices.reverse().map(function (v) { v.flip(); });
  59786. this.plane.flip();
  59787. };
  59788. return Polygon;
  59789. }());
  59790. // # class Node
  59791. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  59792. // by picking a polygon to split along. That polygon (and all other coplanar
  59793. // polygons) are added directly to that node and the other polygons are added to
  59794. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  59795. // no distinction between internal and leaf nodes.
  59796. var Node = (function () {
  59797. function Node(polygons) {
  59798. this.plane = null;
  59799. this.front = null;
  59800. this.back = null;
  59801. this.polygons = [];
  59802. if (polygons) {
  59803. this.build(polygons);
  59804. }
  59805. }
  59806. Node.prototype.clone = function () {
  59807. var node = new Node();
  59808. node.plane = this.plane && this.plane.clone();
  59809. node.front = this.front && this.front.clone();
  59810. node.back = this.back && this.back.clone();
  59811. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  59812. return node;
  59813. };
  59814. // Convert solid space to empty space and empty space to solid space.
  59815. Node.prototype.invert = function () {
  59816. for (var i = 0; i < this.polygons.length; i++) {
  59817. this.polygons[i].flip();
  59818. }
  59819. if (this.plane) {
  59820. this.plane.flip();
  59821. }
  59822. if (this.front) {
  59823. this.front.invert();
  59824. }
  59825. if (this.back) {
  59826. this.back.invert();
  59827. }
  59828. var temp = this.front;
  59829. this.front = this.back;
  59830. this.back = temp;
  59831. };
  59832. // Recursively remove all polygons in `polygons` that are inside this BSP
  59833. // tree.
  59834. Node.prototype.clipPolygons = function (polygons) {
  59835. if (!this.plane)
  59836. return polygons.slice();
  59837. var front = [], back = [];
  59838. for (var i = 0; i < polygons.length; i++) {
  59839. this.plane.splitPolygon(polygons[i], front, back, front, back);
  59840. }
  59841. if (this.front) {
  59842. front = this.front.clipPolygons(front);
  59843. }
  59844. if (this.back) {
  59845. back = this.back.clipPolygons(back);
  59846. }
  59847. else {
  59848. back = [];
  59849. }
  59850. return front.concat(back);
  59851. };
  59852. // Remove all polygons in this BSP tree that are inside the other BSP tree
  59853. // `bsp`.
  59854. Node.prototype.clipTo = function (bsp) {
  59855. this.polygons = bsp.clipPolygons(this.polygons);
  59856. if (this.front)
  59857. this.front.clipTo(bsp);
  59858. if (this.back)
  59859. this.back.clipTo(bsp);
  59860. };
  59861. // Return a list of all polygons in this BSP tree.
  59862. Node.prototype.allPolygons = function () {
  59863. var polygons = this.polygons.slice();
  59864. if (this.front)
  59865. polygons = polygons.concat(this.front.allPolygons());
  59866. if (this.back)
  59867. polygons = polygons.concat(this.back.allPolygons());
  59868. return polygons;
  59869. };
  59870. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  59871. // new polygons are filtered down to the bottom of the tree and become new
  59872. // nodes there. Each set of polygons is partitioned using the first polygon
  59873. // (no heuristic is used to pick a good split).
  59874. Node.prototype.build = function (polygons) {
  59875. if (!polygons.length)
  59876. return;
  59877. if (!this.plane)
  59878. this.plane = polygons[0].plane.clone();
  59879. var front = [], back = [];
  59880. for (var i = 0; i < polygons.length; i++) {
  59881. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  59882. }
  59883. if (front.length) {
  59884. if (!this.front)
  59885. this.front = new Node();
  59886. this.front.build(front);
  59887. }
  59888. if (back.length) {
  59889. if (!this.back)
  59890. this.back = new Node();
  59891. this.back.build(back);
  59892. }
  59893. };
  59894. return Node;
  59895. }());
  59896. var CSG = (function () {
  59897. function CSG() {
  59898. this.polygons = new Array();
  59899. }
  59900. // Convert BABYLON.Mesh to BABYLON.CSG
  59901. CSG.FromMesh = function (mesh) {
  59902. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  59903. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  59904. if (mesh instanceof BABYLON.Mesh) {
  59905. mesh.computeWorldMatrix(true);
  59906. matrix = mesh.getWorldMatrix();
  59907. meshPosition = mesh.position.clone();
  59908. meshRotation = mesh.rotation.clone();
  59909. if (mesh.rotationQuaternion) {
  59910. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  59911. }
  59912. meshScaling = mesh.scaling.clone();
  59913. }
  59914. else {
  59915. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  59916. }
  59917. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59918. var subMeshes = mesh.subMeshes;
  59919. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  59920. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  59921. vertices = [];
  59922. for (var j = 0; j < 3; j++) {
  59923. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  59924. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  59925. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  59926. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  59927. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  59928. vertex = new Vertex(position, normal, uv);
  59929. vertices.push(vertex);
  59930. }
  59931. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  59932. // To handle the case of degenerated triangle
  59933. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  59934. if (polygon.plane)
  59935. polygons.push(polygon);
  59936. }
  59937. }
  59938. var csg = CSG.FromPolygons(polygons);
  59939. csg.matrix = matrix;
  59940. csg.position = meshPosition;
  59941. csg.rotation = meshRotation;
  59942. csg.scaling = meshScaling;
  59943. csg.rotationQuaternion = meshRotationQuaternion;
  59944. currentCSGMeshId++;
  59945. return csg;
  59946. };
  59947. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  59948. CSG.FromPolygons = function (polygons) {
  59949. var csg = new CSG();
  59950. csg.polygons = polygons;
  59951. return csg;
  59952. };
  59953. CSG.prototype.clone = function () {
  59954. var csg = new CSG();
  59955. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  59956. csg.copyTransformAttributes(this);
  59957. return csg;
  59958. };
  59959. CSG.prototype.toPolygons = function () {
  59960. return this.polygons;
  59961. };
  59962. CSG.prototype.union = function (csg) {
  59963. var a = new Node(this.clone().polygons);
  59964. var b = new Node(csg.clone().polygons);
  59965. a.clipTo(b);
  59966. b.clipTo(a);
  59967. b.invert();
  59968. b.clipTo(a);
  59969. b.invert();
  59970. a.build(b.allPolygons());
  59971. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59972. };
  59973. CSG.prototype.unionInPlace = function (csg) {
  59974. var a = new Node(this.polygons);
  59975. var b = new Node(csg.polygons);
  59976. a.clipTo(b);
  59977. b.clipTo(a);
  59978. b.invert();
  59979. b.clipTo(a);
  59980. b.invert();
  59981. a.build(b.allPolygons());
  59982. this.polygons = a.allPolygons();
  59983. };
  59984. CSG.prototype.subtract = function (csg) {
  59985. var a = new Node(this.clone().polygons);
  59986. var b = new Node(csg.clone().polygons);
  59987. a.invert();
  59988. a.clipTo(b);
  59989. b.clipTo(a);
  59990. b.invert();
  59991. b.clipTo(a);
  59992. b.invert();
  59993. a.build(b.allPolygons());
  59994. a.invert();
  59995. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59996. };
  59997. CSG.prototype.subtractInPlace = function (csg) {
  59998. var a = new Node(this.polygons);
  59999. var b = new Node(csg.polygons);
  60000. a.invert();
  60001. a.clipTo(b);
  60002. b.clipTo(a);
  60003. b.invert();
  60004. b.clipTo(a);
  60005. b.invert();
  60006. a.build(b.allPolygons());
  60007. a.invert();
  60008. this.polygons = a.allPolygons();
  60009. };
  60010. CSG.prototype.intersect = function (csg) {
  60011. var a = new Node(this.clone().polygons);
  60012. var b = new Node(csg.clone().polygons);
  60013. a.invert();
  60014. b.clipTo(a);
  60015. b.invert();
  60016. a.clipTo(b);
  60017. b.clipTo(a);
  60018. a.build(b.allPolygons());
  60019. a.invert();
  60020. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60021. };
  60022. CSG.prototype.intersectInPlace = function (csg) {
  60023. var a = new Node(this.polygons);
  60024. var b = new Node(csg.polygons);
  60025. a.invert();
  60026. b.clipTo(a);
  60027. b.invert();
  60028. a.clipTo(b);
  60029. b.clipTo(a);
  60030. a.build(b.allPolygons());
  60031. a.invert();
  60032. this.polygons = a.allPolygons();
  60033. };
  60034. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  60035. // not modified.
  60036. CSG.prototype.inverse = function () {
  60037. var csg = this.clone();
  60038. csg.inverseInPlace();
  60039. return csg;
  60040. };
  60041. CSG.prototype.inverseInPlace = function () {
  60042. this.polygons.map(function (p) { p.flip(); });
  60043. };
  60044. // This is used to keep meshes transformations so they can be restored
  60045. // when we build back a Babylon Mesh
  60046. // NB : All CSG operations are performed in world coordinates
  60047. CSG.prototype.copyTransformAttributes = function (csg) {
  60048. this.matrix = csg.matrix;
  60049. this.position = csg.position;
  60050. this.rotation = csg.rotation;
  60051. this.scaling = csg.scaling;
  60052. this.rotationQuaternion = csg.rotationQuaternion;
  60053. return this;
  60054. };
  60055. // Build Raw mesh from CSG
  60056. // Coordinates here are in world space
  60057. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  60058. var matrix = this.matrix.clone();
  60059. matrix.invert();
  60060. 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;
  60061. if (keepSubMeshes) {
  60062. // Sort Polygons, since subMeshes are indices range
  60063. polygons.sort(function (a, b) {
  60064. if (a.shared.meshId === b.shared.meshId) {
  60065. return a.shared.subMeshId - b.shared.subMeshId;
  60066. }
  60067. else {
  60068. return a.shared.meshId - b.shared.meshId;
  60069. }
  60070. });
  60071. }
  60072. for (var i = 0, il = polygons.length; i < il; i++) {
  60073. polygon = polygons[i];
  60074. // Building SubMeshes
  60075. if (!subMesh_dict[polygon.shared.meshId]) {
  60076. subMesh_dict[polygon.shared.meshId] = {};
  60077. }
  60078. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  60079. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  60080. indexStart: +Infinity,
  60081. indexEnd: -Infinity,
  60082. materialIndex: polygon.shared.materialIndex
  60083. };
  60084. }
  60085. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  60086. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  60087. polygonIndices[0] = 0;
  60088. polygonIndices[1] = j - 1;
  60089. polygonIndices[2] = j;
  60090. for (var k = 0; k < 3; k++) {
  60091. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  60092. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  60093. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  60094. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  60095. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  60096. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  60097. // Check if 2 points can be merged
  60098. if (!(typeof vertex_idx !== 'undefined' &&
  60099. normals[vertex_idx * 3] === localNormal.x &&
  60100. normals[vertex_idx * 3 + 1] === localNormal.y &&
  60101. normals[vertex_idx * 3 + 2] === localNormal.z &&
  60102. uvs[vertex_idx * 2] === uv.x &&
  60103. uvs[vertex_idx * 2 + 1] === uv.y)) {
  60104. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  60105. uvs.push(uv.x, uv.y);
  60106. normals.push(normal.x, normal.y, normal.z);
  60107. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  60108. }
  60109. indices.push(vertex_idx);
  60110. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  60111. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  60112. currentIndex++;
  60113. }
  60114. }
  60115. }
  60116. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  60117. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  60118. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  60119. mesh.setIndices(indices);
  60120. if (keepSubMeshes) {
  60121. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  60122. var materialIndexOffset = 0, materialMaxIndex;
  60123. mesh.subMeshes = new Array();
  60124. for (var m in subMesh_dict) {
  60125. materialMaxIndex = -1;
  60126. for (var sm in subMesh_dict[m]) {
  60127. subMesh_obj = subMesh_dict[m][sm];
  60128. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  60129. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  60130. }
  60131. materialIndexOffset += ++materialMaxIndex;
  60132. }
  60133. }
  60134. return mesh;
  60135. };
  60136. // Build Mesh from CSG taking material and transforms into account
  60137. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  60138. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  60139. mesh.material = material;
  60140. mesh.position.copyFrom(this.position);
  60141. mesh.rotation.copyFrom(this.rotation);
  60142. if (this.rotationQuaternion) {
  60143. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  60144. }
  60145. mesh.scaling.copyFrom(this.scaling);
  60146. mesh.computeWorldMatrix(true);
  60147. return mesh;
  60148. };
  60149. return CSG;
  60150. }());
  60151. BABYLON.CSG = CSG;
  60152. })(BABYLON || (BABYLON = {}));
  60153. //# sourceMappingURL=babylon.csg.js.map
  60154. var BABYLON;
  60155. (function (BABYLON) {
  60156. var LensFlare = (function () {
  60157. function LensFlare(size, position, color, imgUrl, system) {
  60158. this.size = size;
  60159. this.position = position;
  60160. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  60161. this.dispose = function () {
  60162. if (this.texture) {
  60163. this.texture.dispose();
  60164. }
  60165. // Remove from scene
  60166. var index = this._system.lensFlares.indexOf(this);
  60167. this._system.lensFlares.splice(index, 1);
  60168. };
  60169. this.color = color || new BABYLON.Color3(1, 1, 1);
  60170. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  60171. this._system = system;
  60172. system.lensFlares.push(this);
  60173. }
  60174. return LensFlare;
  60175. }());
  60176. BABYLON.LensFlare = LensFlare;
  60177. })(BABYLON || (BABYLON = {}));
  60178. //# sourceMappingURL=babylon.lensFlare.js.map
  60179. var BABYLON;
  60180. (function (BABYLON) {
  60181. var LensFlareSystem = (function () {
  60182. function LensFlareSystem(name, emitter, scene) {
  60183. this.name = name;
  60184. this.lensFlares = new Array();
  60185. this.borderLimit = 300;
  60186. this.viewportBorder = 0;
  60187. this.layerMask = 0x0FFFFFFF;
  60188. this._vertexBuffers = {};
  60189. this._isEnabled = true;
  60190. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60191. this._emitter = emitter;
  60192. this.id = name;
  60193. scene.lensFlareSystems.push(this);
  60194. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  60195. var engine = scene.getEngine();
  60196. // VBO
  60197. var vertices = [];
  60198. vertices.push(1, 1);
  60199. vertices.push(-1, 1);
  60200. vertices.push(-1, -1);
  60201. vertices.push(1, -1);
  60202. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60203. // Indices
  60204. var indices = [];
  60205. indices.push(0);
  60206. indices.push(1);
  60207. indices.push(2);
  60208. indices.push(0);
  60209. indices.push(2);
  60210. indices.push(3);
  60211. this._indexBuffer = engine.createIndexBuffer(indices);
  60212. // Effects
  60213. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  60214. }
  60215. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  60216. get: function () {
  60217. return this._isEnabled;
  60218. },
  60219. set: function (value) {
  60220. this._isEnabled = value;
  60221. },
  60222. enumerable: true,
  60223. configurable: true
  60224. });
  60225. LensFlareSystem.prototype.getScene = function () {
  60226. return this._scene;
  60227. };
  60228. LensFlareSystem.prototype.getEmitter = function () {
  60229. return this._emitter;
  60230. };
  60231. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  60232. this._emitter = newEmitter;
  60233. };
  60234. LensFlareSystem.prototype.getEmitterPosition = function () {
  60235. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  60236. };
  60237. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  60238. var position = this.getEmitterPosition();
  60239. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  60240. this._positionX = position.x;
  60241. this._positionY = position.y;
  60242. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  60243. if (this.viewportBorder > 0) {
  60244. globalViewport.x -= this.viewportBorder;
  60245. globalViewport.y -= this.viewportBorder;
  60246. globalViewport.width += this.viewportBorder * 2;
  60247. globalViewport.height += this.viewportBorder * 2;
  60248. position.x += this.viewportBorder;
  60249. position.y += this.viewportBorder;
  60250. this._positionX += this.viewportBorder;
  60251. this._positionY += this.viewportBorder;
  60252. }
  60253. if (position.z > 0) {
  60254. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  60255. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  60256. return true;
  60257. }
  60258. return true;
  60259. }
  60260. return false;
  60261. };
  60262. LensFlareSystem.prototype._isVisible = function () {
  60263. if (!this._isEnabled) {
  60264. return false;
  60265. }
  60266. var emitterPosition = this.getEmitterPosition();
  60267. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  60268. var distance = direction.length();
  60269. direction.normalize();
  60270. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  60271. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  60272. return !pickInfo.hit || pickInfo.distance > distance;
  60273. };
  60274. LensFlareSystem.prototype.render = function () {
  60275. if (!this._effect.isReady())
  60276. return false;
  60277. var engine = this._scene.getEngine();
  60278. var viewport = this._scene.activeCamera.viewport;
  60279. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  60280. // Position
  60281. if (!this.computeEffectivePosition(globalViewport)) {
  60282. return false;
  60283. }
  60284. // Visibility
  60285. if (!this._isVisible()) {
  60286. return false;
  60287. }
  60288. // Intensity
  60289. var awayX;
  60290. var awayY;
  60291. if (this._positionX < this.borderLimit + globalViewport.x) {
  60292. awayX = this.borderLimit + globalViewport.x - this._positionX;
  60293. }
  60294. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  60295. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  60296. }
  60297. else {
  60298. awayX = 0;
  60299. }
  60300. if (this._positionY < this.borderLimit + globalViewport.y) {
  60301. awayY = this.borderLimit + globalViewport.y - this._positionY;
  60302. }
  60303. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  60304. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  60305. }
  60306. else {
  60307. awayY = 0;
  60308. }
  60309. var away = (awayX > awayY) ? awayX : awayY;
  60310. away -= this.viewportBorder;
  60311. if (away > this.borderLimit) {
  60312. away = this.borderLimit;
  60313. }
  60314. var intensity = 1.0 - (away / this.borderLimit);
  60315. if (intensity < 0) {
  60316. return false;
  60317. }
  60318. if (intensity > 1.0) {
  60319. intensity = 1.0;
  60320. }
  60321. if (this.viewportBorder > 0) {
  60322. globalViewport.x += this.viewportBorder;
  60323. globalViewport.y += this.viewportBorder;
  60324. globalViewport.width -= this.viewportBorder * 2;
  60325. globalViewport.height -= this.viewportBorder * 2;
  60326. this._positionX -= this.viewportBorder;
  60327. this._positionY -= this.viewportBorder;
  60328. }
  60329. // Position
  60330. var centerX = globalViewport.x + globalViewport.width / 2;
  60331. var centerY = globalViewport.y + globalViewport.height / 2;
  60332. var distX = centerX - this._positionX;
  60333. var distY = centerY - this._positionY;
  60334. // Effects
  60335. engine.enableEffect(this._effect);
  60336. engine.setState(false);
  60337. engine.setDepthBuffer(false);
  60338. // VBOs
  60339. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60340. // Flares
  60341. for (var index = 0; index < this.lensFlares.length; index++) {
  60342. var flare = this.lensFlares[index];
  60343. engine.setAlphaMode(flare.alphaMode);
  60344. var x = centerX - (distX * flare.position);
  60345. var y = centerY - (distY * flare.position);
  60346. var cw = flare.size;
  60347. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  60348. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  60349. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  60350. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  60351. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  60352. // Texture
  60353. this._effect.setTexture("textureSampler", flare.texture);
  60354. // Color
  60355. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  60356. // Draw order
  60357. engine.draw(true, 0, 6);
  60358. }
  60359. engine.setDepthBuffer(true);
  60360. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60361. return true;
  60362. };
  60363. LensFlareSystem.prototype.dispose = function () {
  60364. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60365. if (vertexBuffer) {
  60366. vertexBuffer.dispose();
  60367. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60368. }
  60369. if (this._indexBuffer) {
  60370. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60371. this._indexBuffer = null;
  60372. }
  60373. while (this.lensFlares.length) {
  60374. this.lensFlares[0].dispose();
  60375. }
  60376. // Remove from scene
  60377. var index = this._scene.lensFlareSystems.indexOf(this);
  60378. this._scene.lensFlareSystems.splice(index, 1);
  60379. };
  60380. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  60381. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  60382. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  60383. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  60384. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  60385. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  60386. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  60387. var parsedFlare = parsedLensFlareSystem.flares[index];
  60388. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  60389. }
  60390. return lensFlareSystem;
  60391. };
  60392. LensFlareSystem.prototype.serialize = function () {
  60393. var serializationObject = {};
  60394. serializationObject.id = this.id;
  60395. serializationObject.name = this.name;
  60396. serializationObject.emitterId = this.getEmitter().id;
  60397. serializationObject.borderLimit = this.borderLimit;
  60398. serializationObject.flares = [];
  60399. for (var index = 0; index < this.lensFlares.length; index++) {
  60400. var flare = this.lensFlares[index];
  60401. serializationObject.flares.push({
  60402. size: flare.size,
  60403. position: flare.position,
  60404. color: flare.color.asArray(),
  60405. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  60406. });
  60407. }
  60408. return serializationObject;
  60409. };
  60410. return LensFlareSystem;
  60411. }());
  60412. BABYLON.LensFlareSystem = LensFlareSystem;
  60413. })(BABYLON || (BABYLON = {}));
  60414. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  60415. var BABYLON;
  60416. (function (BABYLON) {
  60417. /**
  60418. * This is a holder class for the physics joint created by the physics plugin.
  60419. * It holds a set of functions to control the underlying joint.
  60420. */
  60421. var PhysicsJoint = (function () {
  60422. function PhysicsJoint(type, jointData) {
  60423. this.type = type;
  60424. this.jointData = jointData;
  60425. jointData.nativeParams = jointData.nativeParams || {};
  60426. }
  60427. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  60428. get: function () {
  60429. return this._physicsJoint;
  60430. },
  60431. set: function (newJoint) {
  60432. if (this._physicsJoint) {
  60433. //remove from the wolrd
  60434. }
  60435. this._physicsJoint = newJoint;
  60436. },
  60437. enumerable: true,
  60438. configurable: true
  60439. });
  60440. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  60441. set: function (physicsPlugin) {
  60442. this._physicsPlugin = physicsPlugin;
  60443. },
  60444. enumerable: true,
  60445. configurable: true
  60446. });
  60447. /**
  60448. * Execute a function that is physics-plugin specific.
  60449. * @param {Function} func the function that will be executed.
  60450. * It accepts two parameters: the physics world and the physics joint.
  60451. */
  60452. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  60453. func(this._physicsPlugin.world, this._physicsJoint);
  60454. };
  60455. //TODO check if the native joints are the same
  60456. //Joint Types
  60457. PhysicsJoint.DistanceJoint = 0;
  60458. PhysicsJoint.HingeJoint = 1;
  60459. PhysicsJoint.BallAndSocketJoint = 2;
  60460. PhysicsJoint.WheelJoint = 3;
  60461. PhysicsJoint.SliderJoint = 4;
  60462. //OIMO
  60463. PhysicsJoint.PrismaticJoint = 5;
  60464. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  60465. PhysicsJoint.UniversalJoint = 6;
  60466. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  60467. //Cannon
  60468. //Similar to a Ball-Joint. Different in params
  60469. PhysicsJoint.PointToPointJoint = 8;
  60470. //Cannon only at the moment
  60471. PhysicsJoint.SpringJoint = 9;
  60472. PhysicsJoint.LockJoint = 10;
  60473. return PhysicsJoint;
  60474. }());
  60475. BABYLON.PhysicsJoint = PhysicsJoint;
  60476. /**
  60477. * A class representing a physics distance joint.
  60478. */
  60479. var DistanceJoint = (function (_super) {
  60480. __extends(DistanceJoint, _super);
  60481. function DistanceJoint(jointData) {
  60482. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  60483. }
  60484. /**
  60485. * Update the predefined distance.
  60486. */
  60487. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  60488. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  60489. };
  60490. return DistanceJoint;
  60491. }(PhysicsJoint));
  60492. BABYLON.DistanceJoint = DistanceJoint;
  60493. var MotorEnabledJoint = (function (_super) {
  60494. __extends(MotorEnabledJoint, _super);
  60495. function MotorEnabledJoint(type, jointData) {
  60496. return _super.call(this, type, jointData) || this;
  60497. }
  60498. /**
  60499. * Set the motor values.
  60500. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60501. * @param {number} force the force to apply
  60502. * @param {number} maxForce max force for this motor.
  60503. */
  60504. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  60505. this._physicsPlugin.setMotor(this, force, maxForce);
  60506. };
  60507. /**
  60508. * Set the motor's limits.
  60509. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60510. */
  60511. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  60512. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  60513. };
  60514. return MotorEnabledJoint;
  60515. }(PhysicsJoint));
  60516. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  60517. /**
  60518. * This class represents a single hinge physics joint
  60519. */
  60520. var HingeJoint = (function (_super) {
  60521. __extends(HingeJoint, _super);
  60522. function HingeJoint(jointData) {
  60523. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  60524. }
  60525. /**
  60526. * Set the motor values.
  60527. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60528. * @param {number} force the force to apply
  60529. * @param {number} maxForce max force for this motor.
  60530. */
  60531. HingeJoint.prototype.setMotor = function (force, maxForce) {
  60532. this._physicsPlugin.setMotor(this, force, maxForce);
  60533. };
  60534. /**
  60535. * Set the motor's limits.
  60536. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60537. */
  60538. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  60539. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  60540. };
  60541. return HingeJoint;
  60542. }(MotorEnabledJoint));
  60543. BABYLON.HingeJoint = HingeJoint;
  60544. /**
  60545. * This class represents a dual hinge physics joint (same as wheel joint)
  60546. */
  60547. var Hinge2Joint = (function (_super) {
  60548. __extends(Hinge2Joint, _super);
  60549. function Hinge2Joint(jointData) {
  60550. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  60551. }
  60552. /**
  60553. * Set the motor values.
  60554. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60555. * @param {number} force the force to apply
  60556. * @param {number} maxForce max force for this motor.
  60557. * @param {motorIndex} the motor's index, 0 or 1.
  60558. */
  60559. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  60560. if (motorIndex === void 0) { motorIndex = 0; }
  60561. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  60562. };
  60563. /**
  60564. * Set the motor limits.
  60565. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60566. * @param {number} upperLimit the upper limit
  60567. * @param {number} lowerLimit lower limit
  60568. * @param {motorIndex} the motor's index, 0 or 1.
  60569. */
  60570. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  60571. if (motorIndex === void 0) { motorIndex = 0; }
  60572. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  60573. };
  60574. return Hinge2Joint;
  60575. }(MotorEnabledJoint));
  60576. BABYLON.Hinge2Joint = Hinge2Joint;
  60577. })(BABYLON || (BABYLON = {}));
  60578. //# sourceMappingURL=babylon.physicsJoint.js.map
  60579. var BABYLON;
  60580. (function (BABYLON) {
  60581. var PhysicsImpostor = (function () {
  60582. function PhysicsImpostor(object, type, _options, _scene) {
  60583. if (_options === void 0) { _options = { mass: 0 }; }
  60584. var _this = this;
  60585. this.object = object;
  60586. this.type = type;
  60587. this._options = _options;
  60588. this._scene = _scene;
  60589. this._bodyUpdateRequired = false;
  60590. this._onBeforePhysicsStepCallbacks = new Array();
  60591. this._onAfterPhysicsStepCallbacks = new Array();
  60592. this._onPhysicsCollideCallbacks = [];
  60593. this._deltaPosition = BABYLON.Vector3.Zero();
  60594. this._isDisposed = false;
  60595. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  60596. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  60597. /**
  60598. * this function is executed by the physics engine.
  60599. */
  60600. this.beforeStep = function () {
  60601. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  60602. //conjugate deltaRotation
  60603. if (_this._deltaRotationConjugated) {
  60604. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  60605. }
  60606. else {
  60607. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  60608. }
  60609. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  60610. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  60611. func(_this);
  60612. });
  60613. };
  60614. /**
  60615. * this function is executed by the physics engine.
  60616. */
  60617. this.afterStep = function () {
  60618. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  60619. func(_this);
  60620. });
  60621. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  60622. _this.object.position.addInPlace(_this._deltaPosition);
  60623. if (_this._deltaRotation) {
  60624. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  60625. }
  60626. };
  60627. /**
  60628. * Legacy collision detection event support
  60629. */
  60630. this.onCollideEvent = null;
  60631. //event and body object due to cannon's event-based architecture.
  60632. this.onCollide = function (e) {
  60633. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  60634. return;
  60635. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  60636. if (otherImpostor) {
  60637. // Legacy collision detection event support
  60638. if (_this.onCollideEvent) {
  60639. _this.onCollideEvent(_this, otherImpostor);
  60640. }
  60641. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  60642. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  60643. }).forEach(function (obj) {
  60644. obj.callback(_this, otherImpostor);
  60645. });
  60646. }
  60647. };
  60648. //sanity check!
  60649. if (!this.object) {
  60650. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  60651. return;
  60652. }
  60653. //legacy support for old syntax.
  60654. if (!this._scene && object.getScene) {
  60655. this._scene = object.getScene();
  60656. }
  60657. this._physicsEngine = this._scene.getPhysicsEngine();
  60658. if (!this._physicsEngine) {
  60659. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  60660. }
  60661. else {
  60662. //set the object's quaternion, if not set
  60663. if (!this.object.rotationQuaternion) {
  60664. if (this.object.rotation) {
  60665. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  60666. }
  60667. else {
  60668. this.object.rotationQuaternion = new BABYLON.Quaternion();
  60669. }
  60670. }
  60671. //default options params
  60672. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  60673. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  60674. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  60675. this._joints = [];
  60676. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  60677. if (!this.object.parent) {
  60678. this._init();
  60679. }
  60680. else if (this.object.parent.physicsImpostor) {
  60681. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  60682. }
  60683. }
  60684. }
  60685. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  60686. get: function () {
  60687. return this._isDisposed;
  60688. },
  60689. enumerable: true,
  60690. configurable: true
  60691. });
  60692. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  60693. get: function () {
  60694. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  60695. },
  60696. set: function (value) {
  60697. this.setMass(value);
  60698. },
  60699. enumerable: true,
  60700. configurable: true
  60701. });
  60702. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  60703. get: function () {
  60704. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  60705. },
  60706. set: function (value) {
  60707. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  60708. },
  60709. enumerable: true,
  60710. configurable: true
  60711. });
  60712. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  60713. get: function () {
  60714. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  60715. },
  60716. set: function (value) {
  60717. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  60718. },
  60719. enumerable: true,
  60720. configurable: true
  60721. });
  60722. /**
  60723. * This function will completly initialize this impostor.
  60724. * It will create a new body - but only if this mesh has no parent.
  60725. * If it has, this impostor will not be used other than to define the impostor
  60726. * of the child mesh.
  60727. */
  60728. PhysicsImpostor.prototype._init = function () {
  60729. this._physicsEngine.removeImpostor(this);
  60730. this.physicsBody = null;
  60731. this._parent = this._parent || this._getPhysicsParent();
  60732. if (!this.parent) {
  60733. this._physicsEngine.addImpostor(this);
  60734. }
  60735. };
  60736. PhysicsImpostor.prototype._getPhysicsParent = function () {
  60737. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  60738. var parentMesh = this.object.parent;
  60739. return parentMesh.physicsImpostor;
  60740. }
  60741. return;
  60742. };
  60743. /**
  60744. * Should a new body be generated.
  60745. */
  60746. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  60747. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  60748. };
  60749. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  60750. this.forceUpdate();
  60751. };
  60752. /**
  60753. * Force a regeneration of this or the parent's impostor's body.
  60754. * Use under cautious - This will remove all joints already implemented.
  60755. */
  60756. PhysicsImpostor.prototype.forceUpdate = function () {
  60757. this._init();
  60758. if (this.parent) {
  60759. this.parent.forceUpdate();
  60760. }
  60761. };
  60762. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  60763. /*public get mesh(): AbstractMesh {
  60764. return this._mesh;
  60765. }*/
  60766. /**
  60767. * Gets the body that holds this impostor. Either its own, or its parent.
  60768. */
  60769. get: function () {
  60770. return this._parent ? this._parent.physicsBody : this._physicsBody;
  60771. },
  60772. /**
  60773. * Set the physics body. Used mainly by the physics engine/plugin
  60774. */
  60775. set: function (physicsBody) {
  60776. if (this._physicsBody) {
  60777. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  60778. }
  60779. this._physicsBody = physicsBody;
  60780. this.resetUpdateFlags();
  60781. },
  60782. enumerable: true,
  60783. configurable: true
  60784. });
  60785. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  60786. get: function () {
  60787. return this._parent;
  60788. },
  60789. set: function (value) {
  60790. this._parent = value;
  60791. },
  60792. enumerable: true,
  60793. configurable: true
  60794. });
  60795. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  60796. this._bodyUpdateRequired = false;
  60797. };
  60798. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  60799. if (this.object.getBoundingInfo) {
  60800. var q = this.object.rotationQuaternion;
  60801. //reset rotation
  60802. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  60803. //calculate the world matrix with no rotation
  60804. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  60805. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  60806. //bring back the rotation
  60807. this.object.rotationQuaternion = q;
  60808. //calculate the world matrix with the new rotation
  60809. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  60810. return size;
  60811. }
  60812. else {
  60813. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  60814. }
  60815. };
  60816. PhysicsImpostor.prototype.getObjectCenter = function () {
  60817. if (this.object.getBoundingInfo) {
  60818. return this.object.getBoundingInfo().boundingBox.centerWorld;
  60819. }
  60820. else {
  60821. return this.object.position;
  60822. }
  60823. };
  60824. /**
  60825. * Get a specific parametes from the options parameter.
  60826. */
  60827. PhysicsImpostor.prototype.getParam = function (paramName) {
  60828. return this._options[paramName];
  60829. };
  60830. /**
  60831. * Sets a specific parameter in the options given to the physics plugin
  60832. */
  60833. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  60834. this._options[paramName] = value;
  60835. this._bodyUpdateRequired = true;
  60836. };
  60837. /**
  60838. * Specifically change the body's mass option. Won't recreate the physics body object
  60839. */
  60840. PhysicsImpostor.prototype.setMass = function (mass) {
  60841. if (this.getParam("mass") !== mass) {
  60842. this.setParam("mass", mass);
  60843. }
  60844. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  60845. };
  60846. PhysicsImpostor.prototype.getLinearVelocity = function () {
  60847. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  60848. };
  60849. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  60850. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  60851. };
  60852. PhysicsImpostor.prototype.getAngularVelocity = function () {
  60853. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  60854. };
  60855. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  60856. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  60857. };
  60858. /**
  60859. * Execute a function with the physics plugin native code.
  60860. * Provide a function the will have two variables - the world object and the physics body object.
  60861. */
  60862. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  60863. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  60864. };
  60865. /**
  60866. * Register a function that will be executed before the physics world is stepping forward.
  60867. */
  60868. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  60869. this._onBeforePhysicsStepCallbacks.push(func);
  60870. };
  60871. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  60872. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  60873. if (index > -1) {
  60874. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  60875. }
  60876. else {
  60877. BABYLON.Tools.Warn("Function to remove was not found");
  60878. }
  60879. };
  60880. /**
  60881. * Register a function that will be executed after the physics step
  60882. */
  60883. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  60884. this._onAfterPhysicsStepCallbacks.push(func);
  60885. };
  60886. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  60887. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  60888. if (index > -1) {
  60889. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  60890. }
  60891. else {
  60892. BABYLON.Tools.Warn("Function to remove was not found");
  60893. }
  60894. };
  60895. /**
  60896. * register a function that will be executed when this impostor collides against a different body.
  60897. */
  60898. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  60899. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  60900. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  60901. };
  60902. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  60903. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  60904. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  60905. if (index > -1) {
  60906. this._onPhysicsCollideCallbacks.splice(index, 1);
  60907. }
  60908. else {
  60909. BABYLON.Tools.Warn("Function to remove was not found");
  60910. }
  60911. };
  60912. /**
  60913. * Apply a force
  60914. */
  60915. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  60916. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  60917. };
  60918. /**
  60919. * Apply an impulse
  60920. */
  60921. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  60922. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  60923. };
  60924. /**
  60925. * A help function to create a joint.
  60926. */
  60927. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  60928. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  60929. this.addJoint(otherImpostor, joint);
  60930. };
  60931. /**
  60932. * Add a joint to this impostor with a different impostor.
  60933. */
  60934. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  60935. this._joints.push({
  60936. otherImpostor: otherImpostor,
  60937. joint: joint
  60938. });
  60939. this._physicsEngine.addJoint(this, otherImpostor, joint);
  60940. };
  60941. /**
  60942. * Will keep this body still, in a sleep mode.
  60943. */
  60944. PhysicsImpostor.prototype.sleep = function () {
  60945. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  60946. };
  60947. /**
  60948. * Wake the body up.
  60949. */
  60950. PhysicsImpostor.prototype.wakeUp = function () {
  60951. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  60952. };
  60953. PhysicsImpostor.prototype.clone = function (newObject) {
  60954. if (!newObject)
  60955. return null;
  60956. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  60957. };
  60958. PhysicsImpostor.prototype.dispose = function () {
  60959. var _this = this;
  60960. //no dispose if no physics engine is available.
  60961. if (!this._physicsEngine) {
  60962. return;
  60963. }
  60964. this._joints.forEach(function (j) {
  60965. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  60966. });
  60967. //dispose the physics body
  60968. this._physicsEngine.removeImpostor(this);
  60969. if (this.parent) {
  60970. this.parent.forceUpdate();
  60971. }
  60972. else {
  60973. /*this._object.getChildMeshes().forEach(function(mesh) {
  60974. if (mesh.physicsImpostor) {
  60975. if (disposeChildren) {
  60976. mesh.physicsImpostor.dispose();
  60977. mesh.physicsImpostor = null;
  60978. }
  60979. }
  60980. })*/
  60981. }
  60982. this._isDisposed = true;
  60983. };
  60984. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  60985. this._deltaPosition.copyFrom(position);
  60986. };
  60987. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  60988. if (!this._deltaRotation) {
  60989. this._deltaRotation = new BABYLON.Quaternion();
  60990. }
  60991. this._deltaRotation.copyFrom(rotation);
  60992. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  60993. };
  60994. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  60995. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  60996. };
  60997. PhysicsImpostor.prototype.getRadius = function () {
  60998. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  60999. };
  61000. /**
  61001. * Sync a bone with this impostor
  61002. * @param bone The bone to sync to the impostor.
  61003. * @param boneMesh The mesh that the bone is influencing.
  61004. * @param jointPivot The pivot of the joint / bone in local space.
  61005. * @param distToJoint Optional distance from the impostor to the joint.
  61006. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61007. */
  61008. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  61009. var tempVec = PhysicsImpostor._tmpVecs[0];
  61010. var mesh = this.object;
  61011. if (adjustRotation) {
  61012. var tempQuat = PhysicsImpostor._tmpQuat;
  61013. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  61014. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  61015. }
  61016. else {
  61017. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  61018. }
  61019. tempVec.x = 0;
  61020. tempVec.y = 0;
  61021. tempVec.z = 0;
  61022. if (jointPivot) {
  61023. tempVec.x = jointPivot.x;
  61024. tempVec.y = jointPivot.y;
  61025. tempVec.z = jointPivot.z;
  61026. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  61027. if (distToJoint === undefined || distToJoint === null) {
  61028. distToJoint = jointPivot.length();
  61029. }
  61030. tempVec.x *= distToJoint;
  61031. tempVec.y *= distToJoint;
  61032. tempVec.z *= distToJoint;
  61033. }
  61034. if (bone.getParent()) {
  61035. tempVec.addInPlace(mesh.getAbsolutePosition());
  61036. bone.setAbsolutePosition(tempVec, boneMesh);
  61037. }
  61038. else {
  61039. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  61040. boneMesh.position.x -= tempVec.x;
  61041. boneMesh.position.y -= tempVec.y;
  61042. boneMesh.position.z -= tempVec.z;
  61043. }
  61044. };
  61045. /**
  61046. * Sync impostor to a bone
  61047. * @param bone The bone that the impostor will be synced to.
  61048. * @param boneMesh The mesh that the bone is influencing.
  61049. * @param jointPivot The pivot of the joint / bone in local space.
  61050. * @param distToJoint Optional distance from the impostor to the joint.
  61051. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61052. * @param boneAxis Optional vector3 axis the bone is aligned with
  61053. */
  61054. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  61055. var mesh = this.object;
  61056. if (adjustRotation) {
  61057. var tempQuat = PhysicsImpostor._tmpQuat;
  61058. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  61059. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  61060. }
  61061. else {
  61062. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  61063. }
  61064. var pos = PhysicsImpostor._tmpVecs[0];
  61065. var boneDir = PhysicsImpostor._tmpVecs[1];
  61066. if (!boneAxis) {
  61067. boneAxis = PhysicsImpostor._tmpVecs[2];
  61068. boneAxis.x = 0;
  61069. boneAxis.y = 1;
  61070. boneAxis.z = 0;
  61071. }
  61072. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  61073. bone.getAbsolutePositionToRef(boneMesh, pos);
  61074. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  61075. distToJoint = jointPivot.length();
  61076. }
  61077. if (distToJoint !== undefined && distToJoint !== null) {
  61078. pos.x += boneDir.x * distToJoint;
  61079. pos.y += boneDir.y * distToJoint;
  61080. pos.z += boneDir.z * distToJoint;
  61081. }
  61082. mesh.setAbsolutePosition(pos);
  61083. };
  61084. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  61085. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  61086. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61087. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  61088. //Impostor types
  61089. PhysicsImpostor.NoImpostor = 0;
  61090. PhysicsImpostor.SphereImpostor = 1;
  61091. PhysicsImpostor.BoxImpostor = 2;
  61092. PhysicsImpostor.PlaneImpostor = 3;
  61093. PhysicsImpostor.MeshImpostor = 4;
  61094. PhysicsImpostor.CylinderImpostor = 7;
  61095. PhysicsImpostor.ParticleImpostor = 8;
  61096. PhysicsImpostor.HeightmapImpostor = 9;
  61097. return PhysicsImpostor;
  61098. }());
  61099. BABYLON.PhysicsImpostor = PhysicsImpostor;
  61100. })(BABYLON || (BABYLON = {}));
  61101. //# sourceMappingURL=babylon.physicsImpostor.js.map
  61102. var BABYLON;
  61103. (function (BABYLON) {
  61104. var PhysicsEngine = (function () {
  61105. function PhysicsEngine(gravity, _physicsPlugin) {
  61106. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  61107. this._physicsPlugin = _physicsPlugin;
  61108. //new methods and parameters
  61109. this._impostors = [];
  61110. this._joints = [];
  61111. if (!this._physicsPlugin.isSupported()) {
  61112. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  61113. + "Please make sure it is included.");
  61114. }
  61115. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  61116. this.setGravity(gravity);
  61117. this.setTimeStep();
  61118. }
  61119. PhysicsEngine.prototype.setGravity = function (gravity) {
  61120. this.gravity = gravity;
  61121. this._physicsPlugin.setGravity(this.gravity);
  61122. };
  61123. /**
  61124. * Set the time step of the physics engine.
  61125. * default is 1/60.
  61126. * To slow it down, enter 1/600 for example.
  61127. * To speed it up, 1/30
  61128. * @param {number} newTimeStep the new timestep to apply to this world.
  61129. */
  61130. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  61131. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  61132. this._physicsPlugin.setTimeStep(newTimeStep);
  61133. };
  61134. /**
  61135. * Get the time step of the physics engine.
  61136. */
  61137. PhysicsEngine.prototype.getTimeStep = function () {
  61138. return this._physicsPlugin.getTimeStep();
  61139. };
  61140. PhysicsEngine.prototype.dispose = function () {
  61141. this._impostors.forEach(function (impostor) {
  61142. impostor.dispose();
  61143. });
  61144. this._physicsPlugin.dispose();
  61145. };
  61146. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  61147. return this._physicsPlugin.name;
  61148. };
  61149. /**
  61150. * Adding a new impostor for the impostor tracking.
  61151. * This will be done by the impostor itself.
  61152. * @param {PhysicsImpostor} impostor the impostor to add
  61153. */
  61154. PhysicsEngine.prototype.addImpostor = function (impostor) {
  61155. impostor.uniqueId = this._impostors.push(impostor);
  61156. //if no parent, generate the body
  61157. if (!impostor.parent) {
  61158. this._physicsPlugin.generatePhysicsBody(impostor);
  61159. }
  61160. };
  61161. /**
  61162. * Remove an impostor from the engine.
  61163. * This impostor and its mesh will not longer be updated by the physics engine.
  61164. * @param {PhysicsImpostor} impostor the impostor to remove
  61165. */
  61166. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  61167. var index = this._impostors.indexOf(impostor);
  61168. if (index > -1) {
  61169. var removed = this._impostors.splice(index, 1);
  61170. //Is it needed?
  61171. if (removed.length) {
  61172. //this will also remove it from the world.
  61173. removed[0].physicsBody = null;
  61174. }
  61175. }
  61176. };
  61177. /**
  61178. * Add a joint to the physics engine
  61179. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  61180. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  61181. * @param {PhysicsJoint} the joint that will connect both impostors.
  61182. */
  61183. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  61184. var impostorJoint = {
  61185. mainImpostor: mainImpostor,
  61186. connectedImpostor: connectedImpostor,
  61187. joint: joint
  61188. };
  61189. joint.physicsPlugin = this._physicsPlugin;
  61190. this._joints.push(impostorJoint);
  61191. this._physicsPlugin.generateJoint(impostorJoint);
  61192. };
  61193. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  61194. var matchingJoints = this._joints.filter(function (impostorJoint) {
  61195. return (impostorJoint.connectedImpostor === connectedImpostor
  61196. && impostorJoint.joint === joint
  61197. && impostorJoint.mainImpostor === mainImpostor);
  61198. });
  61199. if (matchingJoints.length) {
  61200. this._physicsPlugin.removeJoint(matchingJoints[0]);
  61201. //TODO remove it from the list as well
  61202. }
  61203. };
  61204. /**
  61205. * Called by the scene. no need to call it.
  61206. */
  61207. PhysicsEngine.prototype._step = function (delta) {
  61208. var _this = this;
  61209. //check if any mesh has no body / requires an update
  61210. this._impostors.forEach(function (impostor) {
  61211. if (impostor.isBodyInitRequired()) {
  61212. _this._physicsPlugin.generatePhysicsBody(impostor);
  61213. }
  61214. });
  61215. if (delta > 0.1) {
  61216. delta = 0.1;
  61217. }
  61218. else if (delta <= 0) {
  61219. delta = 1.0 / 60.0;
  61220. }
  61221. this._physicsPlugin.executeStep(delta, this._impostors);
  61222. };
  61223. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  61224. return this._physicsPlugin;
  61225. };
  61226. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  61227. for (var i = 0; i < this._impostors.length; ++i) {
  61228. if (this._impostors[i].object === object) {
  61229. return this._impostors[i];
  61230. }
  61231. }
  61232. };
  61233. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  61234. for (var i = 0; i < this._impostors.length; ++i) {
  61235. if (this._impostors[i].physicsBody === body) {
  61236. return this._impostors[i];
  61237. }
  61238. }
  61239. };
  61240. // Statics
  61241. PhysicsEngine.Epsilon = 0.001;
  61242. return PhysicsEngine;
  61243. }());
  61244. BABYLON.PhysicsEngine = PhysicsEngine;
  61245. })(BABYLON || (BABYLON = {}));
  61246. //# sourceMappingURL=babylon.physicsEngine.js.map
  61247. var BABYLON;
  61248. (function (BABYLON) {
  61249. var CannonJSPlugin = (function () {
  61250. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  61251. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  61252. if (iterations === void 0) { iterations = 10; }
  61253. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  61254. this.name = "CannonJSPlugin";
  61255. this._physicsMaterials = [];
  61256. this._fixedTimeStep = 1 / 60;
  61257. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  61258. this._currentCollisionGroup = 2;
  61259. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  61260. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  61261. this._tmpPosition = BABYLON.Vector3.Zero();
  61262. this._tmpQuaternion = new BABYLON.Quaternion();
  61263. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  61264. this._tmpDeltaRotation = new BABYLON.Quaternion();
  61265. this._tmpUnityRotation = new BABYLON.Quaternion();
  61266. if (!this.isSupported()) {
  61267. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  61268. return;
  61269. }
  61270. this.world = new CANNON.World();
  61271. this.world.broadphase = new CANNON.NaiveBroadphase();
  61272. this.world.solver.iterations = iterations;
  61273. }
  61274. CannonJSPlugin.prototype.setGravity = function (gravity) {
  61275. this.world.gravity.copy(gravity);
  61276. };
  61277. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  61278. this._fixedTimeStep = timeStep;
  61279. };
  61280. CannonJSPlugin.prototype.getTimeStep = function () {
  61281. return this._fixedTimeStep;
  61282. };
  61283. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  61284. // Delta is in seconds, should be provided in milliseconds
  61285. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  61286. };
  61287. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  61288. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  61289. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  61290. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  61291. };
  61292. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  61293. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  61294. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  61295. impostor.physicsBody.applyForce(impulse, worldPoint);
  61296. };
  61297. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  61298. //parent-child relationship. Does this impostor has a parent impostor?
  61299. if (impostor.parent) {
  61300. if (impostor.physicsBody) {
  61301. this.removePhysicsBody(impostor);
  61302. //TODO is that needed?
  61303. impostor.forceUpdate();
  61304. }
  61305. return;
  61306. }
  61307. //should a new body be created for this impostor?
  61308. if (impostor.isBodyInitRequired()) {
  61309. var shape = this._createShape(impostor);
  61310. //unregister events, if body is being changed
  61311. var oldBody = impostor.physicsBody;
  61312. if (oldBody) {
  61313. this.removePhysicsBody(impostor);
  61314. }
  61315. //create the body and material
  61316. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  61317. var bodyCreationObject = {
  61318. mass: impostor.getParam("mass"),
  61319. material: material
  61320. };
  61321. // A simple extend, in case native options were used.
  61322. var nativeOptions = impostor.getParam("nativeOptions");
  61323. for (var key in nativeOptions) {
  61324. if (nativeOptions.hasOwnProperty(key)) {
  61325. bodyCreationObject[key] = nativeOptions[key];
  61326. }
  61327. }
  61328. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  61329. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  61330. this.world.addEventListener("preStep", impostor.beforeStep);
  61331. this.world.addEventListener("postStep", impostor.afterStep);
  61332. impostor.physicsBody.addShape(shape);
  61333. this.world.add(impostor.physicsBody);
  61334. //try to keep the body moving in the right direction by taking old properties.
  61335. //Should be tested!
  61336. if (oldBody) {
  61337. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  61338. impostor.physicsBody[param].copy(oldBody[param]);
  61339. });
  61340. }
  61341. this._processChildMeshes(impostor);
  61342. }
  61343. //now update the body's transformation
  61344. this._updatePhysicsBodyTransformation(impostor);
  61345. };
  61346. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  61347. var _this = this;
  61348. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  61349. if (meshChildren.length) {
  61350. var processMesh = function (localPosition, mesh) {
  61351. var childImpostor = mesh.getPhysicsImpostor();
  61352. if (childImpostor) {
  61353. var parent = childImpostor.parent;
  61354. if (parent !== mainImpostor) {
  61355. var localPosition = mesh.position;
  61356. if (childImpostor.physicsBody) {
  61357. _this.removePhysicsBody(childImpostor);
  61358. childImpostor.physicsBody = null;
  61359. }
  61360. childImpostor.parent = mainImpostor;
  61361. childImpostor.resetUpdateFlags();
  61362. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  61363. //Add the mass of the children.
  61364. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  61365. }
  61366. }
  61367. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  61368. };
  61369. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  61370. }
  61371. };
  61372. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  61373. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  61374. this.world.removeEventListener("preStep", impostor.beforeStep);
  61375. this.world.removeEventListener("postStep", impostor.afterStep);
  61376. this.world.remove(impostor.physicsBody);
  61377. };
  61378. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  61379. var mainBody = impostorJoint.mainImpostor.physicsBody;
  61380. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  61381. if (!mainBody || !connectedBody) {
  61382. return;
  61383. }
  61384. var constraint;
  61385. var jointData = impostorJoint.joint.jointData;
  61386. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  61387. var constraintData = {
  61388. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  61389. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  61390. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  61391. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  61392. maxForce: jointData.nativeParams.maxForce,
  61393. collideConnected: !!jointData.collision
  61394. };
  61395. switch (impostorJoint.joint.type) {
  61396. case BABYLON.PhysicsJoint.HingeJoint:
  61397. case BABYLON.PhysicsJoint.Hinge2Joint:
  61398. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  61399. break;
  61400. case BABYLON.PhysicsJoint.DistanceJoint:
  61401. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  61402. break;
  61403. case BABYLON.PhysicsJoint.SpringJoint:
  61404. var springData = jointData;
  61405. constraint = new CANNON.Spring(mainBody, connectedBody, {
  61406. restLength: springData.length,
  61407. stiffness: springData.stiffness,
  61408. damping: springData.damping,
  61409. localAnchorA: constraintData.pivotA,
  61410. localAnchorB: constraintData.pivotB
  61411. });
  61412. break;
  61413. case BABYLON.PhysicsJoint.LockJoint:
  61414. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  61415. break;
  61416. case BABYLON.PhysicsJoint.PointToPointJoint:
  61417. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  61418. default:
  61419. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  61420. break;
  61421. }
  61422. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  61423. constraint.collideConnected = !!jointData.collision;
  61424. impostorJoint.joint.physicsJoint = constraint;
  61425. //don't add spring as constraint, as it is not one.
  61426. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  61427. this.world.addConstraint(constraint);
  61428. }
  61429. else {
  61430. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  61431. constraint.applyForce();
  61432. });
  61433. }
  61434. };
  61435. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  61436. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  61437. };
  61438. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  61439. var index;
  61440. var mat;
  61441. for (index = 0; index < this._physicsMaterials.length; index++) {
  61442. mat = this._physicsMaterials[index];
  61443. if (mat.friction === friction && mat.restitution === restitution) {
  61444. return mat;
  61445. }
  61446. }
  61447. var currentMat = new CANNON.Material(name);
  61448. currentMat.friction = friction;
  61449. currentMat.restitution = restitution;
  61450. this._physicsMaterials.push(currentMat);
  61451. return currentMat;
  61452. };
  61453. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  61454. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  61455. };
  61456. CannonJSPlugin.prototype._createShape = function (impostor) {
  61457. var object = impostor.object;
  61458. var returnValue;
  61459. var extendSize = impostor.getObjectExtendSize();
  61460. switch (impostor.type) {
  61461. case BABYLON.PhysicsImpostor.SphereImpostor:
  61462. var radiusX = extendSize.x;
  61463. var radiusY = extendSize.y;
  61464. var radiusZ = extendSize.z;
  61465. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  61466. break;
  61467. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  61468. case BABYLON.PhysicsImpostor.CylinderImpostor:
  61469. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  61470. break;
  61471. case BABYLON.PhysicsImpostor.BoxImpostor:
  61472. var box = extendSize.scale(0.5);
  61473. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  61474. break;
  61475. case BABYLON.PhysicsImpostor.PlaneImpostor:
  61476. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  61477. returnValue = new CANNON.Plane();
  61478. break;
  61479. case BABYLON.PhysicsImpostor.MeshImpostor:
  61480. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  61481. var rawFaces = object.getIndices ? object.getIndices() : [];
  61482. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  61483. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  61484. break;
  61485. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  61486. returnValue = this._createHeightmap(object);
  61487. break;
  61488. case BABYLON.PhysicsImpostor.ParticleImpostor:
  61489. returnValue = new CANNON.Particle();
  61490. break;
  61491. }
  61492. return returnValue;
  61493. };
  61494. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  61495. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61496. var matrix = [];
  61497. //For now pointDepth will not be used and will be automatically calculated.
  61498. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  61499. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  61500. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  61501. var elementSize = dim * 2 / arraySize;
  61502. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  61503. for (var i = 0; i < pos.length; i = i + 3) {
  61504. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  61505. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  61506. var y = pos[i + 1] + minY;
  61507. if (!matrix[x]) {
  61508. matrix[x] = [];
  61509. }
  61510. if (!matrix[x][z]) {
  61511. matrix[x][z] = y;
  61512. }
  61513. matrix[x][z] = Math.max(y, matrix[x][z]);
  61514. }
  61515. for (var x = 0; x <= arraySize; ++x) {
  61516. if (!matrix[x]) {
  61517. var loc = 1;
  61518. while (!matrix[(x + loc) % arraySize]) {
  61519. loc++;
  61520. }
  61521. matrix[x] = matrix[(x + loc) % arraySize].slice();
  61522. //console.log("missing x", x);
  61523. }
  61524. for (var z = 0; z <= arraySize; ++z) {
  61525. if (!matrix[x][z]) {
  61526. var loc = 1;
  61527. var newValue;
  61528. while (newValue === undefined) {
  61529. newValue = matrix[x][(z + loc++) % arraySize];
  61530. }
  61531. matrix[x][z] = newValue;
  61532. }
  61533. }
  61534. }
  61535. var shape = new CANNON.Heightfield(matrix, {
  61536. elementSize: elementSize
  61537. });
  61538. //For future reference, needed for body transformation
  61539. shape.minY = minY;
  61540. return shape;
  61541. };
  61542. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  61543. var object = impostor.object;
  61544. //make sure it is updated...
  61545. object.computeWorldMatrix && object.computeWorldMatrix(true);
  61546. // The delta between the mesh position and the mesh bounding box center
  61547. var center = impostor.getObjectCenter();
  61548. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  61549. this._tmpPosition.copyFrom(center);
  61550. var quaternion = object.rotationQuaternion;
  61551. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  61552. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  61553. //-90 DEG in X, precalculated
  61554. quaternion = quaternion.multiply(this._minus90X);
  61555. //Invert! (Precalculated, 90 deg in X)
  61556. //No need to clone. this will never change.
  61557. impostor.setDeltaRotation(this._plus90X);
  61558. }
  61559. //If it is a heightfield, if should be centered.
  61560. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  61561. var mesh = object;
  61562. //calculate the correct body position:
  61563. var rotationQuaternion = mesh.rotationQuaternion;
  61564. mesh.rotationQuaternion = this._tmpUnityRotation;
  61565. mesh.computeWorldMatrix(true);
  61566. //get original center with no rotation
  61567. var c = center.clone();
  61568. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  61569. //rotation is back
  61570. mesh.rotationQuaternion = rotationQuaternion;
  61571. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  61572. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  61573. mesh.setPivotMatrix(p);
  61574. mesh.computeWorldMatrix(true);
  61575. //calculate the translation
  61576. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  61577. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  61578. //add it inverted to the delta
  61579. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  61580. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  61581. mesh.setPivotMatrix(oldPivot);
  61582. mesh.computeWorldMatrix(true);
  61583. }
  61584. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  61585. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  61586. this._tmpPosition.copyFrom(object.position);
  61587. }
  61588. impostor.setDeltaPosition(this._tmpDeltaPosition);
  61589. //Now update the impostor object
  61590. impostor.physicsBody.position.copy(this._tmpPosition);
  61591. impostor.physicsBody.quaternion.copy(quaternion);
  61592. };
  61593. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  61594. impostor.object.position.copyFrom(impostor.physicsBody.position);
  61595. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  61596. };
  61597. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  61598. impostor.physicsBody.position.copy(newPosition);
  61599. impostor.physicsBody.quaternion.copy(newRotation);
  61600. };
  61601. CannonJSPlugin.prototype.isSupported = function () {
  61602. return window.CANNON !== undefined;
  61603. };
  61604. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  61605. impostor.physicsBody.velocity.copy(velocity);
  61606. };
  61607. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  61608. impostor.physicsBody.angularVelocity.copy(velocity);
  61609. };
  61610. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  61611. var v = impostor.physicsBody.velocity;
  61612. if (!v)
  61613. return null;
  61614. return new BABYLON.Vector3(v.x, v.y, v.z);
  61615. };
  61616. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  61617. var v = impostor.physicsBody.angularVelocity;
  61618. if (!v)
  61619. return null;
  61620. return new BABYLON.Vector3(v.x, v.y, v.z);
  61621. };
  61622. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  61623. impostor.physicsBody.mass = mass;
  61624. impostor.physicsBody.updateMassProperties();
  61625. };
  61626. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  61627. return impostor.physicsBody.mass;
  61628. };
  61629. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  61630. return impostor.physicsBody.material.friction;
  61631. };
  61632. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  61633. impostor.physicsBody.material.friction = friction;
  61634. };
  61635. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  61636. return impostor.physicsBody.material.restitution;
  61637. };
  61638. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  61639. impostor.physicsBody.material.restitution = restitution;
  61640. };
  61641. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  61642. impostor.physicsBody.sleep();
  61643. };
  61644. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  61645. impostor.physicsBody.wakeUp();
  61646. };
  61647. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  61648. joint.physicsJoint.distance = maxDistance;
  61649. };
  61650. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  61651. if (!motorIndex) {
  61652. joint.physicsJoint.enableMotor();
  61653. }
  61654. };
  61655. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  61656. if (!motorIndex) {
  61657. joint.physicsJoint.disableMotor();
  61658. }
  61659. };
  61660. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  61661. if (!motorIndex) {
  61662. joint.physicsJoint.enableMotor();
  61663. joint.physicsJoint.setMotorSpeed(speed);
  61664. if (maxForce) {
  61665. this.setLimit(joint, maxForce);
  61666. }
  61667. }
  61668. };
  61669. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  61670. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  61671. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  61672. };
  61673. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  61674. var body = impostor.physicsBody;
  61675. mesh.position.x = body.position.x;
  61676. mesh.position.y = body.position.y;
  61677. mesh.position.z = body.position.z;
  61678. mesh.rotationQuaternion.x = body.quaternion.x;
  61679. mesh.rotationQuaternion.y = body.quaternion.y;
  61680. mesh.rotationQuaternion.z = body.quaternion.z;
  61681. mesh.rotationQuaternion.w = body.quaternion.w;
  61682. };
  61683. CannonJSPlugin.prototype.getRadius = function (impostor) {
  61684. var shape = impostor.physicsBody.shapes[0];
  61685. return shape.boundingSphereRadius;
  61686. };
  61687. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  61688. var shape = impostor.physicsBody.shapes[0];
  61689. result.x = shape.halfExtents.x * 2;
  61690. result.y = shape.halfExtents.y * 2;
  61691. result.z = shape.halfExtents.z * 2;
  61692. };
  61693. CannonJSPlugin.prototype.dispose = function () {
  61694. };
  61695. return CannonJSPlugin;
  61696. }());
  61697. BABYLON.CannonJSPlugin = CannonJSPlugin;
  61698. })(BABYLON || (BABYLON = {}));
  61699. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  61700. var BABYLON;
  61701. (function (BABYLON) {
  61702. var OimoJSPlugin = (function () {
  61703. function OimoJSPlugin(iterations) {
  61704. this.name = "OimoJSPlugin";
  61705. this._tmpImpostorsArray = [];
  61706. this._tmpPositionVector = BABYLON.Vector3.Zero();
  61707. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  61708. this.world.worldscale(1);
  61709. this.world.clear();
  61710. //making sure no stats are calculated
  61711. this.world.isNoStat = true;
  61712. }
  61713. OimoJSPlugin.prototype.setGravity = function (gravity) {
  61714. this.world.gravity.copy(gravity);
  61715. };
  61716. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  61717. this.world.timeStep = timeStep;
  61718. };
  61719. OimoJSPlugin.prototype.getTimeStep = function () {
  61720. return this.world.timeStep;
  61721. };
  61722. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  61723. var _this = this;
  61724. impostors.forEach(function (impostor) {
  61725. impostor.beforeStep();
  61726. });
  61727. this.world.step();
  61728. impostors.forEach(function (impostor) {
  61729. impostor.afterStep();
  61730. //update the ordered impostors array
  61731. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  61732. });
  61733. //check for collisions
  61734. var contact = this.world.contacts;
  61735. while (contact !== null) {
  61736. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  61737. contact = contact.next;
  61738. continue;
  61739. }
  61740. //is this body colliding with any other? get the impostor
  61741. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  61742. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  61743. if (!mainImpostor || !collidingImpostor) {
  61744. contact = contact.next;
  61745. continue;
  61746. }
  61747. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  61748. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  61749. contact = contact.next;
  61750. }
  61751. };
  61752. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  61753. var mass = impostor.physicsBody.massInfo.mass;
  61754. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  61755. };
  61756. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  61757. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  61758. this.applyImpulse(impostor, force, contactPoint);
  61759. };
  61760. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  61761. var _this = this;
  61762. //parent-child relationship. Does this impostor has a parent impostor?
  61763. if (impostor.parent) {
  61764. if (impostor.physicsBody) {
  61765. this.removePhysicsBody(impostor);
  61766. //TODO is that needed?
  61767. impostor.forceUpdate();
  61768. }
  61769. return;
  61770. }
  61771. if (impostor.isBodyInitRequired()) {
  61772. var bodyConfig = {
  61773. name: impostor.uniqueId,
  61774. //Oimo must have mass, also for static objects.
  61775. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  61776. size: [],
  61777. type: [],
  61778. pos: [],
  61779. rot: [],
  61780. move: impostor.getParam("mass") !== 0,
  61781. //Supporting older versions of Oimo
  61782. world: this.world
  61783. };
  61784. var impostors = [impostor];
  61785. var addToArray = function (parent) {
  61786. if (!parent.getChildMeshes)
  61787. return;
  61788. parent.getChildMeshes().forEach(function (m) {
  61789. if (m.physicsImpostor) {
  61790. impostors.push(m.physicsImpostor);
  61791. m.physicsImpostor._init();
  61792. }
  61793. });
  61794. };
  61795. addToArray(impostor.object);
  61796. var checkWithEpsilon_1 = function (value) {
  61797. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  61798. };
  61799. impostors.forEach(function (i) {
  61800. //get the correct bounding box
  61801. var oldQuaternion = i.object.rotationQuaternion;
  61802. var rot = new OIMO.Euler().setFromQuaternion({
  61803. x: impostor.object.rotationQuaternion.x,
  61804. y: impostor.object.rotationQuaternion.y,
  61805. z: impostor.object.rotationQuaternion.z,
  61806. s: impostor.object.rotationQuaternion.w
  61807. });
  61808. var extendSize = i.getObjectExtendSize();
  61809. if (i === impostor) {
  61810. var center = impostor.getObjectCenter();
  61811. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  61812. //Can also use Array.prototype.push.apply
  61813. bodyConfig.pos.push(center.x);
  61814. bodyConfig.pos.push(center.y);
  61815. bodyConfig.pos.push(center.z);
  61816. //tmp solution
  61817. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  61818. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  61819. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  61820. }
  61821. else {
  61822. bodyConfig.pos.push(i.object.position.x);
  61823. bodyConfig.pos.push(i.object.position.y);
  61824. bodyConfig.pos.push(i.object.position.z);
  61825. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  61826. bodyConfig.rot.push(0);
  61827. bodyConfig.rot.push(0);
  61828. bodyConfig.rot.push(0);
  61829. }
  61830. // register mesh
  61831. switch (i.type) {
  61832. case BABYLON.PhysicsImpostor.ParticleImpostor:
  61833. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  61834. case BABYLON.PhysicsImpostor.SphereImpostor:
  61835. var radiusX = extendSize.x;
  61836. var radiusY = extendSize.y;
  61837. var radiusZ = extendSize.z;
  61838. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  61839. bodyConfig.type.push('sphere');
  61840. //due to the way oimo works with compounds, add 3 times
  61841. bodyConfig.size.push(size);
  61842. bodyConfig.size.push(size);
  61843. bodyConfig.size.push(size);
  61844. break;
  61845. case BABYLON.PhysicsImpostor.CylinderImpostor:
  61846. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  61847. var sizeY = checkWithEpsilon_1(extendSize.y);
  61848. bodyConfig.type.push('cylinder');
  61849. bodyConfig.size.push(sizeX);
  61850. bodyConfig.size.push(sizeY);
  61851. //due to the way oimo works with compounds, add one more value.
  61852. bodyConfig.size.push(sizeY);
  61853. break;
  61854. case BABYLON.PhysicsImpostor.PlaneImpostor:
  61855. case BABYLON.PhysicsImpostor.BoxImpostor:
  61856. default:
  61857. var sizeX = checkWithEpsilon_1(extendSize.x);
  61858. var sizeY = checkWithEpsilon_1(extendSize.y);
  61859. var sizeZ = checkWithEpsilon_1(extendSize.z);
  61860. bodyConfig.type.push('box');
  61861. bodyConfig.size.push(sizeX);
  61862. bodyConfig.size.push(sizeY);
  61863. bodyConfig.size.push(sizeZ);
  61864. break;
  61865. }
  61866. //actually not needed, but hey...
  61867. i.object.rotationQuaternion = oldQuaternion;
  61868. });
  61869. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  61870. }
  61871. else {
  61872. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  61873. }
  61874. impostor.setDeltaPosition(this._tmpPositionVector);
  61875. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  61876. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  61877. };
  61878. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  61879. //impostor.physicsBody.dispose();
  61880. //Same as : (older oimo versions)
  61881. this.world.removeRigidBody(impostor.physicsBody);
  61882. };
  61883. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  61884. var mainBody = impostorJoint.mainImpostor.physicsBody;
  61885. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  61886. if (!mainBody || !connectedBody) {
  61887. return;
  61888. }
  61889. var jointData = impostorJoint.joint.jointData;
  61890. var options = jointData.nativeParams || {};
  61891. var type;
  61892. var nativeJointData = {
  61893. body1: mainBody,
  61894. body2: connectedBody,
  61895. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  61896. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  61897. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  61898. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  61899. min: options.min,
  61900. max: options.max,
  61901. collision: options.collision || jointData.collision,
  61902. spring: options.spring,
  61903. //supporting older version of Oimo
  61904. world: this.world
  61905. };
  61906. switch (impostorJoint.joint.type) {
  61907. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  61908. type = "jointBall";
  61909. break;
  61910. case BABYLON.PhysicsJoint.SpringJoint:
  61911. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  61912. var springData = jointData;
  61913. nativeJointData.min = springData.length || nativeJointData.min;
  61914. //Max should also be set, just make sure it is at least min
  61915. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  61916. case BABYLON.PhysicsJoint.DistanceJoint:
  61917. type = "jointDistance";
  61918. nativeJointData.max = jointData.maxDistance;
  61919. break;
  61920. case BABYLON.PhysicsJoint.PrismaticJoint:
  61921. type = "jointPrisme";
  61922. break;
  61923. case BABYLON.PhysicsJoint.SliderJoint:
  61924. type = "jointSlide";
  61925. break;
  61926. case BABYLON.PhysicsJoint.WheelJoint:
  61927. type = "jointWheel";
  61928. break;
  61929. case BABYLON.PhysicsJoint.HingeJoint:
  61930. default:
  61931. type = "jointHinge";
  61932. break;
  61933. }
  61934. nativeJointData.type = type;
  61935. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  61936. };
  61937. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  61938. //Bug in Oimo prevents us from disposing a joint in the playground
  61939. //joint.joint.physicsJoint.dispose();
  61940. //So we will bruteforce it!
  61941. try {
  61942. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  61943. }
  61944. catch (e) {
  61945. BABYLON.Tools.Warn(e);
  61946. }
  61947. };
  61948. OimoJSPlugin.prototype.isSupported = function () {
  61949. return OIMO !== undefined;
  61950. };
  61951. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  61952. if (!impostor.physicsBody.sleeping) {
  61953. //TODO check that
  61954. if (impostor.physicsBody.shapes.next) {
  61955. var parentShape = this._getLastShape(impostor.physicsBody);
  61956. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  61957. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  61958. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  61959. }
  61960. else {
  61961. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  61962. }
  61963. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  61964. impostor.object.rotationQuaternion.normalize();
  61965. }
  61966. };
  61967. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  61968. var body = impostor.physicsBody;
  61969. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  61970. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  61971. body.syncShapes();
  61972. body.awake();
  61973. };
  61974. OimoJSPlugin.prototype._getLastShape = function (body) {
  61975. var lastShape = body.shapes;
  61976. while (lastShape.next) {
  61977. lastShape = lastShape.next;
  61978. }
  61979. return lastShape;
  61980. };
  61981. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  61982. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  61983. };
  61984. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  61985. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  61986. };
  61987. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  61988. var v = impostor.physicsBody.linearVelocity;
  61989. if (!v)
  61990. return null;
  61991. return new BABYLON.Vector3(v.x, v.y, v.z);
  61992. };
  61993. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  61994. var v = impostor.physicsBody.angularVelocity;
  61995. if (!v)
  61996. return null;
  61997. return new BABYLON.Vector3(v.x, v.y, v.z);
  61998. };
  61999. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62000. var staticBody = mass === 0;
  62001. //this will actually set the body's density and not its mass.
  62002. //But this is how oimo treats the mass variable.
  62003. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  62004. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  62005. };
  62006. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  62007. return impostor.physicsBody.shapes.density;
  62008. };
  62009. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  62010. return impostor.physicsBody.shapes.friction;
  62011. };
  62012. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62013. impostor.physicsBody.shapes.friction = friction;
  62014. };
  62015. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62016. return impostor.physicsBody.shapes.restitution;
  62017. };
  62018. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62019. impostor.physicsBody.shapes.restitution = restitution;
  62020. };
  62021. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  62022. impostor.physicsBody.sleep();
  62023. };
  62024. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  62025. impostor.physicsBody.awake();
  62026. };
  62027. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62028. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  62029. if (minDistance !== void 0) {
  62030. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  62031. }
  62032. };
  62033. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62034. //TODO separate rotational and transational motors.
  62035. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62036. if (motor) {
  62037. motor.setMotor(speed, maxForce);
  62038. }
  62039. };
  62040. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  62041. //TODO separate rotational and transational motors.
  62042. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62043. if (motor) {
  62044. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  62045. }
  62046. };
  62047. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62048. var body = impostor.physicsBody;
  62049. mesh.position.x = body.position.x;
  62050. mesh.position.y = body.position.y;
  62051. mesh.position.z = body.position.z;
  62052. mesh.rotationQuaternion.x = body.orientation.x;
  62053. mesh.rotationQuaternion.y = body.orientation.y;
  62054. mesh.rotationQuaternion.z = body.orientation.z;
  62055. mesh.rotationQuaternion.w = body.orientation.s;
  62056. };
  62057. OimoJSPlugin.prototype.getRadius = function (impostor) {
  62058. return impostor.physicsBody.shapes.radius;
  62059. };
  62060. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62061. var shape = impostor.physicsBody.shapes;
  62062. result.x = shape.halfWidth * 2;
  62063. result.y = shape.halfHeight * 2;
  62064. result.z = shape.halfDepth * 2;
  62065. };
  62066. OimoJSPlugin.prototype.dispose = function () {
  62067. this.world.clear();
  62068. };
  62069. return OimoJSPlugin;
  62070. }());
  62071. BABYLON.OimoJSPlugin = OimoJSPlugin;
  62072. })(BABYLON || (BABYLON = {}));
  62073. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  62074. var BABYLON;
  62075. (function (BABYLON) {
  62076. var Internals;
  62077. (function (Internals) {
  62078. /*
  62079. * Based on jsTGALoader - Javascript loader for TGA file
  62080. * By Vincent Thibault
  62081. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  62082. */
  62083. var TGATools = (function () {
  62084. function TGATools() {
  62085. }
  62086. TGATools.GetTGAHeader = function (data) {
  62087. var offset = 0;
  62088. var header = {
  62089. id_length: data[offset++],
  62090. colormap_type: data[offset++],
  62091. image_type: data[offset++],
  62092. colormap_index: data[offset++] | data[offset++] << 8,
  62093. colormap_length: data[offset++] | data[offset++] << 8,
  62094. colormap_size: data[offset++],
  62095. origin: [
  62096. data[offset++] | data[offset++] << 8,
  62097. data[offset++] | data[offset++] << 8
  62098. ],
  62099. width: data[offset++] | data[offset++] << 8,
  62100. height: data[offset++] | data[offset++] << 8,
  62101. pixel_size: data[offset++],
  62102. flags: data[offset++]
  62103. };
  62104. return header;
  62105. };
  62106. TGATools.UploadContent = function (gl, data) {
  62107. // Not enough data to contain header ?
  62108. if (data.length < 19) {
  62109. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  62110. return;
  62111. }
  62112. // Read Header
  62113. var offset = 18;
  62114. var header = TGATools.GetTGAHeader(data);
  62115. // Assume it's a valid Targa file.
  62116. if (header.id_length + offset > data.length) {
  62117. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  62118. return;
  62119. }
  62120. // Skip not needed data
  62121. offset += header.id_length;
  62122. var use_rle = false;
  62123. var use_pal = false;
  62124. var use_rgb = false;
  62125. var use_grey = false;
  62126. // Get some informations.
  62127. switch (header.image_type) {
  62128. case TGATools._TYPE_RLE_INDEXED:
  62129. use_rle = true;
  62130. case TGATools._TYPE_INDEXED:
  62131. use_pal = true;
  62132. break;
  62133. case TGATools._TYPE_RLE_RGB:
  62134. use_rle = true;
  62135. case TGATools._TYPE_RGB:
  62136. use_rgb = true;
  62137. break;
  62138. case TGATools._TYPE_RLE_GREY:
  62139. use_rle = true;
  62140. case TGATools._TYPE_GREY:
  62141. use_grey = true;
  62142. break;
  62143. }
  62144. var pixel_data;
  62145. var numAlphaBits = header.flags & 0xf;
  62146. var pixel_size = header.pixel_size >> 3;
  62147. var pixel_total = header.width * header.height * pixel_size;
  62148. // Read palettes
  62149. var palettes;
  62150. if (use_pal) {
  62151. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  62152. }
  62153. // Read LRE
  62154. if (use_rle) {
  62155. pixel_data = new Uint8Array(pixel_total);
  62156. var c, count, i;
  62157. var localOffset = 0;
  62158. var pixels = new Uint8Array(pixel_size);
  62159. while (offset < pixel_total && localOffset < pixel_total) {
  62160. c = data[offset++];
  62161. count = (c & 0x7f) + 1;
  62162. // RLE pixels
  62163. if (c & 0x80) {
  62164. // Bind pixel tmp array
  62165. for (i = 0; i < pixel_size; ++i) {
  62166. pixels[i] = data[offset++];
  62167. }
  62168. // Copy pixel array
  62169. for (i = 0; i < count; ++i) {
  62170. pixel_data.set(pixels, localOffset + i * pixel_size);
  62171. }
  62172. localOffset += pixel_size * count;
  62173. }
  62174. else {
  62175. count *= pixel_size;
  62176. for (i = 0; i < count; ++i) {
  62177. pixel_data[localOffset + i] = data[offset++];
  62178. }
  62179. localOffset += count;
  62180. }
  62181. }
  62182. }
  62183. else {
  62184. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  62185. }
  62186. // Load to texture
  62187. var x_start, y_start, x_step, y_step, y_end, x_end;
  62188. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  62189. default:
  62190. case TGATools._ORIGIN_UL:
  62191. x_start = 0;
  62192. x_step = 1;
  62193. x_end = header.width;
  62194. y_start = 0;
  62195. y_step = 1;
  62196. y_end = header.height;
  62197. break;
  62198. case TGATools._ORIGIN_BL:
  62199. x_start = 0;
  62200. x_step = 1;
  62201. x_end = header.width;
  62202. y_start = header.height - 1;
  62203. y_step = -1;
  62204. y_end = -1;
  62205. break;
  62206. case TGATools._ORIGIN_UR:
  62207. x_start = header.width - 1;
  62208. x_step = -1;
  62209. x_end = -1;
  62210. y_start = 0;
  62211. y_step = 1;
  62212. y_end = header.height;
  62213. break;
  62214. case TGATools._ORIGIN_BR:
  62215. x_start = header.width - 1;
  62216. x_step = -1;
  62217. x_end = -1;
  62218. y_start = header.height - 1;
  62219. y_step = -1;
  62220. y_end = -1;
  62221. break;
  62222. }
  62223. // Load the specify method
  62224. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  62225. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  62226. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  62227. };
  62228. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62229. var image = pixel_data, colormap = palettes;
  62230. var width = header.width, height = header.height;
  62231. var color, i = 0, x, y;
  62232. var imageData = new Uint8Array(width * height * 4);
  62233. for (y = y_start; y !== y_end; y += y_step) {
  62234. for (x = x_start; x !== x_end; x += x_step, i++) {
  62235. color = image[i];
  62236. imageData[(x + width * y) * 4 + 3] = 255;
  62237. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  62238. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  62239. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  62240. }
  62241. }
  62242. return imageData;
  62243. };
  62244. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62245. var image = pixel_data;
  62246. var width = header.width, height = header.height;
  62247. var color, i = 0, x, y;
  62248. var imageData = new Uint8Array(width * height * 4);
  62249. for (y = y_start; y !== y_end; y += y_step) {
  62250. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  62251. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  62252. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  62253. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  62254. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  62255. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  62256. }
  62257. }
  62258. return imageData;
  62259. };
  62260. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62261. var image = pixel_data;
  62262. var width = header.width, height = header.height;
  62263. var i = 0, x, y;
  62264. var imageData = new Uint8Array(width * height * 4);
  62265. for (y = y_start; y !== y_end; y += y_step) {
  62266. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  62267. imageData[(x + width * y) * 4 + 3] = 255;
  62268. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  62269. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  62270. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  62271. }
  62272. }
  62273. return imageData;
  62274. };
  62275. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62276. var image = pixel_data;
  62277. var width = header.width, height = header.height;
  62278. var i = 0, x, y;
  62279. var imageData = new Uint8Array(width * height * 4);
  62280. for (y = y_start; y !== y_end; y += y_step) {
  62281. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  62282. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  62283. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  62284. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  62285. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  62286. }
  62287. }
  62288. return imageData;
  62289. };
  62290. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62291. var image = pixel_data;
  62292. var width = header.width, height = header.height;
  62293. var color, i = 0, x, y;
  62294. var imageData = new Uint8Array(width * height * 4);
  62295. for (y = y_start; y !== y_end; y += y_step) {
  62296. for (x = x_start; x !== x_end; x += x_step, i++) {
  62297. color = image[i];
  62298. imageData[(x + width * y) * 4 + 0] = color;
  62299. imageData[(x + width * y) * 4 + 1] = color;
  62300. imageData[(x + width * y) * 4 + 2] = color;
  62301. imageData[(x + width * y) * 4 + 3] = 255;
  62302. }
  62303. }
  62304. return imageData;
  62305. };
  62306. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62307. var image = pixel_data;
  62308. var width = header.width, height = header.height;
  62309. var i = 0, x, y;
  62310. var imageData = new Uint8Array(width * height * 4);
  62311. for (y = y_start; y !== y_end; y += y_step) {
  62312. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  62313. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  62314. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  62315. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  62316. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  62317. }
  62318. }
  62319. return imageData;
  62320. };
  62321. TGATools._TYPE_NO_DATA = 0;
  62322. TGATools._TYPE_INDEXED = 1;
  62323. TGATools._TYPE_RGB = 2;
  62324. TGATools._TYPE_GREY = 3;
  62325. TGATools._TYPE_RLE_INDEXED = 9;
  62326. TGATools._TYPE_RLE_RGB = 10;
  62327. TGATools._TYPE_RLE_GREY = 11;
  62328. TGATools._ORIGIN_MASK = 0x30;
  62329. TGATools._ORIGIN_SHIFT = 0x04;
  62330. TGATools._ORIGIN_BL = 0x00;
  62331. TGATools._ORIGIN_BR = 0x01;
  62332. TGATools._ORIGIN_UL = 0x02;
  62333. TGATools._ORIGIN_UR = 0x03;
  62334. return TGATools;
  62335. }());
  62336. Internals.TGATools = TGATools;
  62337. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62338. })(BABYLON || (BABYLON = {}));
  62339. //# sourceMappingURL=babylon.tga.js.map
  62340. var BABYLON;
  62341. (function (BABYLON) {
  62342. var Internals;
  62343. (function (Internals) {
  62344. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  62345. // All values and structures referenced from:
  62346. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  62347. var DDS_MAGIC = 0x20534444;
  62348. 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;
  62349. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  62350. 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;
  62351. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  62352. function FourCCToInt32(value) {
  62353. return value.charCodeAt(0) +
  62354. (value.charCodeAt(1) << 8) +
  62355. (value.charCodeAt(2) << 16) +
  62356. (value.charCodeAt(3) << 24);
  62357. }
  62358. function Int32ToFourCC(value) {
  62359. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  62360. }
  62361. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  62362. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  62363. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  62364. var FOURCC_DX10 = FourCCToInt32("DX10");
  62365. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  62366. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  62367. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  62368. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  62369. var headerLengthInt = 31; // The header length in 32 bit ints
  62370. // Offsets into the header array
  62371. var off_magic = 0;
  62372. var off_size = 1;
  62373. var off_flags = 2;
  62374. var off_height = 3;
  62375. var off_width = 4;
  62376. var off_mipmapCount = 7;
  62377. var off_pfFlags = 20;
  62378. var off_pfFourCC = 21;
  62379. var off_RGBbpp = 22;
  62380. var off_RMask = 23;
  62381. var off_GMask = 24;
  62382. var off_BMask = 25;
  62383. var off_AMask = 26;
  62384. var off_caps1 = 27;
  62385. var off_caps2 = 28;
  62386. var off_caps3 = 29;
  62387. var off_caps4 = 30;
  62388. var off_dxgiFormat = 32;
  62389. ;
  62390. var DDSTools = (function () {
  62391. function DDSTools() {
  62392. }
  62393. DDSTools.GetDDSInfo = function (arrayBuffer) {
  62394. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  62395. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  62396. var mipmapCount = 1;
  62397. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  62398. mipmapCount = Math.max(1, header[off_mipmapCount]);
  62399. }
  62400. var fourCC = header[off_pfFourCC];
  62401. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  62402. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62403. switch (fourCC) {
  62404. case FOURCC_D3DFMT_R16G16B16A16F:
  62405. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62406. break;
  62407. case FOURCC_D3DFMT_R32G32B32A32F:
  62408. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62409. break;
  62410. case FOURCC_DX10:
  62411. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  62412. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62413. break;
  62414. }
  62415. }
  62416. return {
  62417. width: header[off_width],
  62418. height: header[off_height],
  62419. mipmapCount: mipmapCount,
  62420. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  62421. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  62422. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  62423. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  62424. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  62425. dxgiFormat: dxgiFormat,
  62426. textureType: textureType
  62427. };
  62428. };
  62429. DDSTools._ToHalfFloat = function (value) {
  62430. if (!DDSTools._FloatView) {
  62431. DDSTools._FloatView = new Float32Array(1);
  62432. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  62433. }
  62434. DDSTools._FloatView[0] = value;
  62435. var x = DDSTools._Int32View[0];
  62436. var bits = (x >> 16) & 0x8000; /* Get the sign */
  62437. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  62438. var e = (x >> 23) & 0xff; /* Using int is faster here */
  62439. /* If zero, or denormal, or exponent underflows too much for a denormal
  62440. * half, return signed zero. */
  62441. if (e < 103) {
  62442. return bits;
  62443. }
  62444. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  62445. if (e > 142) {
  62446. bits |= 0x7c00;
  62447. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  62448. * not Inf, so make sure we set one mantissa bit too. */
  62449. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  62450. return bits;
  62451. }
  62452. /* If exponent underflows but not too much, return a denormal */
  62453. if (e < 113) {
  62454. m |= 0x0800;
  62455. /* Extra rounding may overflow and set mantissa to 0 and exponent
  62456. * to 1, which is OK. */
  62457. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  62458. return bits;
  62459. }
  62460. bits |= ((e - 112) << 10) | (m >> 1);
  62461. bits += m & 1;
  62462. return bits;
  62463. };
  62464. DDSTools._FromHalfFloat = function (value) {
  62465. var s = (value & 0x8000) >> 15;
  62466. var e = (value & 0x7C00) >> 10;
  62467. var f = value & 0x03FF;
  62468. if (e === 0) {
  62469. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  62470. }
  62471. else if (e == 0x1F) {
  62472. return f ? NaN : ((s ? -1 : 1) * Infinity);
  62473. }
  62474. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  62475. };
  62476. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62477. var destArray = new Float32Array(dataLength);
  62478. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62479. var index = 0;
  62480. for (var y = 0; y < height; y++) {
  62481. for (var x = 0; x < width; x++) {
  62482. var srcPos = (x + y * width) * 4;
  62483. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  62484. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  62485. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  62486. if (DDSTools.StoreLODInAlphaChannel) {
  62487. destArray[index + 3] = lod;
  62488. }
  62489. else {
  62490. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  62491. }
  62492. index += 4;
  62493. }
  62494. }
  62495. return destArray;
  62496. };
  62497. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62498. if (DDSTools.StoreLODInAlphaChannel) {
  62499. var destArray = new Uint16Array(dataLength);
  62500. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62501. var index = 0;
  62502. for (var y = 0; y < height; y++) {
  62503. for (var x = 0; x < width; x++) {
  62504. var srcPos = (x + y * width) * 4;
  62505. destArray[index] = srcData[srcPos];
  62506. destArray[index + 1] = srcData[srcPos + 1];
  62507. destArray[index + 2] = srcData[srcPos + 2];
  62508. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  62509. index += 4;
  62510. }
  62511. }
  62512. return destArray;
  62513. }
  62514. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  62515. };
  62516. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62517. if (DDSTools.StoreLODInAlphaChannel) {
  62518. var destArray = new Float32Array(dataLength);
  62519. var srcData = new Float32Array(arrayBuffer, dataOffset);
  62520. var index = 0;
  62521. for (var y = 0; y < height; y++) {
  62522. for (var x = 0; x < width; x++) {
  62523. var srcPos = (x + y * width) * 4;
  62524. destArray[index] = srcData[srcPos];
  62525. destArray[index + 1] = srcData[srcPos + 1];
  62526. destArray[index + 2] = srcData[srcPos + 2];
  62527. destArray[index + 3] = lod;
  62528. index += 4;
  62529. }
  62530. }
  62531. return destArray;
  62532. }
  62533. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  62534. };
  62535. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62536. var destArray = new Uint8Array(dataLength);
  62537. var srcData = new Float32Array(arrayBuffer, dataOffset);
  62538. var index = 0;
  62539. for (var y = 0; y < height; y++) {
  62540. for (var x = 0; x < width; x++) {
  62541. var srcPos = (x + y * width) * 4;
  62542. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  62543. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  62544. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  62545. if (DDSTools.StoreLODInAlphaChannel) {
  62546. destArray[index + 3] = lod;
  62547. }
  62548. else {
  62549. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  62550. }
  62551. index += 4;
  62552. }
  62553. }
  62554. return destArray;
  62555. };
  62556. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62557. var destArray = new Uint8Array(dataLength);
  62558. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62559. var index = 0;
  62560. for (var y = 0; y < height; y++) {
  62561. for (var x = 0; x < width; x++) {
  62562. var srcPos = (x + y * width) * 4;
  62563. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  62564. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  62565. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  62566. if (DDSTools.StoreLODInAlphaChannel) {
  62567. destArray[index + 3] = lod;
  62568. }
  62569. else {
  62570. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  62571. }
  62572. index += 4;
  62573. }
  62574. }
  62575. return destArray;
  62576. };
  62577. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62578. var byteArray = new Uint8Array(dataLength);
  62579. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62580. var index = 0;
  62581. for (var y = 0; y < height; y++) {
  62582. for (var x = 0; x < width; x++) {
  62583. var srcPos = (x + y * width) * 4;
  62584. byteArray[index] = srcData[srcPos + 2];
  62585. byteArray[index + 1] = srcData[srcPos + 1];
  62586. byteArray[index + 2] = srcData[srcPos];
  62587. byteArray[index + 3] = srcData[srcPos + 3];
  62588. index += 4;
  62589. }
  62590. }
  62591. return byteArray;
  62592. };
  62593. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62594. var byteArray = new Uint8Array(dataLength);
  62595. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62596. var index = 0;
  62597. for (var y = 0; y < height; y++) {
  62598. for (var x = 0; x < width; x++) {
  62599. var srcPos = (x + y * width) * 3;
  62600. byteArray[index] = srcData[srcPos + 2];
  62601. byteArray[index + 1] = srcData[srcPos + 1];
  62602. byteArray[index + 2] = srcData[srcPos];
  62603. index += 3;
  62604. }
  62605. }
  62606. return byteArray;
  62607. };
  62608. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62609. var byteArray = new Uint8Array(dataLength);
  62610. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62611. var index = 0;
  62612. for (var y = 0; y < height; y++) {
  62613. for (var x = 0; x < width; x++) {
  62614. var srcPos = (x + y * width);
  62615. byteArray[index] = srcData[srcPos];
  62616. index++;
  62617. }
  62618. }
  62619. return byteArray;
  62620. };
  62621. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  62622. if (lodIndex === void 0) { lodIndex = -1; }
  62623. var ext = engine.getCaps().s3tc;
  62624. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  62625. if (header[off_magic] != DDS_MAGIC) {
  62626. BABYLON.Tools.Error("Invalid magic number in DDS header");
  62627. return;
  62628. }
  62629. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  62630. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  62631. return;
  62632. }
  62633. if (info.isCompressed && !ext) {
  62634. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  62635. return;
  62636. }
  62637. var bpp = header[off_RGBbpp];
  62638. dataOffset = header[off_size] + 4;
  62639. var computeFormats = false;
  62640. if (info.isFourCC) {
  62641. fourCC = header[off_pfFourCC];
  62642. switch (fourCC) {
  62643. case FOURCC_DXT1:
  62644. blockBytes = 8;
  62645. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  62646. break;
  62647. case FOURCC_DXT3:
  62648. blockBytes = 16;
  62649. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  62650. break;
  62651. case FOURCC_DXT5:
  62652. blockBytes = 16;
  62653. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  62654. break;
  62655. case FOURCC_D3DFMT_R16G16B16A16F:
  62656. computeFormats = true;
  62657. break;
  62658. case FOURCC_D3DFMT_R32G32B32A32F:
  62659. computeFormats = true;
  62660. break;
  62661. case FOURCC_DX10:
  62662. // There is an additionnal header so dataOffset need to be changed
  62663. dataOffset += 5 * 4; // 5 uints
  62664. var supported = false;
  62665. switch (info.dxgiFormat) {
  62666. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  62667. computeFormats = true;
  62668. supported = true;
  62669. break;
  62670. case DXGI_FORMAT_B8G8R8X8_UNORM:
  62671. info.isRGB = true;
  62672. info.isFourCC = false;
  62673. bpp = 32;
  62674. supported = true;
  62675. break;
  62676. }
  62677. if (supported) {
  62678. break;
  62679. }
  62680. default:
  62681. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  62682. return;
  62683. }
  62684. }
  62685. if (computeFormats) {
  62686. format = engine._getWebGLTextureType(info.textureType);
  62687. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62688. }
  62689. mipmapCount = 1;
  62690. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  62691. mipmapCount = Math.max(1, header[off_mipmapCount]);
  62692. }
  62693. for (var face = 0; face < faces; face++) {
  62694. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  62695. width = header[off_width];
  62696. height = header[off_height];
  62697. for (mip = 0; mip < mipmapCount; ++mip) {
  62698. if (lodIndex === -1 || lodIndex === mip) {
  62699. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  62700. var i = (lodIndex === -1) ? mip : 0;
  62701. if (!info.isCompressed && info.isFourCC) {
  62702. dataLength = width * height * 4;
  62703. var floatArray;
  62704. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  62705. if (bpp === 128) {
  62706. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62707. }
  62708. else if (bpp === 64) {
  62709. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62710. }
  62711. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62712. format = engine._getWebGLTextureType(info.textureType);
  62713. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62714. }
  62715. else {
  62716. if (bpp === 128) {
  62717. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62718. }
  62719. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  62720. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62721. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62722. format = engine._getWebGLTextureType(info.textureType);
  62723. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62724. }
  62725. else {
  62726. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62727. }
  62728. }
  62729. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  62730. }
  62731. else if (info.isRGB) {
  62732. if (bpp === 24) {
  62733. dataLength = width * height * 3;
  62734. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62735. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  62736. }
  62737. else {
  62738. dataLength = width * height * 4;
  62739. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62740. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  62741. }
  62742. }
  62743. else if (info.isLuminance) {
  62744. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  62745. var unpaddedRowSize = width;
  62746. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  62747. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  62748. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62749. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  62750. }
  62751. else {
  62752. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  62753. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  62754. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  62755. }
  62756. }
  62757. dataOffset += width * height * (bpp / 8);
  62758. width *= 0.5;
  62759. height *= 0.5;
  62760. width = Math.max(1.0, width);
  62761. height = Math.max(1.0, height);
  62762. }
  62763. }
  62764. };
  62765. DDSTools.StoreLODInAlphaChannel = false;
  62766. return DDSTools;
  62767. }());
  62768. Internals.DDSTools = DDSTools;
  62769. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62770. })(BABYLON || (BABYLON = {}));
  62771. //# sourceMappingURL=babylon.dds.js.map
  62772. var BABYLON;
  62773. (function (BABYLON) {
  62774. var Internals;
  62775. (function (Internals) {
  62776. /**
  62777. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  62778. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  62779. */
  62780. var KhronosTextureContainer = (function () {
  62781. /**
  62782. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  62783. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  62784. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  62785. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  62786. */
  62787. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  62788. this.arrayBuffer = arrayBuffer;
  62789. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  62790. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  62791. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  62792. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  62793. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  62794. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  62795. BABYLON.Tools.Error("texture missing KTX identifier");
  62796. return;
  62797. }
  62798. // load the reset of the header in native 32 bit int
  62799. var header = new Int32Array(this.arrayBuffer, 12, 13);
  62800. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  62801. var oppositeEndianess = header[0] === 0x01020304;
  62802. // read all the header elements in order they exist in the file, without modification (sans endainness)
  62803. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  62804. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  62805. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  62806. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  62807. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  62808. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  62809. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  62810. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  62811. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  62812. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  62813. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  62814. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  62815. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  62816. if (this.glType !== 0) {
  62817. BABYLON.Tools.Error("only compressed formats currently supported");
  62818. return;
  62819. }
  62820. else {
  62821. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  62822. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  62823. }
  62824. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  62825. BABYLON.Tools.Error("only 2D textures currently supported");
  62826. return;
  62827. }
  62828. if (this.numberOfArrayElements !== 0) {
  62829. BABYLON.Tools.Error("texture arrays not currently supported");
  62830. return;
  62831. }
  62832. if (this.numberOfFaces !== facesExpected) {
  62833. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  62834. return;
  62835. }
  62836. // we now have a completely validated file, so could use existence of loadType as success
  62837. // would need to make this more elaborate & adjust checks above to support more than one load type
  62838. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  62839. }
  62840. // not as fast hardware based, but will probably never need to use
  62841. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  62842. return ((val & 0xFF) << 24)
  62843. | ((val & 0xFF00) << 8)
  62844. | ((val >> 8) & 0xFF00)
  62845. | ((val >> 24) & 0xFF);
  62846. };
  62847. /**
  62848. * It is assumed that the texture has already been created & is currently bound
  62849. */
  62850. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  62851. switch (this.loadType) {
  62852. case KhronosTextureContainer.COMPRESSED_2D:
  62853. this._upload2DCompressedLevels(gl, loadMipmaps);
  62854. break;
  62855. case KhronosTextureContainer.TEX_2D:
  62856. case KhronosTextureContainer.COMPRESSED_3D:
  62857. case KhronosTextureContainer.TEX_3D:
  62858. }
  62859. };
  62860. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  62861. // initialize width & height for level 1
  62862. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  62863. var width = this.pixelWidth;
  62864. var height = this.pixelHeight;
  62865. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  62866. for (var level = 0; level < mipmapCount; level++) {
  62867. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  62868. for (var face = 0; face < this.numberOfFaces; face++) {
  62869. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  62870. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  62871. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  62872. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  62873. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  62874. }
  62875. width = Math.max(1.0, width * 0.5);
  62876. height = Math.max(1.0, height * 0.5);
  62877. }
  62878. };
  62879. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  62880. // load types
  62881. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  62882. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  62883. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  62884. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  62885. return KhronosTextureContainer;
  62886. }());
  62887. Internals.KhronosTextureContainer = KhronosTextureContainer;
  62888. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62889. })(BABYLON || (BABYLON = {}));
  62890. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  62891. var BABYLON;
  62892. (function (BABYLON) {
  62893. var DynamicFloatArrayElementInfo = (function () {
  62894. function DynamicFloatArrayElementInfo() {
  62895. }
  62896. return DynamicFloatArrayElementInfo;
  62897. }());
  62898. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  62899. /**
  62900. * 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.
  62901. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  62902. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  62903. * 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.
  62904. * 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.
  62905. * 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".
  62906. */
  62907. var DynamicFloatArray = (function () {
  62908. /**
  62909. * Construct an instance of the dynamic float array
  62910. * @param stride size of one element in float (i.e. not bytes!)
  62911. * @param initialElementCount the number of available entries at construction
  62912. */
  62913. function DynamicFloatArray(stride, initialElementCount) {
  62914. this.compareValueOffset = null;
  62915. this.sortingAscending = true;
  62916. this._stride = stride;
  62917. this.buffer = new Float32Array(stride * initialElementCount);
  62918. this._lastUsed = 0;
  62919. this._firstFree = 0;
  62920. this._allEntries = new Array(initialElementCount);
  62921. this._freeEntries = new Array(initialElementCount);
  62922. for (var i = 0; i < initialElementCount; i++) {
  62923. var element = new DynamicFloatArrayElementInfo();
  62924. element.offset = i * stride;
  62925. this._allEntries[i] = element;
  62926. this._freeEntries[initialElementCount - i - 1] = element;
  62927. }
  62928. }
  62929. /**
  62930. * Allocate an element in the array.
  62931. * @return the element info instance that contains the offset into the main buffer of the element's location.
  62932. * Beware, this offset may change when you call pack()
  62933. */
  62934. DynamicFloatArray.prototype.allocElement = function () {
  62935. if (this._freeEntries.length === 0) {
  62936. this._growBuffer();
  62937. }
  62938. var el = this._freeEntries.pop();
  62939. this._lastUsed = Math.max(el.offset, this._lastUsed);
  62940. if (el.offset === this._firstFree) {
  62941. if (this._freeEntries.length > 0) {
  62942. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  62943. }
  62944. else {
  62945. this._firstFree += this._stride;
  62946. }
  62947. }
  62948. return el;
  62949. };
  62950. /**
  62951. * Free the element corresponding to the given element info
  62952. * @param elInfo the element that describe the allocated element
  62953. */
  62954. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  62955. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  62956. this._freeEntries.push(elInfo);
  62957. };
  62958. /**
  62959. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  62960. * 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().
  62961. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  62962. */
  62963. DynamicFloatArray.prototype.pack = function () {
  62964. // no free slot? no need to pack
  62965. if (this._freeEntries.length === 0) {
  62966. return this.buffer;
  62967. }
  62968. // If the buffer is already packed the last used will always be lower than the first free
  62969. // 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.
  62970. if (this._lastUsed < this._firstFree) {
  62971. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  62972. return elementsBuffer_1;
  62973. }
  62974. var s = this._stride;
  62975. // 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
  62976. var lastFree = new DynamicFloatArrayElementInfo();
  62977. lastFree.offset = this.totalElementCount * s;
  62978. this._freeEntries.push(lastFree);
  62979. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  62980. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62981. var firstFreeSlotOffset = sortedFree[0].offset;
  62982. var freeZoneSize = 1;
  62983. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  62984. var prevOffset = sortedFree[0].offset;
  62985. for (var i = 1; i < sortedFree.length; i++) {
  62986. // 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
  62987. if (firstFreeSlotOffset >= occupiedZoneSize) {
  62988. break;
  62989. }
  62990. var curFree = sortedFree[i];
  62991. var curOffset = curFree.offset;
  62992. // Compute the distance between this offset and the previous
  62993. var distance = curOffset - prevOffset;
  62994. // If the distance is the stride size, they are adjacent, it good, move to the next
  62995. if (distance === s) {
  62996. // Free zone is one element bigger
  62997. ++freeZoneSize;
  62998. // as we're about to iterate to the next, the cur becomes the previous...
  62999. prevOffset = curOffset;
  63000. continue;
  63001. }
  63002. // Distance is bigger, which means there's x element between the previous free and this one
  63003. var usedRange = (distance / s) - 1;
  63004. // Two cases the free zone is smaller than the data to move or bigger
  63005. // Copy what can fit in the free zone
  63006. var curMoveOffset = curOffset - s;
  63007. var copyCount = Math.min(freeZoneSize, usedRange);
  63008. for (var j = 0; j < copyCount; j++) {
  63009. var freeI = firstFreeSlotOffset / s;
  63010. var curI = curMoveOffset / s;
  63011. var moveEl = sortedAll[curI];
  63012. this._moveElement(moveEl, firstFreeSlotOffset);
  63013. var replacedEl = sortedAll[freeI];
  63014. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  63015. replacedEl.offset = curMoveOffset;
  63016. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  63017. sortedAll[freeI] = moveEl;
  63018. sortedAll[curI] = replacedEl;
  63019. curMoveOffset -= s;
  63020. firstFreeSlotOffset += s;
  63021. }
  63022. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  63023. if (freeZoneSize <= usedRange) {
  63024. firstFreeSlotOffset = curMoveOffset + s;
  63025. freeZoneSize = 1 + copyCount;
  63026. }
  63027. else {
  63028. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  63029. }
  63030. // as we're about to iterate to the next, the cur becomes the previous...
  63031. prevOffset = curOffset;
  63032. }
  63033. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  63034. this._lastUsed = firstFreeSlotOffset - s;
  63035. this._firstFree = firstFreeSlotOffset;
  63036. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  63037. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  63038. this._allEntries = sortedAll;
  63039. return elementsBuffer;
  63040. };
  63041. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  63042. for (var i = 0; i < this._stride; i++) {
  63043. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  63044. }
  63045. element.offset = destOffset;
  63046. };
  63047. DynamicFloatArray.prototype._growBuffer = function () {
  63048. // Allocate the new buffer with 50% more entries, copy the content of the current one
  63049. var newElCount = Math.floor(this.totalElementCount * 1.5);
  63050. var newBuffer = new Float32Array(newElCount * this._stride);
  63051. newBuffer.set(this.buffer);
  63052. var curCount = this.totalElementCount;
  63053. var addedCount = newElCount - this.totalElementCount;
  63054. for (var i = 0; i < addedCount; i++) {
  63055. var element = new DynamicFloatArrayElementInfo();
  63056. element.offset = (curCount + i) * this.stride;
  63057. this._allEntries.push(element);
  63058. this._freeEntries[addedCount - i - 1] = element;
  63059. }
  63060. this._firstFree = curCount * this.stride;
  63061. this.buffer = newBuffer;
  63062. };
  63063. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  63064. /**
  63065. * Get the total count of entries that can fit in the current buffer
  63066. * @returns the elements count
  63067. */
  63068. get: function () {
  63069. return this._allEntries.length;
  63070. },
  63071. enumerable: true,
  63072. configurable: true
  63073. });
  63074. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  63075. /**
  63076. * Get the count of free entries that can still be allocated without resizing the buffer
  63077. * @returns the free elements count
  63078. */
  63079. get: function () {
  63080. return this._freeEntries.length;
  63081. },
  63082. enumerable: true,
  63083. configurable: true
  63084. });
  63085. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  63086. /**
  63087. * Get the count of allocated elements
  63088. * @returns the allocated elements count
  63089. */
  63090. get: function () {
  63091. return this._allEntries.length - this._freeEntries.length;
  63092. },
  63093. enumerable: true,
  63094. configurable: true
  63095. });
  63096. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  63097. /**
  63098. * Return the size of one element in float
  63099. * @returns the size in float
  63100. */
  63101. get: function () {
  63102. return this._stride;
  63103. },
  63104. enumerable: true,
  63105. configurable: true
  63106. });
  63107. DynamicFloatArray.prototype.sort = function () {
  63108. var _this = this;
  63109. if (!this.compareValueOffset) {
  63110. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  63111. }
  63112. var count = this.usedElementCount;
  63113. // Do we have to (re)create the sort table?
  63114. if (!this._sortTable || this._sortTable.length < count) {
  63115. // 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...
  63116. var newCount = Math.min(this.totalElementCount, count * 2);
  63117. this._sortTable = new Array(newCount);
  63118. }
  63119. if (!this._sortedTable || this._sortedTable.length !== count) {
  63120. this._sortedTable = new Array(count);
  63121. }
  63122. // Because, you know...
  63123. this.pack();
  63124. //let stride = this.stride;
  63125. //for (let i = 0; i < count; i++) {
  63126. // let si = this._sortTable[i];
  63127. // if (!si) {
  63128. // si = new SortInfo();
  63129. // this._sortTable[i] = si;
  63130. // }
  63131. // si.entry = this._allEntries[i];
  63132. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  63133. // si.swapedOffset = null;
  63134. // this._sortedTable[i] = si;
  63135. //}
  63136. var curOffset = 0;
  63137. var stride = this.stride;
  63138. for (var i = 0; i < count; i++, curOffset += stride) {
  63139. var si = this._sortTable[i];
  63140. if (!si) {
  63141. si = new SortInfo();
  63142. this._sortTable[i] = si;
  63143. }
  63144. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  63145. si.offset = curOffset;
  63146. si.swapedOffset = null;
  63147. this._sortedTable[i] = si;
  63148. }
  63149. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  63150. if (this.sortingAscending) {
  63151. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  63152. }
  63153. else {
  63154. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  63155. }
  63156. var swapElements = function (src, dst) {
  63157. for (var i = 0; i < stride; i++) {
  63158. var tps = _this.buffer[dst + i];
  63159. _this.buffer[dst + i] = _this.buffer[src + i];
  63160. _this.buffer[src + i] = tps;
  63161. }
  63162. };
  63163. // 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:
  63164. // 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),
  63165. // and I still want something with a good algorithm complexity.
  63166. // 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,
  63167. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  63168. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  63169. // 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
  63170. // until we find a SortInfo object without a swapedOffset which means we got the right location
  63171. // 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
  63172. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  63173. for (var i = 0; i < count; i++) {
  63174. // Get the element to move
  63175. var sourceSI = this._sortedTable[i];
  63176. var destSI = this._sortTable[i];
  63177. var sourceOff = sourceSI.offset;
  63178. // If the source changed location, find the new one
  63179. if (sourceSI.swapedOffset) {
  63180. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  63181. var curSI = sourceSI;
  63182. while (curSI.swapedOffset) {
  63183. curSI = this._sortTable[curSI.swapedOffset / stride];
  63184. }
  63185. // Finally get the right location
  63186. sourceOff = curSI.offset;
  63187. }
  63188. // Tag the element being replaced with its new location
  63189. destSI.swapedOffset = sourceOff;
  63190. // Swap elements (only if needed)
  63191. if (sourceOff !== destSI.offset) {
  63192. swapElements(sourceOff, destSI.offset);
  63193. }
  63194. // Update the offset in the corresponding DFAE
  63195. //sourceSI.entry.offset = destSI.entry.offset;
  63196. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  63197. }
  63198. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  63199. return true;
  63200. };
  63201. return DynamicFloatArray;
  63202. }());
  63203. BABYLON.DynamicFloatArray = DynamicFloatArray;
  63204. var SortInfo = (function () {
  63205. function SortInfo() {
  63206. this.compareData = this.offset = this.swapedOffset = null;
  63207. }
  63208. return SortInfo;
  63209. }());
  63210. })(BABYLON || (BABYLON = {}));
  63211. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  63212. var BABYLON;
  63213. (function (BABYLON) {
  63214. var Debug;
  63215. (function (Debug) {
  63216. /**
  63217. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  63218. */
  63219. var SkeletonViewer = (function () {
  63220. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  63221. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63222. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63223. this.skeleton = skeleton;
  63224. this.mesh = mesh;
  63225. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63226. this.renderingGroupId = renderingGroupId;
  63227. this.color = BABYLON.Color3.White();
  63228. this._debugLines = [];
  63229. this._isEnabled = false;
  63230. this._scene = scene;
  63231. this.update();
  63232. this._renderFunction = this.update.bind(this);
  63233. }
  63234. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63235. get: function () {
  63236. return this._isEnabled;
  63237. },
  63238. set: function (value) {
  63239. if (this._isEnabled === value) {
  63240. return;
  63241. }
  63242. this._isEnabled = value;
  63243. if (value) {
  63244. this._scene.registerBeforeRender(this._renderFunction);
  63245. }
  63246. else {
  63247. this._scene.unregisterBeforeRender(this._renderFunction);
  63248. }
  63249. },
  63250. enumerable: true,
  63251. configurable: true
  63252. });
  63253. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63254. if (x === void 0) { x = 0; }
  63255. if (y === void 0) { y = 0; }
  63256. if (z === void 0) { z = 0; }
  63257. var tmat = BABYLON.Tmp.Matrix[0];
  63258. var parentBone = bone.getParent();
  63259. tmat.copyFrom(bone.getLocalMatrix());
  63260. if (x !== 0 || y !== 0 || z !== 0) {
  63261. var tmat2 = BABYLON.Tmp.Matrix[1];
  63262. BABYLON.Matrix.IdentityToRef(tmat2);
  63263. tmat2.m[12] = x;
  63264. tmat2.m[13] = y;
  63265. tmat2.m[14] = z;
  63266. tmat2.multiplyToRef(tmat, tmat);
  63267. }
  63268. if (parentBone) {
  63269. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63270. }
  63271. tmat.multiplyToRef(meshMat, tmat);
  63272. position.x = tmat.m[12];
  63273. position.y = tmat.m[13];
  63274. position.z = tmat.m[14];
  63275. };
  63276. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63277. var len = bones.length;
  63278. var meshPos = this.mesh.position;
  63279. for (var i = 0; i < len; i++) {
  63280. var bone = bones[i];
  63281. var points = this._debugLines[i];
  63282. if (!points) {
  63283. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63284. this._debugLines[i] = points;
  63285. }
  63286. this._getBonePosition(points[0], bone, meshMat);
  63287. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63288. points[0].subtractInPlace(meshPos);
  63289. points[1].subtractInPlace(meshPos);
  63290. }
  63291. };
  63292. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63293. var len = bones.length;
  63294. var boneNum = 0;
  63295. var meshPos = this.mesh.position;
  63296. for (var i = len - 1; i >= 0; i--) {
  63297. var childBone = bones[i];
  63298. var parentBone = childBone.getParent();
  63299. if (!parentBone) {
  63300. continue;
  63301. }
  63302. var points = this._debugLines[boneNum];
  63303. if (!points) {
  63304. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63305. this._debugLines[boneNum] = points;
  63306. }
  63307. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  63308. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  63309. points[0].subtractInPlace(meshPos);
  63310. points[1].subtractInPlace(meshPos);
  63311. boneNum++;
  63312. }
  63313. };
  63314. SkeletonViewer.prototype.update = function () {
  63315. if (this.autoUpdateBonesMatrices) {
  63316. this.skeleton.computeAbsoluteTransforms();
  63317. }
  63318. if (this.skeleton.bones[0].length === undefined) {
  63319. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63320. }
  63321. else {
  63322. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63323. }
  63324. if (!this._debugMesh) {
  63325. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  63326. this._debugMesh.renderingGroupId = this.renderingGroupId;
  63327. }
  63328. else {
  63329. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  63330. }
  63331. this._debugMesh.position.copyFrom(this.mesh.position);
  63332. this._debugMesh.color = this.color;
  63333. };
  63334. SkeletonViewer.prototype.dispose = function () {
  63335. if (this._debugMesh) {
  63336. this.isEnabled = false;
  63337. this._debugMesh.dispose();
  63338. this._debugMesh = null;
  63339. }
  63340. };
  63341. return SkeletonViewer;
  63342. }());
  63343. Debug.SkeletonViewer = SkeletonViewer;
  63344. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63345. })(BABYLON || (BABYLON = {}));
  63346. //# sourceMappingURL=babylon.skeletonViewer.js.map
  63347. var BABYLON;
  63348. (function (BABYLON) {
  63349. var Debug;
  63350. (function (Debug) {
  63351. var AxesViewer = (function () {
  63352. function AxesViewer(scene, scaleLines) {
  63353. if (scaleLines === void 0) { scaleLines = 1; }
  63354. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63355. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63356. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63357. this.scaleLines = 1;
  63358. this.scaleLines = scaleLines;
  63359. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  63360. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  63361. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  63362. this._xmesh.renderingGroupId = 2;
  63363. this._ymesh.renderingGroupId = 2;
  63364. this._zmesh.renderingGroupId = 2;
  63365. this._xmesh.material.checkReadyOnlyOnce = true;
  63366. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  63367. this._ymesh.material.checkReadyOnlyOnce = true;
  63368. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  63369. this._zmesh.material.checkReadyOnlyOnce = true;
  63370. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  63371. this.scene = scene;
  63372. }
  63373. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  63374. var scaleLines = this.scaleLines;
  63375. this._xmesh.position.copyFrom(position);
  63376. this._ymesh.position.copyFrom(position);
  63377. this._zmesh.position.copyFrom(position);
  63378. var point2 = this._xline[1];
  63379. point2.x = xaxis.x * scaleLines;
  63380. point2.y = xaxis.y * scaleLines;
  63381. point2.z = xaxis.z * scaleLines;
  63382. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  63383. point2 = this._yline[1];
  63384. point2.x = yaxis.x * scaleLines;
  63385. point2.y = yaxis.y * scaleLines;
  63386. point2.z = yaxis.z * scaleLines;
  63387. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  63388. point2 = this._zline[1];
  63389. point2.x = zaxis.x * scaleLines;
  63390. point2.y = zaxis.y * scaleLines;
  63391. point2.z = zaxis.z * scaleLines;
  63392. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  63393. };
  63394. AxesViewer.prototype.dispose = function () {
  63395. if (this._xmesh) {
  63396. this._xmesh.dispose();
  63397. this._ymesh.dispose();
  63398. this._zmesh.dispose();
  63399. this._xmesh = null;
  63400. this._ymesh = null;
  63401. this._zmesh = null;
  63402. this._xline = null;
  63403. this._yline = null;
  63404. this._zline = null;
  63405. this.scene = null;
  63406. }
  63407. };
  63408. return AxesViewer;
  63409. }());
  63410. Debug.AxesViewer = AxesViewer;
  63411. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63412. })(BABYLON || (BABYLON = {}));
  63413. //# sourceMappingURL=babylon.axesViewer.js.map
  63414. var BABYLON;
  63415. (function (BABYLON) {
  63416. var Debug;
  63417. (function (Debug) {
  63418. var BoneAxesViewer = (function (_super) {
  63419. __extends(BoneAxesViewer, _super);
  63420. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63421. if (scaleLines === void 0) { scaleLines = 1; }
  63422. var _this = _super.call(this, scene, scaleLines) || this;
  63423. _this.pos = BABYLON.Vector3.Zero();
  63424. _this.xaxis = BABYLON.Vector3.Zero();
  63425. _this.yaxis = BABYLON.Vector3.Zero();
  63426. _this.zaxis = BABYLON.Vector3.Zero();
  63427. _this.mesh = mesh;
  63428. _this.bone = bone;
  63429. return _this;
  63430. }
  63431. BoneAxesViewer.prototype.update = function () {
  63432. var bone = this.bone;
  63433. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63434. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63435. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63436. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63437. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63438. };
  63439. BoneAxesViewer.prototype.dispose = function () {
  63440. if (this.pos) {
  63441. this.pos = null;
  63442. this.xaxis = null;
  63443. this.yaxis = null;
  63444. this.zaxis = null;
  63445. this.mesh = null;
  63446. this.bone = null;
  63447. _super.prototype.dispose.call(this);
  63448. }
  63449. };
  63450. return BoneAxesViewer;
  63451. }(Debug.AxesViewer));
  63452. Debug.BoneAxesViewer = BoneAxesViewer;
  63453. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63454. })(BABYLON || (BABYLON = {}));
  63455. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63456. var BABYLON;
  63457. (function (BABYLON) {
  63458. var RayHelper = (function () {
  63459. function RayHelper(ray) {
  63460. this.ray = ray;
  63461. }
  63462. RayHelper.CreateAndShow = function (ray, scene, color) {
  63463. var helper = new RayHelper(ray);
  63464. helper.show(scene, color);
  63465. return helper;
  63466. };
  63467. RayHelper.prototype.show = function (scene, color) {
  63468. if (!this._renderFunction) {
  63469. var ray = this.ray;
  63470. this._renderFunction = this._render.bind(this);
  63471. this._scene = scene;
  63472. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63473. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63474. this._scene.registerBeforeRender(this._renderFunction);
  63475. }
  63476. if (color) {
  63477. this._renderLine.color.copyFrom(color);
  63478. }
  63479. };
  63480. RayHelper.prototype.hide = function () {
  63481. if (this._renderFunction) {
  63482. this._scene.unregisterBeforeRender(this._renderFunction);
  63483. this._scene = null;
  63484. this._renderFunction = null;
  63485. this._renderLine.dispose();
  63486. this._renderLine = null;
  63487. this._renderPoints = null;
  63488. }
  63489. };
  63490. RayHelper.prototype._render = function () {
  63491. var ray = this.ray;
  63492. var point = this._renderPoints[1];
  63493. var len = Math.min(ray.length, 1000000);
  63494. point.copyFrom(ray.direction);
  63495. point.scaleInPlace(len);
  63496. point.addInPlace(ray.origin);
  63497. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  63498. };
  63499. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  63500. this._attachedToMesh = mesh;
  63501. var ray = this.ray;
  63502. if (!ray.direction) {
  63503. ray.direction = BABYLON.Vector3.Zero();
  63504. }
  63505. if (!ray.origin) {
  63506. ray.origin = BABYLON.Vector3.Zero();
  63507. }
  63508. if (length) {
  63509. ray.length = length;
  63510. }
  63511. if (!meshSpaceOrigin) {
  63512. meshSpaceOrigin = BABYLON.Vector3.Zero();
  63513. }
  63514. if (!meshSpaceDirection) {
  63515. // -1 so that this will work with Mesh.lookAt
  63516. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  63517. }
  63518. if (!this._meshSpaceDirection) {
  63519. this._meshSpaceDirection = meshSpaceDirection.clone();
  63520. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  63521. }
  63522. else {
  63523. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  63524. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  63525. }
  63526. if (!this._updateToMeshFunction) {
  63527. this._updateToMeshFunction = this._updateToMesh.bind(this);
  63528. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  63529. }
  63530. this._updateToMesh();
  63531. };
  63532. RayHelper.prototype.detachFromMesh = function () {
  63533. if (this._attachedToMesh) {
  63534. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  63535. this._attachedToMesh = null;
  63536. this._updateToMeshFunction = null;
  63537. }
  63538. };
  63539. RayHelper.prototype._updateToMesh = function () {
  63540. var ray = this.ray;
  63541. if (this._attachedToMesh._isDisposed) {
  63542. this.detachFromMesh();
  63543. return;
  63544. }
  63545. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  63546. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  63547. };
  63548. RayHelper.prototype.dispose = function () {
  63549. this.hide();
  63550. this.detachFromMesh();
  63551. this.ray = null;
  63552. };
  63553. return RayHelper;
  63554. }());
  63555. BABYLON.RayHelper = RayHelper;
  63556. })(BABYLON || (BABYLON = {}));
  63557. //# sourceMappingURL=babylon.rayHelper.js.map
  63558. var BABYLON;
  63559. (function (BABYLON) {
  63560. var DebugLayer = (function () {
  63561. function DebugLayer(scene) {
  63562. this._scene = scene;
  63563. }
  63564. /** Creates the inspector window. */
  63565. DebugLayer.prototype._createInspector = function (config) {
  63566. if (config === void 0) { config = {}; }
  63567. var popup = config.popup || false;
  63568. var initialTab = config.initialTab || 0;
  63569. var parentElement = config.parentElement || null;
  63570. if (!this._inspector) {
  63571. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  63572. } // else nothing to do,; instance is already existing
  63573. };
  63574. DebugLayer.prototype.isVisible = function () {
  63575. if (!this._inspector) {
  63576. return false;
  63577. }
  63578. return true;
  63579. };
  63580. DebugLayer.prototype.hide = function () {
  63581. if (this._inspector) {
  63582. try {
  63583. this._inspector.dispose();
  63584. }
  63585. catch (e) {
  63586. // If the inspector has been removed directly from the inspector tool
  63587. }
  63588. this._inspector = null;
  63589. }
  63590. };
  63591. DebugLayer.prototype.show = function (config) {
  63592. if (config === void 0) { config = {}; }
  63593. if (typeof INSPECTOR == 'undefined') {
  63594. // Load inspector and add it to the DOM
  63595. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63596. }
  63597. else {
  63598. // Otherwise creates the inspector
  63599. this._createInspector(config);
  63600. }
  63601. };
  63602. // Get protocol used - http or https
  63603. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63604. return DebugLayer;
  63605. }());
  63606. BABYLON.DebugLayer = DebugLayer;
  63607. })(BABYLON || (BABYLON = {}));
  63608. //# sourceMappingURL=babylon.debugLayer.js.map
  63609. var BABYLON;
  63610. (function (BABYLON) {
  63611. var Debug;
  63612. (function (Debug) {
  63613. var PhysicsViewer = (function () {
  63614. function PhysicsViewer(scene) {
  63615. this._impostors = [];
  63616. this._meshes = [];
  63617. this._numMeshes = 0;
  63618. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63619. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  63620. }
  63621. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63622. var plugin = this._physicsEnginePlugin;
  63623. for (var i = 0; i < this._numMeshes; i++) {
  63624. if (this._impostors[i].isDisposed) {
  63625. this.hideImpostor(this._impostors[i--]);
  63626. }
  63627. else {
  63628. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  63629. }
  63630. }
  63631. };
  63632. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63633. for (var i = 0; i < this._numMeshes; i++) {
  63634. if (this._impostors[i] == impostor) {
  63635. return;
  63636. }
  63637. }
  63638. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63639. if (debugMesh) {
  63640. this._impostors[this._numMeshes] = impostor;
  63641. this._meshes[this._numMeshes] = debugMesh;
  63642. if (this._numMeshes === 0) {
  63643. this._renderFunction = this._updateDebugMeshes.bind(this);
  63644. this._scene.registerBeforeRender(this._renderFunction);
  63645. }
  63646. this._numMeshes++;
  63647. }
  63648. };
  63649. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63650. var removed = false;
  63651. for (var i = 0; i < this._numMeshes; i++) {
  63652. if (this._impostors[i] == impostor) {
  63653. this._scene.removeMesh(this._meshes[i]);
  63654. this._meshes[i].dispose();
  63655. this._numMeshes--;
  63656. if (this._numMeshes > 0) {
  63657. this._meshes[i] = this._meshes[this._numMeshes];
  63658. this._impostors[i] = this._impostors[this._numMeshes];
  63659. this._meshes[this._numMeshes] = null;
  63660. this._impostors[this._numMeshes] = null;
  63661. }
  63662. else {
  63663. this._meshes[0] = null;
  63664. this._impostors[0] = null;
  63665. }
  63666. removed = true;
  63667. break;
  63668. }
  63669. }
  63670. if (removed && this._numMeshes === 0) {
  63671. this._scene.unregisterBeforeRender(this._renderFunction);
  63672. }
  63673. };
  63674. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63675. if (!this._debugMaterial) {
  63676. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63677. this._debugMaterial.wireframe = true;
  63678. }
  63679. return this._debugMaterial;
  63680. };
  63681. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63682. if (!this._debugBoxMesh) {
  63683. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63684. this._debugBoxMesh.renderingGroupId = 1;
  63685. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63686. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63687. scene.removeMesh(this._debugBoxMesh);
  63688. }
  63689. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63690. };
  63691. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63692. if (!this._debugSphereMesh) {
  63693. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63694. this._debugSphereMesh.renderingGroupId = 1;
  63695. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63696. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63697. scene.removeMesh(this._debugSphereMesh);
  63698. }
  63699. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63700. };
  63701. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63702. var body = impostor.physicsBody;
  63703. var shape = body.shapes[0];
  63704. var mesh;
  63705. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63706. mesh = this._getDebugBoxMesh(scene);
  63707. impostor.getBoxSizeToRef(mesh.scaling);
  63708. }
  63709. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63710. mesh = this._getDebugSphereMesh(scene);
  63711. var radius = impostor.getRadius();
  63712. mesh.scaling.x = radius * 2;
  63713. mesh.scaling.y = radius * 2;
  63714. mesh.scaling.z = radius * 2;
  63715. }
  63716. return mesh;
  63717. };
  63718. PhysicsViewer.prototype.dispose = function () {
  63719. for (var i = 0; i < this._numMeshes; i++) {
  63720. this.hideImpostor(this._impostors[i]);
  63721. }
  63722. if (this._debugBoxMesh) {
  63723. this._debugBoxMesh.dispose();
  63724. }
  63725. if (this._debugSphereMesh) {
  63726. this._debugSphereMesh.dispose();
  63727. }
  63728. if (this._debugMaterial) {
  63729. this._debugMaterial.dispose();
  63730. }
  63731. this._impostors.length = 0;
  63732. this._scene = null;
  63733. this._physicsEnginePlugin = null;
  63734. };
  63735. return PhysicsViewer;
  63736. }());
  63737. Debug.PhysicsViewer = PhysicsViewer;
  63738. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63739. })(BABYLON || (BABYLON = {}));
  63740. //# sourceMappingURL=babylon.physicsViewer.js.map
  63741. var BABYLON;
  63742. (function (BABYLON) {
  63743. var BoundingBoxRenderer = (function () {
  63744. function BoundingBoxRenderer(scene) {
  63745. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63746. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63747. this.showBackLines = true;
  63748. this.renderList = new BABYLON.SmartArray(32);
  63749. this._vertexBuffers = {};
  63750. this._scene = scene;
  63751. }
  63752. BoundingBoxRenderer.prototype._prepareRessources = function () {
  63753. if (this._colorShader) {
  63754. return;
  63755. }
  63756. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  63757. attributes: [BABYLON.VertexBuffer.PositionKind],
  63758. uniforms: ["world", "viewProjection", "color"]
  63759. });
  63760. var engine = this._scene.getEngine();
  63761. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  63762. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  63763. this._createIndexBuffer();
  63764. };
  63765. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  63766. var engine = this._scene.getEngine();
  63767. 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]);
  63768. };
  63769. BoundingBoxRenderer.prototype._rebuild = function () {
  63770. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  63771. this._createIndexBuffer();
  63772. };
  63773. BoundingBoxRenderer.prototype.reset = function () {
  63774. this.renderList.reset();
  63775. };
  63776. BoundingBoxRenderer.prototype.render = function () {
  63777. if (this.renderList.length === 0) {
  63778. return;
  63779. }
  63780. this._prepareRessources();
  63781. if (!this._colorShader.isReady()) {
  63782. return;
  63783. }
  63784. var engine = this._scene.getEngine();
  63785. engine.setDepthWrite(false);
  63786. this._colorShader._preBind();
  63787. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  63788. var boundingBox = this.renderList.data[boundingBoxIndex];
  63789. var min = boundingBox.minimum;
  63790. var max = boundingBox.maximum;
  63791. var diff = max.subtract(min);
  63792. var median = min.add(diff.scale(0.5));
  63793. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63794. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63795. .multiply(boundingBox.getWorldMatrix());
  63796. // VBOs
  63797. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63798. if (this.showBackLines) {
  63799. // Back
  63800. engine.setDepthFunctionToGreaterOrEqual();
  63801. this._scene.resetCachedMaterial();
  63802. this._colorShader.setColor4("color", this.backColor.toColor4());
  63803. this._colorShader.bind(worldMatrix);
  63804. // Draw order
  63805. engine.draw(false, 0, 24);
  63806. }
  63807. // Front
  63808. engine.setDepthFunctionToLess();
  63809. this._scene.resetCachedMaterial();
  63810. this._colorShader.setColor4("color", this.frontColor.toColor4());
  63811. this._colorShader.bind(worldMatrix);
  63812. // Draw order
  63813. engine.draw(false, 0, 24);
  63814. }
  63815. this._colorShader.unbind();
  63816. engine.setDepthFunctionToLessOrEqual();
  63817. engine.setDepthWrite(true);
  63818. };
  63819. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63820. this._prepareRessources();
  63821. if (!this._colorShader.isReady()) {
  63822. return;
  63823. }
  63824. var engine = this._scene.getEngine();
  63825. engine.setDepthWrite(false);
  63826. engine.setColorWrite(false);
  63827. this._colorShader._preBind();
  63828. var boundingBox = mesh._boundingInfo.boundingBox;
  63829. var min = boundingBox.minimum;
  63830. var max = boundingBox.maximum;
  63831. var diff = max.subtract(min);
  63832. var median = min.add(diff.scale(0.5));
  63833. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63834. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63835. .multiply(boundingBox.getWorldMatrix());
  63836. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63837. engine.setDepthFunctionToLess();
  63838. this._scene.resetCachedMaterial();
  63839. this._colorShader.bind(worldMatrix);
  63840. engine.draw(false, 0, 24);
  63841. this._colorShader.unbind();
  63842. engine.setDepthFunctionToLessOrEqual();
  63843. engine.setDepthWrite(true);
  63844. engine.setColorWrite(true);
  63845. };
  63846. BoundingBoxRenderer.prototype.dispose = function () {
  63847. if (!this._colorShader) {
  63848. return;
  63849. }
  63850. this.renderList.dispose();
  63851. this._colorShader.dispose();
  63852. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63853. if (buffer) {
  63854. buffer.dispose();
  63855. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63856. }
  63857. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  63858. };
  63859. return BoundingBoxRenderer;
  63860. }());
  63861. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63862. })(BABYLON || (BABYLON = {}));
  63863. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63864. var BABYLON;
  63865. (function (BABYLON) {
  63866. var MorphTarget = (function () {
  63867. function MorphTarget(name, influence) {
  63868. if (influence === void 0) { influence = 0; }
  63869. this.name = name;
  63870. this.animations = new Array();
  63871. this.onInfluenceChanged = new BABYLON.Observable();
  63872. this.influence = influence;
  63873. }
  63874. Object.defineProperty(MorphTarget.prototype, "influence", {
  63875. get: function () {
  63876. return this._influence;
  63877. },
  63878. set: function (influence) {
  63879. if (this._influence === influence) {
  63880. return;
  63881. }
  63882. var previous = this._influence;
  63883. this._influence = influence;
  63884. if (this.onInfluenceChanged.hasObservers) {
  63885. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  63886. }
  63887. },
  63888. enumerable: true,
  63889. configurable: true
  63890. });
  63891. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  63892. get: function () {
  63893. return this._normals !== undefined;
  63894. },
  63895. enumerable: true,
  63896. configurable: true
  63897. });
  63898. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  63899. get: function () {
  63900. return this._tangents !== undefined;
  63901. },
  63902. enumerable: true,
  63903. configurable: true
  63904. });
  63905. MorphTarget.prototype.setPositions = function (data) {
  63906. this._positions = new Float32Array(data);
  63907. };
  63908. MorphTarget.prototype.getPositions = function () {
  63909. return this._positions;
  63910. };
  63911. MorphTarget.prototype.setNormals = function (data) {
  63912. this._normals = new Float32Array(data);
  63913. };
  63914. MorphTarget.prototype.getNormals = function () {
  63915. return this._normals;
  63916. };
  63917. MorphTarget.prototype.setTangents = function (data) {
  63918. this._tangents = new Float32Array(data);
  63919. };
  63920. MorphTarget.prototype.getTangents = function () {
  63921. return this._tangents;
  63922. };
  63923. /**
  63924. * Serializes the current target into a Serialization object.
  63925. * Returns the serialized object.
  63926. */
  63927. MorphTarget.prototype.serialize = function () {
  63928. var serializationObject = {};
  63929. serializationObject.name = this.name;
  63930. serializationObject.influence = this.influence;
  63931. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  63932. if (this.hasNormals) {
  63933. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  63934. }
  63935. if (this.hasTangents) {
  63936. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  63937. }
  63938. return serializationObject;
  63939. };
  63940. // Statics
  63941. MorphTarget.Parse = function (serializationObject) {
  63942. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  63943. result.setPositions(serializationObject.positions);
  63944. if (serializationObject.normals) {
  63945. result.setNormals(serializationObject.normals);
  63946. }
  63947. if (serializationObject.tangents) {
  63948. result.setTangents(serializationObject.tangents);
  63949. }
  63950. return result;
  63951. };
  63952. MorphTarget.FromMesh = function (mesh, name, influence) {
  63953. if (!name) {
  63954. name = mesh.name;
  63955. }
  63956. var result = new MorphTarget(name, influence);
  63957. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  63958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  63959. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  63960. }
  63961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  63962. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  63963. }
  63964. return result;
  63965. };
  63966. return MorphTarget;
  63967. }());
  63968. BABYLON.MorphTarget = MorphTarget;
  63969. })(BABYLON || (BABYLON = {}));
  63970. //# sourceMappingURL=babylon.morphTarget.js.map
  63971. var BABYLON;
  63972. (function (BABYLON) {
  63973. var MorphTargetManager = (function () {
  63974. function MorphTargetManager(scene) {
  63975. this._targets = new Array();
  63976. this._targetObservable = new Array();
  63977. this._activeTargets = new BABYLON.SmartArray(16);
  63978. this._supportsNormals = false;
  63979. this._supportsTangents = false;
  63980. this._vertexCount = 0;
  63981. this._uniqueId = 0;
  63982. this._tempInfluences = new Array();
  63983. if (!scene) {
  63984. scene = BABYLON.Engine.LastCreatedScene;
  63985. }
  63986. this._scene = scene;
  63987. this._scene.morphTargetManagers.push(this);
  63988. this._uniqueId = scene.getUniqueId();
  63989. }
  63990. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  63991. get: function () {
  63992. return this._uniqueId;
  63993. },
  63994. enumerable: true,
  63995. configurable: true
  63996. });
  63997. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  63998. get: function () {
  63999. return this._vertexCount;
  64000. },
  64001. enumerable: true,
  64002. configurable: true
  64003. });
  64004. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  64005. get: function () {
  64006. return this._supportsNormals;
  64007. },
  64008. enumerable: true,
  64009. configurable: true
  64010. });
  64011. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  64012. get: function () {
  64013. return this._supportsTangents;
  64014. },
  64015. enumerable: true,
  64016. configurable: true
  64017. });
  64018. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  64019. get: function () {
  64020. return this._targets.length;
  64021. },
  64022. enumerable: true,
  64023. configurable: true
  64024. });
  64025. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  64026. get: function () {
  64027. return this._activeTargets.length;
  64028. },
  64029. enumerable: true,
  64030. configurable: true
  64031. });
  64032. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  64033. get: function () {
  64034. return this._influences;
  64035. },
  64036. enumerable: true,
  64037. configurable: true
  64038. });
  64039. MorphTargetManager.prototype.getActiveTarget = function (index) {
  64040. return this._activeTargets.data[index];
  64041. };
  64042. MorphTargetManager.prototype.getTarget = function (index) {
  64043. return this._targets[index];
  64044. };
  64045. MorphTargetManager.prototype.addTarget = function (target) {
  64046. var _this = this;
  64047. if (this._vertexCount) {
  64048. if (this._vertexCount !== target.getPositions().length / 3) {
  64049. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  64050. return;
  64051. }
  64052. }
  64053. this._targets.push(target);
  64054. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  64055. _this._syncActiveTargets(needUpdate);
  64056. }));
  64057. this._syncActiveTargets(true);
  64058. };
  64059. MorphTargetManager.prototype.removeTarget = function (target) {
  64060. var index = this._targets.indexOf(target);
  64061. if (index >= 0) {
  64062. this._targets.splice(index, 1);
  64063. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  64064. this._vertexCount = 0;
  64065. this._syncActiveTargets(true);
  64066. }
  64067. };
  64068. /**
  64069. * Serializes the current manager into a Serialization object.
  64070. * Returns the serialized object.
  64071. */
  64072. MorphTargetManager.prototype.serialize = function () {
  64073. var serializationObject = {};
  64074. serializationObject.id = this.uniqueId;
  64075. serializationObject.targets = [];
  64076. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64077. var target = _a[_i];
  64078. serializationObject.targets.push(target.serialize());
  64079. }
  64080. return serializationObject;
  64081. };
  64082. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  64083. this._syncActiveTargets(needUpdate);
  64084. };
  64085. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  64086. var influenceCount = 0;
  64087. this._activeTargets.reset();
  64088. this._supportsNormals = true;
  64089. this._supportsTangents = true;
  64090. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64091. var target = _a[_i];
  64092. if (target.influence > 0) {
  64093. this._activeTargets.push(target);
  64094. this._tempInfluences[influenceCount++] = target.influence;
  64095. this._supportsNormals = this._supportsNormals && target.hasNormals;
  64096. this._supportsTangents = this._supportsTangents && target.hasTangents;
  64097. if (this._vertexCount === 0) {
  64098. this._vertexCount = target.getPositions().length / 3;
  64099. }
  64100. }
  64101. }
  64102. if (!this._influences || this._influences.length !== influenceCount) {
  64103. this._influences = new Float32Array(influenceCount);
  64104. }
  64105. for (var index = 0; index < influenceCount; index++) {
  64106. this._influences[index] = this._tempInfluences[index];
  64107. }
  64108. if (needUpdate) {
  64109. // Flag meshes as dirty to resync with the active targets
  64110. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  64111. var mesh = _c[_b];
  64112. if (mesh.morphTargetManager === this) {
  64113. mesh._syncGeometryWithMorphTargetManager();
  64114. }
  64115. }
  64116. }
  64117. };
  64118. // Statics
  64119. MorphTargetManager.Parse = function (serializationObject, scene) {
  64120. var result = new MorphTargetManager(scene);
  64121. result._uniqueId = serializationObject.id;
  64122. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  64123. var targetData = _a[_i];
  64124. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  64125. }
  64126. return result;
  64127. };
  64128. return MorphTargetManager;
  64129. }());
  64130. BABYLON.MorphTargetManager = MorphTargetManager;
  64131. })(BABYLON || (BABYLON = {}));
  64132. //# sourceMappingURL=babylon.morphTargetManager.js.map
  64133. var BABYLON;
  64134. (function (BABYLON) {
  64135. /**
  64136. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  64137. * It can help converting any input color in a desired output one. This can then be used to create effects
  64138. * from sepia, black and white to sixties or futuristic rendering...
  64139. *
  64140. * The only supported format is currently 3dl.
  64141. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  64142. */
  64143. var ColorGradingTexture = (function (_super) {
  64144. __extends(ColorGradingTexture, _super);
  64145. /**
  64146. * Instantiates a ColorGradingTexture from the following parameters.
  64147. *
  64148. * @param url The location of the color gradind data (currently only supporting 3dl)
  64149. * @param scene The scene the texture will be used in
  64150. */
  64151. function ColorGradingTexture(url, scene) {
  64152. var _this = _super.call(this, scene) || this;
  64153. if (!url) {
  64154. return _this;
  64155. }
  64156. _this._textureMatrix = BABYLON.Matrix.Identity();
  64157. _this.name = url;
  64158. _this.url = url;
  64159. _this.hasAlpha = false;
  64160. _this.isCube = false;
  64161. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64162. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64163. _this.anisotropicFilteringLevel = 1;
  64164. _this._texture = _this._getFromCache(url, true);
  64165. if (!_this._texture) {
  64166. if (!scene.useDelayedTextureLoading) {
  64167. _this.loadTexture();
  64168. }
  64169. else {
  64170. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64171. }
  64172. }
  64173. return _this;
  64174. }
  64175. /**
  64176. * Returns the texture matrix used in most of the material.
  64177. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  64178. */
  64179. ColorGradingTexture.prototype.getTextureMatrix = function () {
  64180. return this._textureMatrix;
  64181. };
  64182. /**
  64183. * Occurs when the file being loaded is a .3dl LUT file.
  64184. */
  64185. ColorGradingTexture.prototype.load3dlTexture = function () {
  64186. var _this = this;
  64187. var mipLevels = 0;
  64188. var floatArrayView = null;
  64189. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64190. this._texture = texture;
  64191. var callback = function (text) {
  64192. var data;
  64193. var tempData;
  64194. var line;
  64195. var lines = text.split('\n');
  64196. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  64197. var maxColor = 0;
  64198. for (var i = 0; i < lines.length; i++) {
  64199. line = lines[i];
  64200. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  64201. continue;
  64202. if (line.indexOf('#') === 0)
  64203. continue;
  64204. var words = line.split(" ");
  64205. if (size === 0) {
  64206. // Number of space + one
  64207. size = words.length;
  64208. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  64209. tempData = new Float32Array(size * size * size * 4);
  64210. continue;
  64211. }
  64212. if (size != 0) {
  64213. var r = Math.max(parseInt(words[0]), 0);
  64214. var g = Math.max(parseInt(words[1]), 0);
  64215. var b = Math.max(parseInt(words[2]), 0);
  64216. maxColor = Math.max(r, maxColor);
  64217. maxColor = Math.max(g, maxColor);
  64218. maxColor = Math.max(b, maxColor);
  64219. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  64220. tempData[pixelStorageIndex + 0] = r;
  64221. tempData[pixelStorageIndex + 1] = g;
  64222. tempData[pixelStorageIndex + 2] = b;
  64223. pixelIndexSlice++;
  64224. if (pixelIndexSlice % size == 0) {
  64225. pixelIndexH++;
  64226. pixelIndexSlice = 0;
  64227. if (pixelIndexH % size == 0) {
  64228. pixelIndexW++;
  64229. pixelIndexH = 0;
  64230. }
  64231. }
  64232. }
  64233. }
  64234. for (var i = 0; i < tempData.length; i++) {
  64235. if (i > 0 && (i + 1) % 4 === 0) {
  64236. data[i] = 255;
  64237. }
  64238. else {
  64239. var value = tempData[i];
  64240. data[i] = (value / maxColor * 255);
  64241. }
  64242. }
  64243. texture.updateSize(size * size, size);
  64244. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  64245. };
  64246. BABYLON.Tools.LoadFile(this.url, callback);
  64247. return this._texture;
  64248. };
  64249. /**
  64250. * Starts the loading process of the texture.
  64251. */
  64252. ColorGradingTexture.prototype.loadTexture = function () {
  64253. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  64254. this.load3dlTexture();
  64255. }
  64256. };
  64257. /**
  64258. * Clones the color gradind texture.
  64259. */
  64260. ColorGradingTexture.prototype.clone = function () {
  64261. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  64262. // Base texture
  64263. newTexture.level = this.level;
  64264. return newTexture;
  64265. };
  64266. /**
  64267. * Called during delayed load for textures.
  64268. */
  64269. ColorGradingTexture.prototype.delayLoad = function () {
  64270. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64271. return;
  64272. }
  64273. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64274. this._texture = this._getFromCache(this.url, true);
  64275. if (!this._texture) {
  64276. this.loadTexture();
  64277. }
  64278. };
  64279. /**
  64280. * Parses a color grading texture serialized by Babylon.
  64281. * @param parsedTexture The texture information being parsedTexture
  64282. * @param scene The scene to load the texture in
  64283. * @param rootUrl The root url of the data assets to load
  64284. * @return A color gradind texture
  64285. */
  64286. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64287. var texture = null;
  64288. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64289. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  64290. texture.name = parsedTexture.name;
  64291. texture.level = parsedTexture.level;
  64292. }
  64293. return texture;
  64294. };
  64295. /**
  64296. * Serializes the LUT texture to json format.
  64297. */
  64298. ColorGradingTexture.prototype.serialize = function () {
  64299. if (!this.name) {
  64300. return null;
  64301. }
  64302. var serializationObject = {};
  64303. serializationObject.name = this.name;
  64304. serializationObject.level = this.level;
  64305. serializationObject.customType = "BABYLON.ColorGradingTexture";
  64306. return serializationObject;
  64307. };
  64308. /**
  64309. * Empty line regex stored for GC.
  64310. */
  64311. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  64312. return ColorGradingTexture;
  64313. }(BABYLON.BaseTexture));
  64314. BABYLON.ColorGradingTexture = ColorGradingTexture;
  64315. })(BABYLON || (BABYLON = {}));
  64316. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  64317. var BABYLON;
  64318. (function (BABYLON) {
  64319. /**
  64320. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  64321. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  64322. * 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;
  64323. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  64324. */
  64325. var ColorCurves = (function () {
  64326. function ColorCurves() {
  64327. this._dirty = true;
  64328. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  64329. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  64330. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  64331. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  64332. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  64333. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  64334. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  64335. this._globalHue = 30;
  64336. this._globalDensity = 0;
  64337. this._globalSaturation = 0;
  64338. this._globalExposure = 0;
  64339. this._highlightsHue = 30;
  64340. this._highlightsDensity = 0;
  64341. this._highlightsSaturation = 0;
  64342. this._highlightsExposure = 0;
  64343. this._midtonesHue = 30;
  64344. this._midtonesDensity = 0;
  64345. this._midtonesSaturation = 0;
  64346. this._midtonesExposure = 0;
  64347. this._shadowsHue = 30;
  64348. this._shadowsDensity = 0;
  64349. this._shadowsSaturation = 0;
  64350. this._shadowsExposure = 0;
  64351. }
  64352. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  64353. /**
  64354. * Gets the global Hue value.
  64355. * 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).
  64356. */
  64357. get: function () {
  64358. return this._globalHue;
  64359. },
  64360. /**
  64361. * Sets the global Hue value.
  64362. * 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).
  64363. */
  64364. set: function (value) {
  64365. this._globalHue = value;
  64366. this._dirty = true;
  64367. },
  64368. enumerable: true,
  64369. configurable: true
  64370. });
  64371. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  64372. /**
  64373. * Gets the global Density value.
  64374. * 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.
  64375. * Values less than zero provide a filter of opposite hue.
  64376. */
  64377. get: function () {
  64378. return this._globalDensity;
  64379. },
  64380. /**
  64381. * Sets the global Density value.
  64382. * 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.
  64383. * Values less than zero provide a filter of opposite hue.
  64384. */
  64385. set: function (value) {
  64386. this._globalDensity = value;
  64387. this._dirty = true;
  64388. },
  64389. enumerable: true,
  64390. configurable: true
  64391. });
  64392. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  64393. /**
  64394. * Gets the global Saturation value.
  64395. * 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.
  64396. */
  64397. get: function () {
  64398. return this._globalSaturation;
  64399. },
  64400. /**
  64401. * Sets the global Saturation value.
  64402. * 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.
  64403. */
  64404. set: function (value) {
  64405. this._globalSaturation = value;
  64406. this._dirty = true;
  64407. },
  64408. enumerable: true,
  64409. configurable: true
  64410. });
  64411. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  64412. /**
  64413. * Gets the highlights Hue value.
  64414. * 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).
  64415. */
  64416. get: function () {
  64417. return this._highlightsHue;
  64418. },
  64419. /**
  64420. * Sets the highlights Hue value.
  64421. * 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).
  64422. */
  64423. set: function (value) {
  64424. this._highlightsHue = value;
  64425. this._dirty = true;
  64426. },
  64427. enumerable: true,
  64428. configurable: true
  64429. });
  64430. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  64431. /**
  64432. * Gets the highlights Density value.
  64433. * 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.
  64434. * Values less than zero provide a filter of opposite hue.
  64435. */
  64436. get: function () {
  64437. return this._highlightsDensity;
  64438. },
  64439. /**
  64440. * Sets the highlights Density value.
  64441. * 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.
  64442. * Values less than zero provide a filter of opposite hue.
  64443. */
  64444. set: function (value) {
  64445. this._highlightsDensity = value;
  64446. this._dirty = true;
  64447. },
  64448. enumerable: true,
  64449. configurable: true
  64450. });
  64451. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  64452. /**
  64453. * Gets the highlights Saturation value.
  64454. * 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.
  64455. */
  64456. get: function () {
  64457. return this._highlightsSaturation;
  64458. },
  64459. /**
  64460. * Sets the highlights Saturation value.
  64461. * 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.
  64462. */
  64463. set: function (value) {
  64464. this._highlightsSaturation = value;
  64465. this._dirty = true;
  64466. },
  64467. enumerable: true,
  64468. configurable: true
  64469. });
  64470. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  64471. /**
  64472. * Gets the highlights Exposure value.
  64473. * 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.
  64474. */
  64475. get: function () {
  64476. return this._highlightsExposure;
  64477. },
  64478. /**
  64479. * Sets the highlights Exposure value.
  64480. * 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.
  64481. */
  64482. set: function (value) {
  64483. this._highlightsExposure = value;
  64484. this._dirty = true;
  64485. },
  64486. enumerable: true,
  64487. configurable: true
  64488. });
  64489. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  64490. /**
  64491. * Gets the midtones Hue value.
  64492. * 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).
  64493. */
  64494. get: function () {
  64495. return this._midtonesHue;
  64496. },
  64497. /**
  64498. * Sets the midtones Hue value.
  64499. * 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).
  64500. */
  64501. set: function (value) {
  64502. this._midtonesHue = value;
  64503. this._dirty = true;
  64504. },
  64505. enumerable: true,
  64506. configurable: true
  64507. });
  64508. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  64509. /**
  64510. * Gets the midtones Density value.
  64511. * 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.
  64512. * Values less than zero provide a filter of opposite hue.
  64513. */
  64514. get: function () {
  64515. return this._midtonesDensity;
  64516. },
  64517. /**
  64518. * Sets the midtones Density value.
  64519. * 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.
  64520. * Values less than zero provide a filter of opposite hue.
  64521. */
  64522. set: function (value) {
  64523. this._midtonesDensity = value;
  64524. this._dirty = true;
  64525. },
  64526. enumerable: true,
  64527. configurable: true
  64528. });
  64529. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  64530. /**
  64531. * Gets the midtones Saturation value.
  64532. * 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.
  64533. */
  64534. get: function () {
  64535. return this._midtonesSaturation;
  64536. },
  64537. /**
  64538. * Sets the midtones Saturation value.
  64539. * 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.
  64540. */
  64541. set: function (value) {
  64542. this._midtonesSaturation = value;
  64543. this._dirty = true;
  64544. },
  64545. enumerable: true,
  64546. configurable: true
  64547. });
  64548. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  64549. /**
  64550. * Gets the midtones Exposure value.
  64551. * 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.
  64552. */
  64553. get: function () {
  64554. return this._midtonesExposure;
  64555. },
  64556. /**
  64557. * Sets the midtones Exposure value.
  64558. * 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.
  64559. */
  64560. set: function (value) {
  64561. this._midtonesExposure = value;
  64562. this._dirty = true;
  64563. },
  64564. enumerable: true,
  64565. configurable: true
  64566. });
  64567. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  64568. /**
  64569. * Gets the shadows Hue value.
  64570. * 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).
  64571. */
  64572. get: function () {
  64573. return this._shadowsHue;
  64574. },
  64575. /**
  64576. * Sets the shadows Hue value.
  64577. * 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).
  64578. */
  64579. set: function (value) {
  64580. this._shadowsHue = value;
  64581. this._dirty = true;
  64582. },
  64583. enumerable: true,
  64584. configurable: true
  64585. });
  64586. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  64587. /**
  64588. * Gets the shadows Density value.
  64589. * 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.
  64590. * Values less than zero provide a filter of opposite hue.
  64591. */
  64592. get: function () {
  64593. return this._shadowsDensity;
  64594. },
  64595. /**
  64596. * Sets the shadows Density value.
  64597. * 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.
  64598. * Values less than zero provide a filter of opposite hue.
  64599. */
  64600. set: function (value) {
  64601. this._shadowsDensity = value;
  64602. this._dirty = true;
  64603. },
  64604. enumerable: true,
  64605. configurable: true
  64606. });
  64607. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  64608. /**
  64609. * Gets the shadows Saturation value.
  64610. * 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.
  64611. */
  64612. get: function () {
  64613. return this._shadowsSaturation;
  64614. },
  64615. /**
  64616. * Sets the shadows Saturation value.
  64617. * 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.
  64618. */
  64619. set: function (value) {
  64620. this._shadowsSaturation = value;
  64621. this._dirty = true;
  64622. },
  64623. enumerable: true,
  64624. configurable: true
  64625. });
  64626. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  64627. /**
  64628. * Gets the shadows Exposure value.
  64629. * 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.
  64630. */
  64631. get: function () {
  64632. return this._shadowsExposure;
  64633. },
  64634. /**
  64635. * Sets the shadows Exposure value.
  64636. * 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.
  64637. */
  64638. set: function (value) {
  64639. this._shadowsExposure = value;
  64640. this._dirty = true;
  64641. },
  64642. enumerable: true,
  64643. configurable: true
  64644. });
  64645. ColorCurves.prototype.getClassName = function () {
  64646. return "ColorCurves";
  64647. };
  64648. /**
  64649. * Binds the color curves to the shader.
  64650. * @param colorCurves The color curve to bind
  64651. * @param effect The effect to bind to
  64652. */
  64653. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  64654. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  64655. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  64656. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  64657. if (colorCurves._dirty) {
  64658. colorCurves._dirty = false;
  64659. // Fill in global info.
  64660. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  64661. // Compute highlights info.
  64662. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  64663. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  64664. // Compute midtones info.
  64665. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  64666. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  64667. // Compute shadows info.
  64668. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  64669. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  64670. // Compute deltas (neutral is midtones).
  64671. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  64672. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  64673. }
  64674. if (effect) {
  64675. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  64676. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  64677. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  64678. }
  64679. };
  64680. /**
  64681. * Prepare the list of uniforms associated with the ColorCurves effects.
  64682. * @param uniformsList The list of uniforms used in the effect
  64683. */
  64684. ColorCurves.PrepareUniforms = function (uniformsList) {
  64685. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  64686. };
  64687. /**
  64688. * Returns color grading data based on a hue, density, saturation and exposure value.
  64689. * @param filterHue The hue of the color filter.
  64690. * @param filterDensity The density of the color filter.
  64691. * @param saturation The saturation.
  64692. * @param exposure The exposure.
  64693. * @param result The result data container.
  64694. */
  64695. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  64696. if (hue == null) {
  64697. return;
  64698. }
  64699. hue = ColorCurves.clamp(hue, 0, 360);
  64700. density = ColorCurves.clamp(density, -100, 100);
  64701. saturation = ColorCurves.clamp(saturation, -100, 100);
  64702. exposure = ColorCurves.clamp(exposure, -100, 100);
  64703. // Remap the slider/config filter density with non-linear mapping and also scale by half
  64704. // so that the maximum filter density is only 50% control. This provides fine control
  64705. // for small values and reasonable range.
  64706. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  64707. density *= 0.5;
  64708. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  64709. if (density < 0) {
  64710. density *= -1;
  64711. hue = (hue + 180) % 360;
  64712. }
  64713. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  64714. result.scaleToRef(2, result);
  64715. result.a = 1 + 0.01 * saturation;
  64716. };
  64717. /**
  64718. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  64719. * @param value The input slider value in range [-100,100].
  64720. * @returns Adjusted value.
  64721. */
  64722. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  64723. value /= 100;
  64724. var x = Math.abs(value);
  64725. x = Math.pow(x, 2);
  64726. if (value < 0) {
  64727. x *= -1;
  64728. }
  64729. x *= 100;
  64730. return x;
  64731. };
  64732. /**
  64733. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  64734. * @param hue The hue (H) input.
  64735. * @param saturation The saturation (S) input.
  64736. * @param brightness The brightness (B) input.
  64737. * @result An RGBA color represented as Vector4.
  64738. */
  64739. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  64740. var h = ColorCurves.clamp(hue, 0, 360);
  64741. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  64742. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  64743. if (s === 0) {
  64744. result.r = v;
  64745. result.g = v;
  64746. result.b = v;
  64747. }
  64748. else {
  64749. // sector 0 to 5
  64750. h /= 60;
  64751. var i = Math.floor(h);
  64752. // fractional part of h
  64753. var f = h - i;
  64754. var p = v * (1 - s);
  64755. var q = v * (1 - s * f);
  64756. var t = v * (1 - s * (1 - f));
  64757. switch (i) {
  64758. case 0:
  64759. result.r = v;
  64760. result.g = t;
  64761. result.b = p;
  64762. break;
  64763. case 1:
  64764. result.r = q;
  64765. result.g = v;
  64766. result.b = p;
  64767. break;
  64768. case 2:
  64769. result.r = p;
  64770. result.g = v;
  64771. result.b = t;
  64772. break;
  64773. case 3:
  64774. result.r = p;
  64775. result.g = q;
  64776. result.b = v;
  64777. break;
  64778. case 4:
  64779. result.r = t;
  64780. result.g = p;
  64781. result.b = v;
  64782. break;
  64783. default:// case 5:
  64784. result.r = v;
  64785. result.g = p;
  64786. result.b = q;
  64787. break;
  64788. }
  64789. }
  64790. result.a = 1;
  64791. };
  64792. /**
  64793. * Returns a value clamped between min and max
  64794. * @param value The value to clamp
  64795. * @param min The minimum of value
  64796. * @param max The maximum of value
  64797. * @returns The clamped value.
  64798. */
  64799. ColorCurves.clamp = function (value, min, max) {
  64800. return Math.min(Math.max(value, min), max);
  64801. };
  64802. /**
  64803. * Clones the current color curve instance.
  64804. * @return The cloned curves
  64805. */
  64806. ColorCurves.prototype.clone = function () {
  64807. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  64808. };
  64809. /**
  64810. * Serializes the current color curve instance to a json representation.
  64811. * @return a JSON representation
  64812. */
  64813. ColorCurves.prototype.serialize = function () {
  64814. return BABYLON.SerializationHelper.Serialize(this);
  64815. };
  64816. /**
  64817. * Parses the color curve from a json representation.
  64818. * @param source the JSON source to parse
  64819. * @return The parsed curves
  64820. */
  64821. ColorCurves.Parse = function (source) {
  64822. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  64823. };
  64824. __decorate([
  64825. BABYLON.serialize()
  64826. ], ColorCurves.prototype, "_globalHue", void 0);
  64827. __decorate([
  64828. BABYLON.serialize()
  64829. ], ColorCurves.prototype, "_globalDensity", void 0);
  64830. __decorate([
  64831. BABYLON.serialize()
  64832. ], ColorCurves.prototype, "_globalSaturation", void 0);
  64833. __decorate([
  64834. BABYLON.serialize()
  64835. ], ColorCurves.prototype, "_globalExposure", void 0);
  64836. __decorate([
  64837. BABYLON.serialize()
  64838. ], ColorCurves.prototype, "_highlightsHue", void 0);
  64839. __decorate([
  64840. BABYLON.serialize()
  64841. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  64842. __decorate([
  64843. BABYLON.serialize()
  64844. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  64845. __decorate([
  64846. BABYLON.serialize()
  64847. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  64848. __decorate([
  64849. BABYLON.serialize()
  64850. ], ColorCurves.prototype, "_midtonesHue", void 0);
  64851. __decorate([
  64852. BABYLON.serialize()
  64853. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  64854. __decorate([
  64855. BABYLON.serialize()
  64856. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  64857. __decorate([
  64858. BABYLON.serialize()
  64859. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  64860. return ColorCurves;
  64861. }());
  64862. BABYLON.ColorCurves = ColorCurves;
  64863. })(BABYLON || (BABYLON = {}));
  64864. //# sourceMappingURL=babylon.colorCurves.js.map
  64865. var BABYLON;
  64866. (function (BABYLON) {
  64867. var Octree = (function () {
  64868. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  64869. if (maxDepth === void 0) { maxDepth = 2; }
  64870. this.maxDepth = maxDepth;
  64871. this.dynamicContent = new Array();
  64872. this._maxBlockCapacity = maxBlockCapacity || 64;
  64873. this._selectionContent = new BABYLON.SmartArray(1024);
  64874. this._creationFunc = creationFunc;
  64875. }
  64876. // Methods
  64877. Octree.prototype.update = function (worldMin, worldMax, entries) {
  64878. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  64879. };
  64880. Octree.prototype.addMesh = function (entry) {
  64881. for (var index = 0; index < this.blocks.length; index++) {
  64882. var block = this.blocks[index];
  64883. block.addEntry(entry);
  64884. }
  64885. };
  64886. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  64887. this._selectionContent.reset();
  64888. for (var index = 0; index < this.blocks.length; index++) {
  64889. var block = this.blocks[index];
  64890. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  64891. }
  64892. if (allowDuplicate) {
  64893. this._selectionContent.concat(this.dynamicContent);
  64894. }
  64895. else {
  64896. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64897. }
  64898. return this._selectionContent;
  64899. };
  64900. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  64901. this._selectionContent.reset();
  64902. for (var index = 0; index < this.blocks.length; index++) {
  64903. var block = this.blocks[index];
  64904. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  64905. }
  64906. if (allowDuplicate) {
  64907. this._selectionContent.concat(this.dynamicContent);
  64908. }
  64909. else {
  64910. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64911. }
  64912. return this._selectionContent;
  64913. };
  64914. Octree.prototype.intersectsRay = function (ray) {
  64915. this._selectionContent.reset();
  64916. for (var index = 0; index < this.blocks.length; index++) {
  64917. var block = this.blocks[index];
  64918. block.intersectsRay(ray, this._selectionContent);
  64919. }
  64920. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64921. return this._selectionContent;
  64922. };
  64923. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  64924. target.blocks = new Array();
  64925. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  64926. // Segmenting space
  64927. for (var x = 0; x < 2; x++) {
  64928. for (var y = 0; y < 2; y++) {
  64929. for (var z = 0; z < 2; z++) {
  64930. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  64931. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  64932. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  64933. block.addEntries(entries);
  64934. target.blocks.push(block);
  64935. }
  64936. }
  64937. }
  64938. };
  64939. Octree.CreationFuncForMeshes = function (entry, block) {
  64940. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  64941. block.entries.push(entry);
  64942. }
  64943. };
  64944. Octree.CreationFuncForSubMeshes = function (entry, block) {
  64945. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  64946. block.entries.push(entry);
  64947. }
  64948. };
  64949. return Octree;
  64950. }());
  64951. BABYLON.Octree = Octree;
  64952. })(BABYLON || (BABYLON = {}));
  64953. //# sourceMappingURL=babylon.octree.js.map
  64954. var BABYLON;
  64955. (function (BABYLON) {
  64956. var OctreeBlock = (function () {
  64957. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  64958. this.entries = new Array();
  64959. this._boundingVectors = new Array();
  64960. this._capacity = capacity;
  64961. this._depth = depth;
  64962. this._maxDepth = maxDepth;
  64963. this._creationFunc = creationFunc;
  64964. this._minPoint = minPoint;
  64965. this._maxPoint = maxPoint;
  64966. this._boundingVectors.push(minPoint.clone());
  64967. this._boundingVectors.push(maxPoint.clone());
  64968. this._boundingVectors.push(minPoint.clone());
  64969. this._boundingVectors[2].x = maxPoint.x;
  64970. this._boundingVectors.push(minPoint.clone());
  64971. this._boundingVectors[3].y = maxPoint.y;
  64972. this._boundingVectors.push(minPoint.clone());
  64973. this._boundingVectors[4].z = maxPoint.z;
  64974. this._boundingVectors.push(maxPoint.clone());
  64975. this._boundingVectors[5].z = minPoint.z;
  64976. this._boundingVectors.push(maxPoint.clone());
  64977. this._boundingVectors[6].x = minPoint.x;
  64978. this._boundingVectors.push(maxPoint.clone());
  64979. this._boundingVectors[7].y = minPoint.y;
  64980. }
  64981. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  64982. // Property
  64983. get: function () {
  64984. return this._capacity;
  64985. },
  64986. enumerable: true,
  64987. configurable: true
  64988. });
  64989. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  64990. get: function () {
  64991. return this._minPoint;
  64992. },
  64993. enumerable: true,
  64994. configurable: true
  64995. });
  64996. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  64997. get: function () {
  64998. return this._maxPoint;
  64999. },
  65000. enumerable: true,
  65001. configurable: true
  65002. });
  65003. // Methods
  65004. OctreeBlock.prototype.addEntry = function (entry) {
  65005. if (this.blocks) {
  65006. for (var index = 0; index < this.blocks.length; index++) {
  65007. var block = this.blocks[index];
  65008. block.addEntry(entry);
  65009. }
  65010. return;
  65011. }
  65012. this._creationFunc(entry, this);
  65013. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  65014. this.createInnerBlocks();
  65015. }
  65016. };
  65017. OctreeBlock.prototype.addEntries = function (entries) {
  65018. for (var index = 0; index < entries.length; index++) {
  65019. var mesh = entries[index];
  65020. this.addEntry(mesh);
  65021. }
  65022. };
  65023. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  65024. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  65025. if (this.blocks) {
  65026. for (var index = 0; index < this.blocks.length; index++) {
  65027. var block = this.blocks[index];
  65028. block.select(frustumPlanes, selection, allowDuplicate);
  65029. }
  65030. return;
  65031. }
  65032. if (allowDuplicate) {
  65033. selection.concat(this.entries);
  65034. }
  65035. else {
  65036. selection.concatWithNoDuplicate(this.entries);
  65037. }
  65038. }
  65039. };
  65040. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  65041. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  65042. if (this.blocks) {
  65043. for (var index = 0; index < this.blocks.length; index++) {
  65044. var block = this.blocks[index];
  65045. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  65046. }
  65047. return;
  65048. }
  65049. if (allowDuplicate) {
  65050. selection.concat(this.entries);
  65051. }
  65052. else {
  65053. selection.concatWithNoDuplicate(this.entries);
  65054. }
  65055. }
  65056. };
  65057. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  65058. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  65059. if (this.blocks) {
  65060. for (var index = 0; index < this.blocks.length; index++) {
  65061. var block = this.blocks[index];
  65062. block.intersectsRay(ray, selection);
  65063. }
  65064. return;
  65065. }
  65066. selection.concatWithNoDuplicate(this.entries);
  65067. }
  65068. };
  65069. OctreeBlock.prototype.createInnerBlocks = function () {
  65070. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  65071. };
  65072. return OctreeBlock;
  65073. }());
  65074. BABYLON.OctreeBlock = OctreeBlock;
  65075. })(BABYLON || (BABYLON = {}));
  65076. //# sourceMappingURL=babylon.octreeBlock.js.map
  65077. var BABYLON;
  65078. (function (BABYLON) {
  65079. var SIMDVector3 = (function () {
  65080. function SIMDVector3() {
  65081. }
  65082. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  65083. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  65084. };
  65085. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  65086. var m = transformation.m;
  65087. var m0 = SIMD.Float32x4.load(m, 0);
  65088. var m1 = SIMD.Float32x4.load(m, 4);
  65089. var m2 = SIMD.Float32x4.load(m, 8);
  65090. var m3 = SIMD.Float32x4.load(m, 12);
  65091. 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));
  65092. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  65093. result.x = SIMD.Float32x4.extractLane(r, 0);
  65094. result.y = SIMD.Float32x4.extractLane(r, 1);
  65095. result.z = SIMD.Float32x4.extractLane(r, 2);
  65096. };
  65097. return SIMDVector3;
  65098. }());
  65099. var SIMDMatrix = (function () {
  65100. function SIMDMatrix() {
  65101. }
  65102. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  65103. var tm = this.m;
  65104. var om = other.m;
  65105. var m0 = SIMD.Float32x4.load(om, 0);
  65106. var m1 = SIMD.Float32x4.load(om, 4);
  65107. var m2 = SIMD.Float32x4.load(om, 8);
  65108. var m3 = SIMD.Float32x4.load(om, 12);
  65109. for (var i = 0; i < 16; i += 4) {
  65110. 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)))));
  65111. }
  65112. return this;
  65113. };
  65114. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  65115. var src = this.m;
  65116. var dest = other.m;
  65117. // Load the 4 rows
  65118. var src0 = SIMD.Float32x4.load(src, 0);
  65119. var src1 = SIMD.Float32x4.load(src, 4);
  65120. var src2 = SIMD.Float32x4.load(src, 8);
  65121. var src3 = SIMD.Float32x4.load(src, 12);
  65122. // Transpose the source matrix. Sort of. Not a true transpose operation
  65123. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  65124. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  65125. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  65126. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  65127. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  65128. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  65129. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  65130. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  65131. // This is a true transposition, but it will lead to an incorrect result
  65132. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  65133. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  65134. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65135. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65136. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  65137. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  65138. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65139. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65140. // ----
  65141. tmp1 = SIMD.Float32x4.mul(row2, row3);
  65142. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65143. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  65144. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  65145. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65146. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  65147. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  65148. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  65149. // ----
  65150. tmp1 = SIMD.Float32x4.mul(row1, row2);
  65151. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65152. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  65153. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  65154. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65155. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  65156. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  65157. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  65158. // ----
  65159. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  65160. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65161. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  65162. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  65163. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  65164. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65165. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  65166. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  65167. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  65168. // ----
  65169. tmp1 = SIMD.Float32x4.mul(row0, row1);
  65170. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65171. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  65172. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  65173. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65174. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  65175. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  65176. // ----
  65177. tmp1 = SIMD.Float32x4.mul(row0, row3);
  65178. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65179. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  65180. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  65181. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65182. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  65183. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  65184. // ----
  65185. tmp1 = SIMD.Float32x4.mul(row0, row2);
  65186. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65187. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  65188. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  65189. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65190. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  65191. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  65192. // Compute determinant
  65193. var det = SIMD.Float32x4.mul(row0, minor0);
  65194. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  65195. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  65196. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  65197. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  65198. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  65199. // These shuffles aren't necessary if the faulty transposition is done
  65200. // up at the top of this function.
  65201. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  65202. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  65203. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  65204. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  65205. // Compute final values by multiplying with 1/det
  65206. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  65207. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  65208. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  65209. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  65210. return this;
  65211. };
  65212. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  65213. var out = result.m;
  65214. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  65215. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  65216. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  65217. // cc.kmVec3Subtract(f, pCenter, pEye);
  65218. var f = SIMD.Float32x4.sub(center, eye);
  65219. // cc.kmVec3Normalize(f, f);
  65220. var tmp = SIMD.Float32x4.mul(f, f);
  65221. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65222. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65223. // cc.kmVec3Assign(up, pUp);
  65224. // cc.kmVec3Normalize(up, up);
  65225. tmp = SIMD.Float32x4.mul(up, up);
  65226. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65227. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65228. // cc.kmVec3Cross(s, f, up);
  65229. 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)));
  65230. // cc.kmVec3Normalize(s, s);
  65231. tmp = SIMD.Float32x4.mul(s, s);
  65232. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65233. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65234. // cc.kmVec3Cross(u, s, f);
  65235. 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)));
  65236. // cc.kmVec3Normalize(s, s);
  65237. tmp = SIMD.Float32x4.mul(s, s);
  65238. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65239. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65240. var zero = SIMD.Float32x4.splat(0.0);
  65241. s = SIMD.Float32x4.neg(s);
  65242. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  65243. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  65244. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  65245. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  65246. 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);
  65247. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  65248. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  65249. 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)))));
  65250. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  65251. 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)))));
  65252. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  65253. 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)))));
  65254. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  65255. 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)))));
  65256. };
  65257. return SIMDMatrix;
  65258. }());
  65259. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  65260. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  65261. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  65262. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  65263. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  65264. var SIMDHelper = (function () {
  65265. function SIMDHelper() {
  65266. }
  65267. Object.defineProperty(SIMDHelper, "IsEnabled", {
  65268. get: function () {
  65269. return SIMDHelper._isEnabled;
  65270. },
  65271. enumerable: true,
  65272. configurable: true
  65273. });
  65274. SIMDHelper.DisableSIMD = function () {
  65275. // Replace functions
  65276. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  65277. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  65278. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  65279. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  65280. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  65281. SIMDHelper._isEnabled = false;
  65282. };
  65283. SIMDHelper.EnableSIMD = function () {
  65284. if (self.SIMD === undefined) {
  65285. return;
  65286. }
  65287. // check if polyfills needed
  65288. if (!self.Math.fround) {
  65289. self.Math.fround = (function (array) { return function (x) {
  65290. return array[0] = x, array[0];
  65291. }; })(new Float32Array(1));
  65292. }
  65293. if (!self.Math.imul) {
  65294. self.Math.imul = function (a, b) {
  65295. var ah = (a >>> 16) & 0xffff;
  65296. var al = a & 0xffff;
  65297. var bh = (b >>> 16) & 0xffff;
  65298. var bl = b & 0xffff;
  65299. // the shift by 0 fixes the sign on the high part
  65300. // the final |0 converts the unsigned value into a signed value
  65301. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  65302. };
  65303. }
  65304. // Replace functions
  65305. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  65306. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  65307. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  65308. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  65309. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  65310. SIMDHelper._isEnabled = true;
  65311. };
  65312. SIMDHelper._isEnabled = false;
  65313. return SIMDHelper;
  65314. }());
  65315. BABYLON.SIMDHelper = SIMDHelper;
  65316. })(BABYLON || (BABYLON = {}));
  65317. //# sourceMappingURL=babylon.math.SIMD.js.map
  65318. var BABYLON;
  65319. (function (BABYLON) {
  65320. var VRDistortionCorrectionPostProcess = (function (_super) {
  65321. __extends(VRDistortionCorrectionPostProcess, _super);
  65322. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  65323. var _this = _super.call(this, name, "vrDistortionCorrection", [
  65324. 'LensCenter',
  65325. 'Scale',
  65326. 'ScaleIn',
  65327. 'HmdWarpParam'
  65328. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  65329. _this._isRightEye = isRightEye;
  65330. _this._distortionFactors = vrMetrics.distortionK;
  65331. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  65332. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  65333. _this.adaptScaleToCurrentViewport = true;
  65334. _this.onSizeChangedObservable.add(function () {
  65335. _this.aspectRatio = _this.width * .5 / _this.height;
  65336. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  65337. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  65338. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  65339. });
  65340. _this.onApplyObservable.add(function (effect) {
  65341. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  65342. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  65343. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  65344. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  65345. });
  65346. return _this;
  65347. }
  65348. return VRDistortionCorrectionPostProcess;
  65349. }(BABYLON.PostProcess));
  65350. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  65351. })(BABYLON || (BABYLON = {}));
  65352. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  65353. var BABYLON;
  65354. (function (BABYLON) {
  65355. var AnaglyphPostProcess = (function (_super) {
  65356. __extends(AnaglyphPostProcess, _super);
  65357. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  65358. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  65359. _this._passedProcess = rigCameras[0]._rigPostProcess;
  65360. _this.onApplyObservable.add(function (effect) {
  65361. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  65362. });
  65363. return _this;
  65364. }
  65365. return AnaglyphPostProcess;
  65366. }(BABYLON.PostProcess));
  65367. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  65368. })(BABYLON || (BABYLON = {}));
  65369. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  65370. var BABYLON;
  65371. (function (BABYLON) {
  65372. var StereoscopicInterlacePostProcess = (function (_super) {
  65373. __extends(StereoscopicInterlacePostProcess, _super);
  65374. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  65375. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  65376. _this._passedProcess = rigCameras[0]._rigPostProcess;
  65377. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  65378. _this.onSizeChangedObservable.add(function () {
  65379. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  65380. });
  65381. _this.onApplyObservable.add(function (effect) {
  65382. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  65383. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  65384. });
  65385. return _this;
  65386. }
  65387. return StereoscopicInterlacePostProcess;
  65388. }(BABYLON.PostProcess));
  65389. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  65390. })(BABYLON || (BABYLON = {}));
  65391. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  65392. var BABYLON;
  65393. (function (BABYLON) {
  65394. var FreeCameraDeviceOrientationInput = (function () {
  65395. function FreeCameraDeviceOrientationInput() {
  65396. var _this = this;
  65397. this._screenOrientationAngle = 0;
  65398. this._screenQuaternion = new BABYLON.Quaternion();
  65399. this._alpha = 0;
  65400. this._beta = 0;
  65401. this._gamma = 0;
  65402. this._orientationChanged = function () {
  65403. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  65404. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  65405. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  65406. };
  65407. this._deviceOrientation = function (evt) {
  65408. _this._alpha = evt.alpha;
  65409. _this._beta = evt.beta;
  65410. _this._gamma = evt.gamma;
  65411. };
  65412. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  65413. this._orientationChanged();
  65414. }
  65415. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  65416. get: function () {
  65417. return this._camera;
  65418. },
  65419. set: function (camera) {
  65420. this._camera = camera;
  65421. if (this._camera != null && !this._camera.rotationQuaternion) {
  65422. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  65423. }
  65424. },
  65425. enumerable: true,
  65426. configurable: true
  65427. });
  65428. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  65429. window.addEventListener("orientationchange", this._orientationChanged);
  65430. window.addEventListener("deviceorientation", this._deviceOrientation);
  65431. //In certain cases, the attach control is called AFTER orientation was changed,
  65432. //So this is needed.
  65433. this._orientationChanged();
  65434. };
  65435. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  65436. window.removeEventListener("orientationchange", this._orientationChanged);
  65437. window.removeEventListener("deviceorientation", this._deviceOrientation);
  65438. };
  65439. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  65440. //if no device orientation provided, don't update the rotation.
  65441. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  65442. if (!this._alpha)
  65443. return;
  65444. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  65445. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  65446. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  65447. //Mirror on XY Plane
  65448. this._camera.rotationQuaternion.z *= -1;
  65449. this._camera.rotationQuaternion.w *= -1;
  65450. };
  65451. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  65452. return "FreeCameraDeviceOrientationInput";
  65453. };
  65454. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  65455. return "deviceOrientation";
  65456. };
  65457. return FreeCameraDeviceOrientationInput;
  65458. }());
  65459. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  65460. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  65461. })(BABYLON || (BABYLON = {}));
  65462. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  65463. var BABYLON;
  65464. (function (BABYLON) {
  65465. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  65466. function ArcRotateCameraVRDeviceOrientationInput() {
  65467. this.alphaCorrection = 1;
  65468. this.betaCorrection = 1;
  65469. this.gammaCorrection = 1;
  65470. this._alpha = 0;
  65471. this._beta = 0;
  65472. this._gamma = 0;
  65473. this._dirty = false;
  65474. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  65475. }
  65476. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  65477. this.camera.attachControl(element, noPreventDefault);
  65478. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  65479. };
  65480. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  65481. var camera = this.camera;
  65482. this._alpha = +evt.alpha | 0;
  65483. this._beta = +evt.beta | 0;
  65484. this._gamma = +evt.gamma | 0;
  65485. this._dirty = true;
  65486. };
  65487. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  65488. if (this._dirty) {
  65489. this._dirty = false;
  65490. if (this._gamma < 0) {
  65491. this._gamma = 180 + this._gamma;
  65492. }
  65493. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  65494. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  65495. }
  65496. };
  65497. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  65498. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  65499. };
  65500. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  65501. return "ArcRotateCameraVRDeviceOrientationInput";
  65502. };
  65503. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  65504. return "VRDeviceOrientation";
  65505. };
  65506. return ArcRotateCameraVRDeviceOrientationInput;
  65507. }());
  65508. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  65509. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  65510. })(BABYLON || (BABYLON = {}));
  65511. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  65512. var BABYLON;
  65513. (function (BABYLON) {
  65514. var VRCameraMetrics = (function () {
  65515. function VRCameraMetrics() {
  65516. this.compensateDistortion = true;
  65517. }
  65518. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  65519. get: function () {
  65520. return this.hResolution / (2 * this.vResolution);
  65521. },
  65522. enumerable: true,
  65523. configurable: true
  65524. });
  65525. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  65526. get: function () {
  65527. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  65528. },
  65529. enumerable: true,
  65530. configurable: true
  65531. });
  65532. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  65533. get: function () {
  65534. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  65535. var h = (4 * meters) / this.hScreenSize;
  65536. return BABYLON.Matrix.Translation(h, 0, 0);
  65537. },
  65538. enumerable: true,
  65539. configurable: true
  65540. });
  65541. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  65542. get: function () {
  65543. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  65544. var h = (4 * meters) / this.hScreenSize;
  65545. return BABYLON.Matrix.Translation(-h, 0, 0);
  65546. },
  65547. enumerable: true,
  65548. configurable: true
  65549. });
  65550. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  65551. get: function () {
  65552. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  65553. },
  65554. enumerable: true,
  65555. configurable: true
  65556. });
  65557. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  65558. get: function () {
  65559. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  65560. },
  65561. enumerable: true,
  65562. configurable: true
  65563. });
  65564. VRCameraMetrics.GetDefault = function () {
  65565. var result = new VRCameraMetrics();
  65566. result.hResolution = 1280;
  65567. result.vResolution = 800;
  65568. result.hScreenSize = 0.149759993;
  65569. result.vScreenSize = 0.0935999975;
  65570. result.vScreenCenter = 0.0467999987;
  65571. result.eyeToScreenDistance = 0.0410000011;
  65572. result.lensSeparationDistance = 0.0635000020;
  65573. result.interpupillaryDistance = 0.0640000030;
  65574. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  65575. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  65576. result.postProcessScaleFactor = 1.714605507808412;
  65577. result.lensCenterOffset = 0.151976421;
  65578. return result;
  65579. };
  65580. return VRCameraMetrics;
  65581. }());
  65582. BABYLON.VRCameraMetrics = VRCameraMetrics;
  65583. })(BABYLON || (BABYLON = {}));
  65584. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  65585. var BABYLON;
  65586. (function (BABYLON) {
  65587. var WebVRFreeCamera = (function (_super) {
  65588. __extends(WebVRFreeCamera, _super);
  65589. function WebVRFreeCamera(name, position, scene, webVROptions) {
  65590. if (webVROptions === void 0) { webVROptions = {}; }
  65591. var _this = _super.call(this, name, position, scene) || this;
  65592. _this.webVROptions = webVROptions;
  65593. _this._vrDevice = null;
  65594. _this.rawPose = null;
  65595. _this._vrEnabled = false;
  65596. _this._specsVersion = 1.1;
  65597. _this._attached = false;
  65598. _this._positionOffset = BABYLON.Vector3.Zero();
  65599. _this._descendants = [];
  65600. _this.devicePosition = BABYLON.Vector3.Zero();
  65601. _this.deviceScaleFactor = 1;
  65602. _this.controllers = [];
  65603. _this.onControllersAttachedObservable = new BABYLON.Observable();
  65604. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  65605. _this.minZ = 0.1;
  65606. //legacy support - the compensation boolean was removed.
  65607. if (arguments.length === 5) {
  65608. _this.webVROptions = arguments[4];
  65609. }
  65610. // default webVR options
  65611. if (_this.webVROptions.trackPosition == undefined) {
  65612. _this.webVROptions.trackPosition = true;
  65613. }
  65614. if (_this.webVROptions.controllerMeshes == undefined) {
  65615. _this.webVROptions.controllerMeshes = true;
  65616. }
  65617. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  65618. _this.webVROptions.defaultLightingOnControllers = true;
  65619. }
  65620. _this.rotationQuaternion = new BABYLON.Quaternion();
  65621. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65622. if (_this.webVROptions && _this.webVROptions.positionScale) {
  65623. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  65624. }
  65625. //enable VR
  65626. _this.getEngine().initWebVR();
  65627. //check specs version
  65628. if (!window.VRFrameData) {
  65629. _this._specsVersion = 1.0;
  65630. _this._frameData = {};
  65631. }
  65632. else {
  65633. _this._frameData = new VRFrameData();
  65634. }
  65635. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  65636. if (!device) {
  65637. return;
  65638. }
  65639. _this._vrEnabled = true;
  65640. _this._vrDevice = device;
  65641. //reset the rig parameters.
  65642. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  65643. if (_this._attached) {
  65644. _this.getEngine().enableVR(_this._vrDevice);
  65645. }
  65646. });
  65647. /**
  65648. * The idea behind the following lines:
  65649. * objects that have the camera as parent should actually have the rig cameras as a parent.
  65650. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  65651. * the second will not show it correctly.
  65652. *
  65653. * To solve this - each object that has the camera as parent will be added to a protected array.
  65654. * When the rig camera renders, it will take this array and set all of those to be its children.
  65655. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  65656. * Amazing!
  65657. */
  65658. scene.onBeforeCameraRenderObservable.add(function (camera) {
  65659. if (camera.parent === _this && _this.rigParenting) {
  65660. _this._descendants = _this.getDescendants(true, function (n) {
  65661. // don't take the cameras or the controllers!
  65662. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  65663. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  65664. return !isController && !isRigCamera;
  65665. });
  65666. _this._descendants.forEach(function (node) {
  65667. node.parent = camera;
  65668. });
  65669. }
  65670. });
  65671. scene.onAfterCameraRenderObservable.add(function (camera) {
  65672. if (camera.parent === _this && _this.rigParenting) {
  65673. _this._descendants.forEach(function (node) {
  65674. node.parent = _this;
  65675. });
  65676. }
  65677. });
  65678. return _this;
  65679. }
  65680. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  65681. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  65682. var gp = _a[_i];
  65683. if (gp.hand === name) {
  65684. return gp;
  65685. }
  65686. }
  65687. return undefined;
  65688. };
  65689. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  65690. get: function () {
  65691. if (!this._leftController) {
  65692. this._leftController = this.getControllerByName("left");
  65693. }
  65694. return this._leftController;
  65695. },
  65696. enumerable: true,
  65697. configurable: true
  65698. });
  65699. ;
  65700. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  65701. get: function () {
  65702. if (!this._rightController) {
  65703. this._rightController = this.getControllerByName("right");
  65704. }
  65705. return this._rightController;
  65706. },
  65707. enumerable: true,
  65708. configurable: true
  65709. });
  65710. ;
  65711. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  65712. if (length === void 0) { length = 100; }
  65713. if (this.leftCamera) {
  65714. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  65715. }
  65716. else {
  65717. return _super.prototype.getForwardRay.call(this, length);
  65718. }
  65719. };
  65720. WebVRFreeCamera.prototype._checkInputs = function () {
  65721. if (this._vrEnabled) {
  65722. if (this._specsVersion === 1.1) {
  65723. this._vrDevice.getFrameData(this._frameData);
  65724. }
  65725. else {
  65726. //backwards comp
  65727. var pose = this._vrDevice.getPose();
  65728. this._frameData.pose = pose;
  65729. }
  65730. this.updateFromDevice(this._frameData.pose);
  65731. }
  65732. _super.prototype._checkInputs.call(this);
  65733. };
  65734. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  65735. if (poseData && poseData.orientation) {
  65736. this.rawPose = poseData;
  65737. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  65738. if (this.getScene().useRightHandedSystem) {
  65739. this.deviceRotationQuaternion.z *= -1;
  65740. this.deviceRotationQuaternion.w *= -1;
  65741. }
  65742. if (this.webVROptions.trackPosition && this.rawPose.position) {
  65743. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  65744. if (this.getScene().useRightHandedSystem) {
  65745. this.devicePosition.z *= -1;
  65746. }
  65747. }
  65748. }
  65749. };
  65750. /**
  65751. * WebVR's attach control will start broadcasting frames to the device.
  65752. * Note that in certain browsers (chrome for example) this function must be called
  65753. * within a user-interaction callback. Example:
  65754. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  65755. *
  65756. * @param {HTMLElement} element
  65757. * @param {boolean} [noPreventDefault]
  65758. *
  65759. * @memberOf WebVRFreeCamera
  65760. */
  65761. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  65762. _super.prototype.attachControl.call(this, element, noPreventDefault);
  65763. this._attached = true;
  65764. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  65765. if (this._vrEnabled) {
  65766. this.getEngine().enableVR(this._vrDevice);
  65767. }
  65768. // try to attach the controllers, if found.
  65769. this.initControllers();
  65770. };
  65771. WebVRFreeCamera.prototype.detachControl = function (element) {
  65772. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65773. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65774. _super.prototype.detachControl.call(this, element);
  65775. this._vrEnabled = false;
  65776. this._attached = false;
  65777. this.getEngine().disableVR();
  65778. };
  65779. WebVRFreeCamera.prototype.getClassName = function () {
  65780. return "WebVRFreeCamera";
  65781. };
  65782. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  65783. //uses the vrDisplay's "resetPose()".
  65784. //pitch and roll won't be affected.
  65785. this._vrDevice.resetPose();
  65786. };
  65787. WebVRFreeCamera.prototype._updateRigCameras = function () {
  65788. var camLeft = this._rigCameras[0];
  65789. var camRight = this._rigCameras[1];
  65790. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65791. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65792. camLeft.position.copyFrom(this.devicePosition);
  65793. camRight.position.copyFrom(this.devicePosition);
  65794. };
  65795. /**
  65796. * This function is called by the two RIG cameras.
  65797. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  65798. */
  65799. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  65800. var _this = this;
  65801. //WebVR 1.0
  65802. if (this._cameraRigParams["specs"] === 1.0) {
  65803. this._updateCameraRotationMatrix();
  65804. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  65805. // Computing target and final matrix
  65806. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  65807. if (this.getScene().useRightHandedSystem) {
  65808. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  65809. }
  65810. else {
  65811. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  65812. }
  65813. //now move the eye in the right direction
  65814. var eyeParams = this._cameraRigParams["eyeParameters"];
  65815. var offset = eyeParams.offset;
  65816. // it will actually always be 0, but just in case
  65817. if (this.getScene().useRightHandedSystem) {
  65818. offset[2] *= -1;
  65819. }
  65820. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  65821. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  65822. }
  65823. else {
  65824. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  65825. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  65826. if (!this.getScene().useRightHandedSystem) {
  65827. [2, 6, 8, 9, 14].forEach(function (num) {
  65828. _this._webvrViewMatrix.m[num] *= -1;
  65829. });
  65830. }
  65831. // update the camera rotation matrix
  65832. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  65833. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  65834. // Computing target and final matrix
  65835. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  65836. }
  65837. var parentCamera = this._cameraRigParams["parentCamera"];
  65838. // should the view matrix be updated with scale and position offset?
  65839. if (parentCamera.deviceScaleFactor !== 1) {
  65840. this._webvrViewMatrix.invert();
  65841. // scale the position, if set
  65842. if (parentCamera.deviceScaleFactor) {
  65843. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  65844. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  65845. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  65846. }
  65847. this._webvrViewMatrix.invert();
  65848. }
  65849. return this._webvrViewMatrix;
  65850. };
  65851. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  65852. var _this = this;
  65853. if (this._cameraRigParams["specs"] === 1.0) {
  65854. var eyeParams = this._cameraRigParams["eyeParameters"];
  65855. // deprecated!!
  65856. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, this.minZ, this.maxZ, this._projectionMatrix, this.getScene().useRightHandedSystem);
  65857. }
  65858. else {
  65859. var parentCamera = this.parent;
  65860. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  65861. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  65862. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  65863. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  65864. //babylon compatible matrix
  65865. if (!this.getScene().useRightHandedSystem) {
  65866. [8, 9, 10, 11].forEach(function (num) {
  65867. _this._projectionMatrix.m[num] *= -1;
  65868. });
  65869. }
  65870. }
  65871. return this._projectionMatrix;
  65872. };
  65873. WebVRFreeCamera.prototype.initControllers = function () {
  65874. var _this = this;
  65875. this.controllers = [];
  65876. var manager = this.getScene().gamepadManager;
  65877. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65878. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  65879. var webVrController = gamepad;
  65880. var index = _this.controllers.indexOf(webVrController);
  65881. if (index === -1) {
  65882. // we are good
  65883. return;
  65884. }
  65885. _this.controllers.splice(index, 1);
  65886. }
  65887. });
  65888. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65889. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  65890. var webVrController = gamepad;
  65891. if (_this.webVROptions.controllerMeshes) {
  65892. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  65893. if (_this.webVROptions.defaultLightingOnControllers) {
  65894. if (!_this._lightOnControllers) {
  65895. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  65896. }
  65897. var activateLightOnSubMeshes_1 = function (mesh, light) {
  65898. var children = mesh.getChildren();
  65899. if (children.length !== 0) {
  65900. children.forEach(function (mesh) {
  65901. light.includedOnlyMeshes.push(mesh);
  65902. activateLightOnSubMeshes_1(mesh, light);
  65903. });
  65904. }
  65905. };
  65906. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  65907. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  65908. }
  65909. });
  65910. }
  65911. webVrController.attachToPoseControlledCamera(_this);
  65912. // since this is async - sanity check. Is the controller already stored?
  65913. if (_this.controllers.indexOf(webVrController) === -1) {
  65914. //add to the controllers array
  65915. _this.controllers.push(webVrController);
  65916. //did we find enough controllers? Great! let the developer know.
  65917. if (_this.controllers.length >= 2) {
  65918. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  65919. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  65920. // So we're overriding setting left & right manually to be sure
  65921. var firstViveWandDetected = false;
  65922. for (var i = 0; i < _this.controllers.length; i++) {
  65923. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  65924. if (!firstViveWandDetected) {
  65925. firstViveWandDetected = true;
  65926. _this.controllers[i].hand = "left";
  65927. }
  65928. else {
  65929. _this.controllers[i].hand = "right";
  65930. }
  65931. }
  65932. }
  65933. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  65934. }
  65935. }
  65936. }
  65937. });
  65938. };
  65939. return WebVRFreeCamera;
  65940. }(BABYLON.FreeCamera));
  65941. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  65942. })(BABYLON || (BABYLON = {}));
  65943. //# sourceMappingURL=babylon.webVRCamera.js.map
  65944. /// <reference path="babylon.freeCamera.ts" />
  65945. var BABYLON;
  65946. (function (BABYLON) {
  65947. // We're mainly based on the logic defined into the FreeCamera code
  65948. var DeviceOrientationCamera = (function (_super) {
  65949. __extends(DeviceOrientationCamera, _super);
  65950. function DeviceOrientationCamera(name, position, scene) {
  65951. var _this = _super.call(this, name, position, scene) || this;
  65952. _this._quaternionCache = new BABYLON.Quaternion();
  65953. _this.inputs.addDeviceOrientation();
  65954. return _this;
  65955. }
  65956. DeviceOrientationCamera.prototype.getClassName = function () {
  65957. return "DeviceOrientationCamera";
  65958. };
  65959. DeviceOrientationCamera.prototype._checkInputs = function () {
  65960. _super.prototype._checkInputs.call(this);
  65961. this._quaternionCache.copyFrom(this.rotationQuaternion);
  65962. if (this._initialQuaternion) {
  65963. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  65964. }
  65965. };
  65966. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  65967. var _this = this;
  65968. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  65969. //can only work if this camera has a rotation quaternion already.
  65970. if (!this.rotationQuaternion)
  65971. return;
  65972. if (!this._initialQuaternion) {
  65973. this._initialQuaternion = new BABYLON.Quaternion();
  65974. }
  65975. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  65976. ['x', 'y', 'z'].forEach(function (axisName) {
  65977. if (!axis[axisName]) {
  65978. _this._initialQuaternion[axisName] = 0;
  65979. }
  65980. else {
  65981. _this._initialQuaternion[axisName] *= -1;
  65982. }
  65983. });
  65984. this._initialQuaternion.normalize();
  65985. //force rotation update
  65986. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  65987. };
  65988. return DeviceOrientationCamera;
  65989. }(BABYLON.FreeCamera));
  65990. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  65991. })(BABYLON || (BABYLON = {}));
  65992. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  65993. var BABYLON;
  65994. (function (BABYLON) {
  65995. var VRDeviceOrientationFreeCamera = (function (_super) {
  65996. __extends(VRDeviceOrientationFreeCamera, _super);
  65997. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  65998. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65999. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66000. var _this = _super.call(this, name, position, scene) || this;
  66001. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66002. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66003. return _this;
  66004. }
  66005. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  66006. return "VRDeviceOrientationFreeCamera";
  66007. };
  66008. return VRDeviceOrientationFreeCamera;
  66009. }(BABYLON.DeviceOrientationCamera));
  66010. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  66011. var VRDeviceOrientationGamepadCamera = (function (_super) {
  66012. __extends(VRDeviceOrientationGamepadCamera, _super);
  66013. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  66014. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66015. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66016. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  66017. _this.inputs.addGamepad();
  66018. return _this;
  66019. }
  66020. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  66021. return "VRDeviceOrientationGamepadCamera";
  66022. };
  66023. return VRDeviceOrientationGamepadCamera;
  66024. }(VRDeviceOrientationFreeCamera));
  66025. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  66026. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  66027. __extends(VRDeviceOrientationArcRotateCamera, _super);
  66028. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  66029. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66030. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66031. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66032. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66033. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66034. _this.inputs.addVRDeviceOrientation();
  66035. return _this;
  66036. }
  66037. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  66038. return "VRDeviceOrientationArcRotateCamera";
  66039. };
  66040. return VRDeviceOrientationArcRotateCamera;
  66041. }(BABYLON.ArcRotateCamera));
  66042. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  66043. })(BABYLON || (BABYLON = {}));
  66044. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  66045. /// <reference path="babylon.freeCamera.ts" />
  66046. /// <reference path="babylon.arcRotateCamera.ts" />
  66047. /// <reference path="babylon.gamepadCamera.ts" />
  66048. /// <reference path="babylon.universalCamera.ts" />
  66049. var BABYLON;
  66050. (function (BABYLON) {
  66051. var AnaglyphFreeCamera = (function (_super) {
  66052. __extends(AnaglyphFreeCamera, _super);
  66053. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  66054. var _this = _super.call(this, name, position, scene) || this;
  66055. _this.interaxialDistance = interaxialDistance;
  66056. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66057. return _this;
  66058. }
  66059. AnaglyphFreeCamera.prototype.getClassName = function () {
  66060. return "AnaglyphFreeCamera";
  66061. };
  66062. return AnaglyphFreeCamera;
  66063. }(BABYLON.FreeCamera));
  66064. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  66065. var AnaglyphArcRotateCamera = (function (_super) {
  66066. __extends(AnaglyphArcRotateCamera, _super);
  66067. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  66068. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66069. _this.interaxialDistance = interaxialDistance;
  66070. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66071. return _this;
  66072. }
  66073. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  66074. return "AnaglyphArcRotateCamera";
  66075. };
  66076. return AnaglyphArcRotateCamera;
  66077. }(BABYLON.ArcRotateCamera));
  66078. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  66079. var AnaglyphGamepadCamera = (function (_super) {
  66080. __extends(AnaglyphGamepadCamera, _super);
  66081. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  66082. var _this = _super.call(this, name, position, scene) || this;
  66083. _this.interaxialDistance = interaxialDistance;
  66084. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66085. return _this;
  66086. }
  66087. AnaglyphGamepadCamera.prototype.getClassName = function () {
  66088. return "AnaglyphGamepadCamera";
  66089. };
  66090. return AnaglyphGamepadCamera;
  66091. }(BABYLON.GamepadCamera));
  66092. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  66093. var AnaglyphUniversalCamera = (function (_super) {
  66094. __extends(AnaglyphUniversalCamera, _super);
  66095. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  66096. var _this = _super.call(this, name, position, scene) || this;
  66097. _this.interaxialDistance = interaxialDistance;
  66098. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66099. return _this;
  66100. }
  66101. AnaglyphUniversalCamera.prototype.getClassName = function () {
  66102. return "AnaglyphUniversalCamera";
  66103. };
  66104. return AnaglyphUniversalCamera;
  66105. }(BABYLON.UniversalCamera));
  66106. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  66107. var StereoscopicFreeCamera = (function (_super) {
  66108. __extends(StereoscopicFreeCamera, _super);
  66109. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66110. var _this = _super.call(this, name, position, scene) || this;
  66111. _this.interaxialDistance = interaxialDistance;
  66112. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66113. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66114. return _this;
  66115. }
  66116. StereoscopicFreeCamera.prototype.getClassName = function () {
  66117. return "StereoscopicFreeCamera";
  66118. };
  66119. return StereoscopicFreeCamera;
  66120. }(BABYLON.FreeCamera));
  66121. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  66122. var StereoscopicArcRotateCamera = (function (_super) {
  66123. __extends(StereoscopicArcRotateCamera, _super);
  66124. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  66125. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66126. _this.interaxialDistance = interaxialDistance;
  66127. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66128. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66129. return _this;
  66130. }
  66131. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  66132. return "StereoscopicArcRotateCamera";
  66133. };
  66134. return StereoscopicArcRotateCamera;
  66135. }(BABYLON.ArcRotateCamera));
  66136. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  66137. var StereoscopicGamepadCamera = (function (_super) {
  66138. __extends(StereoscopicGamepadCamera, _super);
  66139. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66140. var _this = _super.call(this, name, position, scene) || this;
  66141. _this.interaxialDistance = interaxialDistance;
  66142. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66143. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66144. return _this;
  66145. }
  66146. StereoscopicGamepadCamera.prototype.getClassName = function () {
  66147. return "StereoscopicGamepadCamera";
  66148. };
  66149. return StereoscopicGamepadCamera;
  66150. }(BABYLON.GamepadCamera));
  66151. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  66152. var StereoscopicUniversalCamera = (function (_super) {
  66153. __extends(StereoscopicUniversalCamera, _super);
  66154. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66155. var _this = _super.call(this, name, position, scene) || this;
  66156. _this.interaxialDistance = interaxialDistance;
  66157. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66158. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66159. return _this;
  66160. }
  66161. StereoscopicUniversalCamera.prototype.getClassName = function () {
  66162. return "StereoscopicUniversalCamera";
  66163. };
  66164. return StereoscopicUniversalCamera;
  66165. }(BABYLON.UniversalCamera));
  66166. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  66167. })(BABYLON || (BABYLON = {}));
  66168. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  66169. var BABYLON;
  66170. (function (BABYLON) {
  66171. var VRExperienceHelper = (function () {
  66172. function VRExperienceHelper(scene, webVROptions) {
  66173. if (webVROptions === void 0) { webVROptions = {}; }
  66174. var _this = this;
  66175. this.webVROptions = webVROptions;
  66176. this._webVRsupportedAndReady = false;
  66177. this._isInVRMode = false;
  66178. this._scene = scene;
  66179. if (!this._scene.activeCamera) {
  66180. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  66181. }
  66182. else {
  66183. var newCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  66184. if (scene.activeCamera.rotation) {
  66185. newCamera.rotation = scene.activeCamera.rotation.clone();
  66186. }
  66187. this._scene.activeCamera = newCamera;
  66188. }
  66189. this._position = this._scene.activeCamera.position;
  66190. this._canvas = scene.getEngine().getRenderingCanvas();
  66191. this._scene.activeCamera.attachControl(this._canvas);
  66192. this._btnVR = document.createElement("BUTTON");
  66193. this._btnVR.className = "babylonVRicon";
  66194. this._btnVR.id = "babylonVRiconbtn";
  66195. this._btnVR.title = "Click to switch to VR";
  66196. 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) }";
  66197. var style = document.createElement('style');
  66198. style.appendChild(document.createTextNode(css));
  66199. document.getElementsByTagName('head')[0].appendChild(style);
  66200. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  66201. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  66202. window.addEventListener("resize", function () {
  66203. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  66204. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  66205. });
  66206. // Exiting VR mode using 'ESC' key on desktop
  66207. document.addEventListener("keydown", function (event) {
  66208. if (event.keyCode === 27 && _this._isInVRMode) {
  66209. _this.exitVR();
  66210. }
  66211. });
  66212. // Exiting VR mode double tapping the touch screen
  66213. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  66214. if (_this._isInVRMode) {
  66215. _this.exitVR();
  66216. }
  66217. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  66218. if (navigator.getVRDisplays) {
  66219. navigator.getVRDisplays().then(function (headsets) {
  66220. if (headsets.length > 0) {
  66221. scene.getEngine().initWebVR();
  66222. _this._webVRsupportedAndReady = true;
  66223. }
  66224. document.body.appendChild(_this._btnVR);
  66225. });
  66226. }
  66227. else {
  66228. document.body.appendChild(this._btnVR);
  66229. }
  66230. this._btnVR.addEventListener("click", function () {
  66231. _this.enterVR();
  66232. });
  66233. }
  66234. VRExperienceHelper.prototype.enterVR = function () {
  66235. this._scene.activeCamera.dispose();
  66236. // If WebVR is supported and a headset is connected
  66237. if (this._webVRsupportedAndReady) {
  66238. this._scene.activeCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene);
  66239. }
  66240. else {
  66241. this._scene.activeCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  66242. this._scene.getEngine().switchFullscreen(true);
  66243. }
  66244. this._scene.activeCamera.attachControl(this._canvas);
  66245. this._isInVRMode = true;
  66246. this._btnVR.style.display = "none";
  66247. };
  66248. VRExperienceHelper.prototype.exitVR = function () {
  66249. if (this._webVRsupportedAndReady) {
  66250. this._scene.getEngine().disableVR();
  66251. }
  66252. if (this._scene.activeCamera) {
  66253. this._position = this._scene.activeCamera.position;
  66254. this._scene.activeCamera.dispose();
  66255. }
  66256. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, this._scene);
  66257. this._scene.activeCamera.attachControl(this._canvas);
  66258. this._isInVRMode = false;
  66259. this._btnVR.style.display = "";
  66260. };
  66261. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  66262. get: function () {
  66263. return this._position;
  66264. },
  66265. set: function (value) {
  66266. this._position = value;
  66267. this._scene.activeCamera.position = value;
  66268. },
  66269. enumerable: true,
  66270. configurable: true
  66271. });
  66272. VRExperienceHelper.prototype.dispose = function () {
  66273. if (this._isInVRMode) {
  66274. this.exitVR();
  66275. }
  66276. document.body.removeChild(this._btnVR);
  66277. };
  66278. VRExperienceHelper.prototype.getClassName = function () {
  66279. return "VRExperienceHelper";
  66280. };
  66281. return VRExperienceHelper;
  66282. }());
  66283. BABYLON.VRExperienceHelper = VRExperienceHelper;
  66284. })(BABYLON || (BABYLON = {}));
  66285. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  66286. // Mainly based on these 2 articles :
  66287. // 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
  66288. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  66289. var BABYLON;
  66290. (function (BABYLON) {
  66291. var JoystickAxis;
  66292. (function (JoystickAxis) {
  66293. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  66294. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  66295. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  66296. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  66297. var VirtualJoystick = (function () {
  66298. function VirtualJoystick(leftJoystick) {
  66299. var _this = this;
  66300. if (leftJoystick) {
  66301. this._leftJoystick = true;
  66302. }
  66303. else {
  66304. this._leftJoystick = false;
  66305. }
  66306. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  66307. VirtualJoystick._globalJoystickIndex++;
  66308. // By default left & right arrow keys are moving the X
  66309. // and up & down keys are moving the Y
  66310. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  66311. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  66312. this.reverseLeftRight = false;
  66313. this.reverseUpDown = false;
  66314. // collections of pointers
  66315. this._touches = new BABYLON.StringDictionary();
  66316. this.deltaPosition = BABYLON.Vector3.Zero();
  66317. this._joystickSensibility = 25;
  66318. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  66319. this._rotationSpeed = 25;
  66320. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  66321. this._rotateOnAxisRelativeToMesh = false;
  66322. this._onResize = function (evt) {
  66323. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  66324. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  66325. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  66326. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  66327. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  66328. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  66329. };
  66330. // injecting a canvas element on top of the canvas 3D game
  66331. if (!VirtualJoystick.vjCanvas) {
  66332. window.addEventListener("resize", this._onResize, false);
  66333. VirtualJoystick.vjCanvas = document.createElement("canvas");
  66334. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  66335. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  66336. VirtualJoystick.vjCanvas.width = window.innerWidth;
  66337. VirtualJoystick.vjCanvas.height = window.innerHeight;
  66338. VirtualJoystick.vjCanvas.style.width = "100%";
  66339. VirtualJoystick.vjCanvas.style.height = "100%";
  66340. VirtualJoystick.vjCanvas.style.position = "absolute";
  66341. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  66342. VirtualJoystick.vjCanvas.style.top = "0px";
  66343. VirtualJoystick.vjCanvas.style.left = "0px";
  66344. VirtualJoystick.vjCanvas.style.zIndex = "5";
  66345. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  66346. // Support for jQuery PEP polyfill
  66347. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  66348. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  66349. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  66350. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  66351. document.body.appendChild(VirtualJoystick.vjCanvas);
  66352. }
  66353. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  66354. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  66355. this.pressed = false;
  66356. // default joystick color
  66357. this._joystickColor = "cyan";
  66358. this._joystickPointerID = -1;
  66359. // current joystick position
  66360. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  66361. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  66362. // origin joystick position
  66363. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  66364. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  66365. this._onPointerDownHandlerRef = function (evt) {
  66366. _this._onPointerDown(evt);
  66367. };
  66368. this._onPointerMoveHandlerRef = function (evt) {
  66369. _this._onPointerMove(evt);
  66370. };
  66371. this._onPointerOutHandlerRef = function (evt) {
  66372. _this._onPointerUp(evt);
  66373. };
  66374. this._onPointerUpHandlerRef = function (evt) {
  66375. _this._onPointerUp(evt);
  66376. };
  66377. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  66378. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  66379. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  66380. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  66381. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  66382. evt.preventDefault(); // Disables system menu
  66383. }, false);
  66384. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  66385. }
  66386. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  66387. this._joystickSensibility = newJoystickSensibility;
  66388. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  66389. };
  66390. VirtualJoystick.prototype._onPointerDown = function (e) {
  66391. var positionOnScreenCondition;
  66392. e.preventDefault();
  66393. if (this._leftJoystick === true) {
  66394. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  66395. }
  66396. else {
  66397. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  66398. }
  66399. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  66400. // First contact will be dedicated to the virtual joystick
  66401. this._joystickPointerID = e.pointerId;
  66402. this._joystickPointerStartPos.x = e.clientX;
  66403. this._joystickPointerStartPos.y = e.clientY;
  66404. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  66405. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  66406. this._deltaJoystickVector.x = 0;
  66407. this._deltaJoystickVector.y = 0;
  66408. this.pressed = true;
  66409. this._touches.add(e.pointerId.toString(), e);
  66410. }
  66411. else {
  66412. // You can only trigger the action buttons with a joystick declared
  66413. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  66414. this._action();
  66415. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  66416. }
  66417. }
  66418. };
  66419. VirtualJoystick.prototype._onPointerMove = function (e) {
  66420. // If the current pointer is the one associated to the joystick (first touch contact)
  66421. if (this._joystickPointerID == e.pointerId) {
  66422. this._joystickPointerPos.x = e.clientX;
  66423. this._joystickPointerPos.y = e.clientY;
  66424. this._deltaJoystickVector = this._joystickPointerPos.clone();
  66425. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  66426. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  66427. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  66428. switch (this._axisTargetedByLeftAndRight) {
  66429. case JoystickAxis.X:
  66430. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  66431. break;
  66432. case JoystickAxis.Y:
  66433. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  66434. break;
  66435. case JoystickAxis.Z:
  66436. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  66437. break;
  66438. }
  66439. var directionUpDown = this.reverseUpDown ? 1 : -1;
  66440. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  66441. switch (this._axisTargetedByUpAndDown) {
  66442. case JoystickAxis.X:
  66443. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  66444. break;
  66445. case JoystickAxis.Y:
  66446. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  66447. break;
  66448. case JoystickAxis.Z:
  66449. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  66450. break;
  66451. }
  66452. }
  66453. else {
  66454. var data = this._touches.get(e.pointerId.toString());
  66455. if (data) {
  66456. data.x = e.clientX;
  66457. data.y = e.clientY;
  66458. }
  66459. }
  66460. };
  66461. VirtualJoystick.prototype._onPointerUp = function (e) {
  66462. if (this._joystickPointerID == e.pointerId) {
  66463. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  66464. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  66465. this._joystickPointerID = -1;
  66466. this.pressed = false;
  66467. }
  66468. else {
  66469. var touch = this._touches.get(e.pointerId.toString());
  66470. if (touch) {
  66471. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  66472. }
  66473. }
  66474. this._deltaJoystickVector.x = 0;
  66475. this._deltaJoystickVector.y = 0;
  66476. this._touches.remove(e.pointerId.toString());
  66477. };
  66478. /**
  66479. * Change the color of the virtual joystick
  66480. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  66481. */
  66482. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  66483. this._joystickColor = newColor;
  66484. };
  66485. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  66486. this._action = action;
  66487. };
  66488. // Define which axis you'd like to control for left & right
  66489. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  66490. switch (axis) {
  66491. case JoystickAxis.X:
  66492. case JoystickAxis.Y:
  66493. case JoystickAxis.Z:
  66494. this._axisTargetedByLeftAndRight = axis;
  66495. break;
  66496. default:
  66497. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  66498. break;
  66499. }
  66500. };
  66501. // Define which axis you'd like to control for up & down
  66502. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  66503. switch (axis) {
  66504. case JoystickAxis.X:
  66505. case JoystickAxis.Y:
  66506. case JoystickAxis.Z:
  66507. this._axisTargetedByUpAndDown = axis;
  66508. break;
  66509. default:
  66510. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  66511. break;
  66512. }
  66513. };
  66514. VirtualJoystick.prototype._clearCanvas = function () {
  66515. if (this._leftJoystick) {
  66516. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  66517. }
  66518. else {
  66519. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  66520. }
  66521. };
  66522. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  66523. var _this = this;
  66524. if (this.pressed) {
  66525. this._touches.forEach(function (key, touch) {
  66526. if (touch.pointerId === _this._joystickPointerID) {
  66527. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  66528. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  66529. VirtualJoystick.vjCanvasContext.beginPath();
  66530. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  66531. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  66532. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  66533. VirtualJoystick.vjCanvasContext.stroke();
  66534. VirtualJoystick.vjCanvasContext.closePath();
  66535. VirtualJoystick.vjCanvasContext.beginPath();
  66536. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  66537. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  66538. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  66539. VirtualJoystick.vjCanvasContext.stroke();
  66540. VirtualJoystick.vjCanvasContext.closePath();
  66541. VirtualJoystick.vjCanvasContext.beginPath();
  66542. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  66543. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  66544. VirtualJoystick.vjCanvasContext.stroke();
  66545. VirtualJoystick.vjCanvasContext.closePath();
  66546. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  66547. }
  66548. else {
  66549. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  66550. VirtualJoystick.vjCanvasContext.beginPath();
  66551. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  66552. VirtualJoystick.vjCanvasContext.beginPath();
  66553. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  66554. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  66555. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  66556. VirtualJoystick.vjCanvasContext.stroke();
  66557. VirtualJoystick.vjCanvasContext.closePath();
  66558. touch.prevX = touch.x;
  66559. touch.prevY = touch.y;
  66560. }
  66561. ;
  66562. });
  66563. }
  66564. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  66565. };
  66566. VirtualJoystick.prototype.releaseCanvas = function () {
  66567. if (VirtualJoystick.vjCanvas) {
  66568. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  66569. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  66570. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  66571. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  66572. window.removeEventListener("resize", this._onResize);
  66573. document.body.removeChild(VirtualJoystick.vjCanvas);
  66574. VirtualJoystick.vjCanvas = null;
  66575. }
  66576. };
  66577. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  66578. VirtualJoystick._globalJoystickIndex = 0;
  66579. return VirtualJoystick;
  66580. }());
  66581. BABYLON.VirtualJoystick = VirtualJoystick;
  66582. })(BABYLON || (BABYLON = {}));
  66583. //# sourceMappingURL=babylon.virtualJoystick.js.map
  66584. var BABYLON;
  66585. (function (BABYLON) {
  66586. // We're mainly based on the logic defined into the FreeCamera code
  66587. var VirtualJoysticksCamera = (function (_super) {
  66588. __extends(VirtualJoysticksCamera, _super);
  66589. function VirtualJoysticksCamera(name, position, scene) {
  66590. var _this = _super.call(this, name, position, scene) || this;
  66591. _this.inputs.addVirtualJoystick();
  66592. return _this;
  66593. }
  66594. VirtualJoysticksCamera.prototype.getClassName = function () {
  66595. return "VirtualJoysticksCamera";
  66596. };
  66597. return VirtualJoysticksCamera;
  66598. }(BABYLON.FreeCamera));
  66599. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  66600. })(BABYLON || (BABYLON = {}));
  66601. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  66602. var BABYLON;
  66603. (function (BABYLON) {
  66604. var FreeCameraVirtualJoystickInput = (function () {
  66605. function FreeCameraVirtualJoystickInput() {
  66606. }
  66607. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  66608. return this._leftjoystick;
  66609. };
  66610. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  66611. return this._rightjoystick;
  66612. };
  66613. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  66614. if (this._leftjoystick) {
  66615. var camera = this.camera;
  66616. var speed = camera._computeLocalCameraSpeed() * 50;
  66617. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  66618. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  66619. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  66620. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  66621. if (!this._leftjoystick.pressed) {
  66622. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  66623. }
  66624. if (!this._rightjoystick.pressed) {
  66625. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  66626. }
  66627. }
  66628. };
  66629. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  66630. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  66631. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  66632. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  66633. this._leftjoystick.setJoystickSensibility(0.15);
  66634. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  66635. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  66636. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  66637. this._rightjoystick.reverseUpDown = true;
  66638. this._rightjoystick.setJoystickSensibility(0.05);
  66639. this._rightjoystick.setJoystickColor("yellow");
  66640. };
  66641. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  66642. this._leftjoystick.releaseCanvas();
  66643. this._rightjoystick.releaseCanvas();
  66644. };
  66645. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  66646. return "FreeCameraVirtualJoystickInput";
  66647. };
  66648. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  66649. return "virtualJoystick";
  66650. };
  66651. return FreeCameraVirtualJoystickInput;
  66652. }());
  66653. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  66654. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  66655. })(BABYLON || (BABYLON = {}));
  66656. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  66657. var BABYLON;
  66658. (function (BABYLON) {
  66659. var SimplificationSettings = (function () {
  66660. function SimplificationSettings(quality, distance, optimizeMesh) {
  66661. this.quality = quality;
  66662. this.distance = distance;
  66663. this.optimizeMesh = optimizeMesh;
  66664. }
  66665. return SimplificationSettings;
  66666. }());
  66667. BABYLON.SimplificationSettings = SimplificationSettings;
  66668. var SimplificationQueue = (function () {
  66669. function SimplificationQueue() {
  66670. this.running = false;
  66671. this._simplificationArray = [];
  66672. }
  66673. SimplificationQueue.prototype.addTask = function (task) {
  66674. this._simplificationArray.push(task);
  66675. };
  66676. SimplificationQueue.prototype.executeNext = function () {
  66677. var task = this._simplificationArray.pop();
  66678. if (task) {
  66679. this.running = true;
  66680. this.runSimplification(task);
  66681. }
  66682. else {
  66683. this.running = false;
  66684. }
  66685. };
  66686. SimplificationQueue.prototype.runSimplification = function (task) {
  66687. var _this = this;
  66688. if (task.parallelProcessing) {
  66689. //parallel simplifier
  66690. task.settings.forEach(function (setting) {
  66691. var simplifier = _this.getSimplifier(task);
  66692. simplifier.simplify(setting, function (newMesh) {
  66693. task.mesh.addLODLevel(setting.distance, newMesh);
  66694. newMesh.isVisible = true;
  66695. //check if it is the last
  66696. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  66697. //all done, run the success callback.
  66698. task.successCallback();
  66699. }
  66700. _this.executeNext();
  66701. });
  66702. });
  66703. }
  66704. else {
  66705. //single simplifier.
  66706. var simplifier = this.getSimplifier(task);
  66707. var runDecimation = function (setting, callback) {
  66708. simplifier.simplify(setting, function (newMesh) {
  66709. task.mesh.addLODLevel(setting.distance, newMesh);
  66710. newMesh.isVisible = true;
  66711. //run the next quality level
  66712. callback();
  66713. });
  66714. };
  66715. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  66716. runDecimation(task.settings[loop.index], function () {
  66717. loop.executeNext();
  66718. });
  66719. }, function () {
  66720. //execution ended, run the success callback.
  66721. if (task.successCallback) {
  66722. task.successCallback();
  66723. }
  66724. _this.executeNext();
  66725. });
  66726. }
  66727. };
  66728. SimplificationQueue.prototype.getSimplifier = function (task) {
  66729. switch (task.simplificationType) {
  66730. case SimplificationType.QUADRATIC:
  66731. default:
  66732. return new QuadraticErrorSimplification(task.mesh);
  66733. }
  66734. };
  66735. return SimplificationQueue;
  66736. }());
  66737. BABYLON.SimplificationQueue = SimplificationQueue;
  66738. /**
  66739. * The implemented types of simplification.
  66740. * At the moment only Quadratic Error Decimation is implemented.
  66741. */
  66742. var SimplificationType;
  66743. (function (SimplificationType) {
  66744. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  66745. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  66746. var DecimationTriangle = (function () {
  66747. function DecimationTriangle(vertices) {
  66748. this.vertices = vertices;
  66749. this.error = new Array(4);
  66750. this.deleted = false;
  66751. this.isDirty = false;
  66752. this.deletePending = false;
  66753. this.borderFactor = 0;
  66754. }
  66755. return DecimationTriangle;
  66756. }());
  66757. BABYLON.DecimationTriangle = DecimationTriangle;
  66758. var DecimationVertex = (function () {
  66759. function DecimationVertex(position, id) {
  66760. this.position = position;
  66761. this.id = id;
  66762. this.isBorder = true;
  66763. this.q = new QuadraticMatrix();
  66764. this.triangleCount = 0;
  66765. this.triangleStart = 0;
  66766. this.originalOffsets = [];
  66767. }
  66768. DecimationVertex.prototype.updatePosition = function (newPosition) {
  66769. this.position.copyFrom(newPosition);
  66770. };
  66771. return DecimationVertex;
  66772. }());
  66773. BABYLON.DecimationVertex = DecimationVertex;
  66774. var QuadraticMatrix = (function () {
  66775. function QuadraticMatrix(data) {
  66776. this.data = new Array(10);
  66777. for (var i = 0; i < 10; ++i) {
  66778. if (data && data[i]) {
  66779. this.data[i] = data[i];
  66780. }
  66781. else {
  66782. this.data[i] = 0;
  66783. }
  66784. }
  66785. }
  66786. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  66787. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  66788. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  66789. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  66790. return det;
  66791. };
  66792. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  66793. for (var i = 0; i < 10; ++i) {
  66794. this.data[i] += matrix.data[i];
  66795. }
  66796. };
  66797. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  66798. for (var i = 0; i < 10; ++i) {
  66799. this.data[i] += data[i];
  66800. }
  66801. };
  66802. QuadraticMatrix.prototype.add = function (matrix) {
  66803. var m = new QuadraticMatrix();
  66804. for (var i = 0; i < 10; ++i) {
  66805. m.data[i] = this.data[i] + matrix.data[i];
  66806. }
  66807. return m;
  66808. };
  66809. QuadraticMatrix.FromData = function (a, b, c, d) {
  66810. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  66811. };
  66812. //returning an array to avoid garbage collection
  66813. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  66814. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  66815. };
  66816. return QuadraticMatrix;
  66817. }());
  66818. BABYLON.QuadraticMatrix = QuadraticMatrix;
  66819. var Reference = (function () {
  66820. function Reference(vertexId, triangleId) {
  66821. this.vertexId = vertexId;
  66822. this.triangleId = triangleId;
  66823. }
  66824. return Reference;
  66825. }());
  66826. BABYLON.Reference = Reference;
  66827. /**
  66828. * An implementation of the Quadratic Error simplification algorithm.
  66829. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  66830. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  66831. * @author RaananW
  66832. */
  66833. var QuadraticErrorSimplification = (function () {
  66834. function QuadraticErrorSimplification(_mesh) {
  66835. this._mesh = _mesh;
  66836. this.initialized = false;
  66837. this.syncIterations = 5000;
  66838. this.aggressiveness = 7;
  66839. this.decimationIterations = 100;
  66840. this.boundingBoxEpsilon = BABYLON.Epsilon;
  66841. }
  66842. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  66843. var _this = this;
  66844. this.initDecimatedMesh();
  66845. //iterating through the submeshes array, one after the other.
  66846. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  66847. _this.initWithMesh(loop.index, function () {
  66848. _this.runDecimation(settings, loop.index, function () {
  66849. loop.executeNext();
  66850. });
  66851. }, settings.optimizeMesh);
  66852. }, function () {
  66853. setTimeout(function () {
  66854. successCallback(_this._reconstructedMesh);
  66855. }, 0);
  66856. });
  66857. };
  66858. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  66859. var _this = this;
  66860. var gCount = 0;
  66861. triangle.vertices.forEach(function (vertex) {
  66862. var count = 0;
  66863. var vPos = vertex.position;
  66864. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  66865. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  66866. ++count;
  66867. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  66868. ++count;
  66869. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  66870. ++count;
  66871. if (count > 1) {
  66872. ++gCount;
  66873. }
  66874. ;
  66875. });
  66876. if (gCount > 1) {
  66877. console.log(triangle, gCount);
  66878. }
  66879. return gCount > 1;
  66880. };
  66881. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  66882. var _this = this;
  66883. var targetCount = ~~(this.triangles.length * settings.quality);
  66884. var deletedTriangles = 0;
  66885. var triangleCount = this.triangles.length;
  66886. var iterationFunction = function (iteration, callback) {
  66887. setTimeout(function () {
  66888. if (iteration % 5 === 0) {
  66889. _this.updateMesh(iteration === 0);
  66890. }
  66891. for (var i = 0; i < _this.triangles.length; ++i) {
  66892. _this.triangles[i].isDirty = false;
  66893. }
  66894. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  66895. var trianglesIterator = function (i) {
  66896. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  66897. var t = _this.triangles[tIdx];
  66898. if (!t)
  66899. return;
  66900. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  66901. return;
  66902. }
  66903. for (var j = 0; j < 3; ++j) {
  66904. if (t.error[j] < threshold) {
  66905. var deleted0 = [];
  66906. var deleted1 = [];
  66907. var v0 = t.vertices[j];
  66908. var v1 = t.vertices[(j + 1) % 3];
  66909. if (v0.isBorder || v1.isBorder)
  66910. continue;
  66911. var p = BABYLON.Vector3.Zero();
  66912. var n = BABYLON.Vector3.Zero();
  66913. var uv = BABYLON.Vector2.Zero();
  66914. var color = new BABYLON.Color4(0, 0, 0, 1);
  66915. _this.calculateError(v0, v1, p, n, uv, color);
  66916. var delTr = [];
  66917. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  66918. continue;
  66919. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  66920. continue;
  66921. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  66922. continue;
  66923. var uniqueArray = [];
  66924. delTr.forEach(function (deletedT) {
  66925. if (uniqueArray.indexOf(deletedT) === -1) {
  66926. deletedT.deletePending = true;
  66927. uniqueArray.push(deletedT);
  66928. }
  66929. });
  66930. if (uniqueArray.length % 2 !== 0) {
  66931. continue;
  66932. }
  66933. v0.q = v1.q.add(v0.q);
  66934. v0.updatePosition(p);
  66935. var tStart = _this.references.length;
  66936. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  66937. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  66938. var tCount = _this.references.length - tStart;
  66939. if (tCount <= v0.triangleCount) {
  66940. if (tCount) {
  66941. for (var c = 0; c < tCount; c++) {
  66942. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  66943. }
  66944. }
  66945. }
  66946. else {
  66947. v0.triangleStart = tStart;
  66948. }
  66949. v0.triangleCount = tCount;
  66950. break;
  66951. }
  66952. }
  66953. };
  66954. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  66955. }, 0);
  66956. };
  66957. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  66958. if (triangleCount - deletedTriangles <= targetCount)
  66959. loop.breakLoop();
  66960. else {
  66961. iterationFunction(loop.index, function () {
  66962. loop.executeNext();
  66963. });
  66964. }
  66965. }, function () {
  66966. setTimeout(function () {
  66967. //reconstruct this part of the mesh
  66968. _this.reconstructMesh(submeshIndex);
  66969. successCallback();
  66970. }, 0);
  66971. });
  66972. };
  66973. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  66974. var _this = this;
  66975. this.vertices = [];
  66976. this.triangles = [];
  66977. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66978. var indices = this._mesh.getIndices();
  66979. var submesh = this._mesh.subMeshes[submeshIndex];
  66980. var findInVertices = function (positionToSearch) {
  66981. if (optimizeMesh) {
  66982. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  66983. if (_this.vertices[ii].position.equals(positionToSearch)) {
  66984. return _this.vertices[ii];
  66985. }
  66986. }
  66987. }
  66988. return null;
  66989. };
  66990. var vertexReferences = [];
  66991. var vertexInit = function (i) {
  66992. var offset = i + submesh.verticesStart;
  66993. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  66994. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  66995. vertex.originalOffsets.push(offset);
  66996. if (vertex.id === _this.vertices.length) {
  66997. _this.vertices.push(vertex);
  66998. }
  66999. vertexReferences.push(vertex.id);
  67000. };
  67001. //var totalVertices = mesh.getTotalVertices();
  67002. var totalVertices = submesh.verticesCount;
  67003. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  67004. var indicesInit = function (i) {
  67005. var offset = (submesh.indexStart / 3) + i;
  67006. var pos = (offset * 3);
  67007. var i0 = indices[pos + 0];
  67008. var i1 = indices[pos + 1];
  67009. var i2 = indices[pos + 2];
  67010. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  67011. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  67012. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  67013. var triangle = new DecimationTriangle([v0, v1, v2]);
  67014. triangle.originalOffset = pos;
  67015. _this.triangles.push(triangle);
  67016. };
  67017. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  67018. _this.init(callback);
  67019. });
  67020. });
  67021. };
  67022. QuadraticErrorSimplification.prototype.init = function (callback) {
  67023. var _this = this;
  67024. var triangleInit1 = function (i) {
  67025. var t = _this.triangles[i];
  67026. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  67027. for (var j = 0; j < 3; j++) {
  67028. 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))));
  67029. }
  67030. };
  67031. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  67032. var triangleInit2 = function (i) {
  67033. var t = _this.triangles[i];
  67034. for (var j = 0; j < 3; ++j) {
  67035. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  67036. }
  67037. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  67038. };
  67039. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  67040. _this.initialized = true;
  67041. callback();
  67042. });
  67043. });
  67044. };
  67045. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  67046. var newTriangles = [];
  67047. var i;
  67048. for (i = 0; i < this.vertices.length; ++i) {
  67049. this.vertices[i].triangleCount = 0;
  67050. }
  67051. var t;
  67052. var j;
  67053. for (i = 0; i < this.triangles.length; ++i) {
  67054. if (!this.triangles[i].deleted) {
  67055. t = this.triangles[i];
  67056. for (j = 0; j < 3; ++j) {
  67057. t.vertices[j].triangleCount = 1;
  67058. }
  67059. newTriangles.push(t);
  67060. }
  67061. }
  67062. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  67063. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  67064. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  67065. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  67066. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67067. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67068. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67069. var vertexCount = 0;
  67070. for (i = 0; i < this.vertices.length; ++i) {
  67071. var vertex = this.vertices[i];
  67072. vertex.id = vertexCount;
  67073. if (vertex.triangleCount) {
  67074. vertex.originalOffsets.forEach(function (originalOffset) {
  67075. newPositionData.push(vertex.position.x);
  67076. newPositionData.push(vertex.position.y);
  67077. newPositionData.push(vertex.position.z);
  67078. newNormalData.push(normalData[originalOffset * 3]);
  67079. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  67080. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  67081. if (uvs && uvs.length) {
  67082. newUVsData.push(uvs[(originalOffset * 2)]);
  67083. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  67084. }
  67085. else if (colorsData && colorsData.length) {
  67086. newColorsData.push(colorsData[(originalOffset * 4)]);
  67087. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  67088. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  67089. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  67090. }
  67091. ++vertexCount;
  67092. });
  67093. }
  67094. }
  67095. var startingIndex = this._reconstructedMesh.getTotalIndices();
  67096. var startingVertex = this._reconstructedMesh.getTotalVertices();
  67097. var submeshesArray = this._reconstructedMesh.subMeshes;
  67098. this._reconstructedMesh.subMeshes = [];
  67099. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  67100. var originalIndices = this._mesh.getIndices();
  67101. for (i = 0; i < newTriangles.length; ++i) {
  67102. t = newTriangles[i]; //now get the new referencing point for each vertex
  67103. [0, 1, 2].forEach(function (idx) {
  67104. var id = originalIndices[t.originalOffset + idx];
  67105. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  67106. if (offset < 0)
  67107. offset = 0;
  67108. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  67109. });
  67110. }
  67111. //overwriting the old vertex buffers and indices.
  67112. this._reconstructedMesh.setIndices(newIndicesArray);
  67113. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  67114. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  67115. if (newUVsData.length > 0)
  67116. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  67117. if (newColorsData.length > 0)
  67118. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  67119. //create submesh
  67120. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  67121. if (submeshIndex > 0) {
  67122. this._reconstructedMesh.subMeshes = [];
  67123. submeshesArray.forEach(function (submesh) {
  67124. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  67125. });
  67126. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  67127. }
  67128. };
  67129. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  67130. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  67131. this._reconstructedMesh.material = this._mesh.material;
  67132. this._reconstructedMesh.parent = this._mesh.parent;
  67133. this._reconstructedMesh.isVisible = false;
  67134. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  67135. };
  67136. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  67137. for (var i = 0; i < vertex1.triangleCount; ++i) {
  67138. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  67139. if (t.deleted)
  67140. continue;
  67141. var s = this.references[vertex1.triangleStart + i].vertexId;
  67142. var v1 = t.vertices[(s + 1) % 3];
  67143. var v2 = t.vertices[(s + 2) % 3];
  67144. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  67145. deletedArray[i] = true;
  67146. delTr.push(t);
  67147. continue;
  67148. }
  67149. var d1 = v1.position.subtract(point);
  67150. d1 = d1.normalize();
  67151. var d2 = v2.position.subtract(point);
  67152. d2 = d2.normalize();
  67153. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  67154. return true;
  67155. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  67156. deletedArray[i] = false;
  67157. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  67158. return true;
  67159. }
  67160. return false;
  67161. };
  67162. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  67163. var newDeleted = deletedTriangles;
  67164. for (var i = 0; i < vertex.triangleCount; ++i) {
  67165. var ref = this.references[vertex.triangleStart + i];
  67166. var t = this.triangles[ref.triangleId];
  67167. if (t.deleted)
  67168. continue;
  67169. if (deletedArray[i] && t.deletePending) {
  67170. t.deleted = true;
  67171. newDeleted++;
  67172. continue;
  67173. }
  67174. t.vertices[ref.vertexId] = origVertex;
  67175. t.isDirty = true;
  67176. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  67177. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  67178. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  67179. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  67180. this.references.push(ref);
  67181. }
  67182. return newDeleted;
  67183. };
  67184. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  67185. for (var i = 0; i < this.vertices.length; ++i) {
  67186. var vCount = [];
  67187. var vId = [];
  67188. var v = this.vertices[i];
  67189. var j;
  67190. for (j = 0; j < v.triangleCount; ++j) {
  67191. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  67192. for (var ii = 0; ii < 3; ii++) {
  67193. var ofs = 0;
  67194. var vv = triangle.vertices[ii];
  67195. while (ofs < vCount.length) {
  67196. if (vId[ofs] === vv.id)
  67197. break;
  67198. ++ofs;
  67199. }
  67200. if (ofs === vCount.length) {
  67201. vCount.push(1);
  67202. vId.push(vv.id);
  67203. }
  67204. else {
  67205. vCount[ofs]++;
  67206. }
  67207. }
  67208. }
  67209. for (j = 0; j < vCount.length; ++j) {
  67210. if (vCount[j] === 1) {
  67211. this.vertices[vId[j]].isBorder = true;
  67212. }
  67213. else {
  67214. this.vertices[vId[j]].isBorder = false;
  67215. }
  67216. }
  67217. }
  67218. };
  67219. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  67220. if (identifyBorders === void 0) { identifyBorders = false; }
  67221. var i;
  67222. if (!identifyBorders) {
  67223. var newTrianglesVector = [];
  67224. for (i = 0; i < this.triangles.length; ++i) {
  67225. if (!this.triangles[i].deleted) {
  67226. newTrianglesVector.push(this.triangles[i]);
  67227. }
  67228. }
  67229. this.triangles = newTrianglesVector;
  67230. }
  67231. for (i = 0; i < this.vertices.length; ++i) {
  67232. this.vertices[i].triangleCount = 0;
  67233. this.vertices[i].triangleStart = 0;
  67234. }
  67235. var t;
  67236. var j;
  67237. var v;
  67238. for (i = 0; i < this.triangles.length; ++i) {
  67239. t = this.triangles[i];
  67240. for (j = 0; j < 3; ++j) {
  67241. v = t.vertices[j];
  67242. v.triangleCount++;
  67243. }
  67244. }
  67245. var tStart = 0;
  67246. for (i = 0; i < this.vertices.length; ++i) {
  67247. this.vertices[i].triangleStart = tStart;
  67248. tStart += this.vertices[i].triangleCount;
  67249. this.vertices[i].triangleCount = 0;
  67250. }
  67251. var newReferences = new Array(this.triangles.length * 3);
  67252. for (i = 0; i < this.triangles.length; ++i) {
  67253. t = this.triangles[i];
  67254. for (j = 0; j < 3; ++j) {
  67255. v = t.vertices[j];
  67256. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  67257. v.triangleCount++;
  67258. }
  67259. }
  67260. this.references = newReferences;
  67261. if (identifyBorders) {
  67262. this.identifyBorder();
  67263. }
  67264. };
  67265. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  67266. var x = point.x;
  67267. var y = point.y;
  67268. var z = point.z;
  67269. 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
  67270. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  67271. };
  67272. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  67273. var q = vertex1.q.add(vertex2.q);
  67274. var border = vertex1.isBorder && vertex2.isBorder;
  67275. var error = 0;
  67276. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  67277. if (qDet !== 0 && !border) {
  67278. if (!pointResult) {
  67279. pointResult = BABYLON.Vector3.Zero();
  67280. }
  67281. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  67282. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  67283. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  67284. error = this.vertexError(q, pointResult);
  67285. }
  67286. else {
  67287. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  67288. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  67289. var error1 = this.vertexError(q, vertex1.position);
  67290. var error2 = this.vertexError(q, vertex2.position);
  67291. var error3 = this.vertexError(q, p3);
  67292. error = Math.min(error1, error2, error3);
  67293. if (error === error1) {
  67294. if (pointResult) {
  67295. pointResult.copyFrom(vertex1.position);
  67296. }
  67297. }
  67298. else if (error === error2) {
  67299. if (pointResult) {
  67300. pointResult.copyFrom(vertex2.position);
  67301. }
  67302. }
  67303. else {
  67304. if (pointResult) {
  67305. pointResult.copyFrom(p3);
  67306. }
  67307. }
  67308. }
  67309. return error;
  67310. };
  67311. return QuadraticErrorSimplification;
  67312. }());
  67313. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  67314. })(BABYLON || (BABYLON = {}));
  67315. //# sourceMappingURL=babylon.meshSimplification.js.map
  67316. var BABYLON;
  67317. (function (BABYLON) {
  67318. var Internals;
  67319. (function (Internals) {
  67320. var MeshLODLevel = (function () {
  67321. function MeshLODLevel(distance, mesh) {
  67322. this.distance = distance;
  67323. this.mesh = mesh;
  67324. }
  67325. return MeshLODLevel;
  67326. }());
  67327. Internals.MeshLODLevel = MeshLODLevel;
  67328. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67329. })(BABYLON || (BABYLON = {}));
  67330. //# sourceMappingURL=babylon.meshLODLevel.js.map
  67331. var BABYLON;
  67332. (function (BABYLON) {
  67333. // Standard optimizations
  67334. var SceneOptimization = (function () {
  67335. function SceneOptimization(priority) {
  67336. if (priority === void 0) { priority = 0; }
  67337. this.priority = priority;
  67338. this.apply = function (scene) {
  67339. return true; // Return true if everything that can be done was applied
  67340. };
  67341. }
  67342. return SceneOptimization;
  67343. }());
  67344. BABYLON.SceneOptimization = SceneOptimization;
  67345. var TextureOptimization = (function (_super) {
  67346. __extends(TextureOptimization, _super);
  67347. function TextureOptimization(priority, maximumSize) {
  67348. if (priority === void 0) { priority = 0; }
  67349. if (maximumSize === void 0) { maximumSize = 1024; }
  67350. var _this = _super.call(this, priority) || this;
  67351. _this.priority = priority;
  67352. _this.maximumSize = maximumSize;
  67353. _this.apply = function (scene) {
  67354. var allDone = true;
  67355. for (var index = 0; index < scene.textures.length; index++) {
  67356. var texture = scene.textures[index];
  67357. if (!texture.canRescale || texture.getContext) {
  67358. continue;
  67359. }
  67360. var currentSize = texture.getSize();
  67361. var maxDimension = Math.max(currentSize.width, currentSize.height);
  67362. if (maxDimension > _this.maximumSize) {
  67363. texture.scale(0.5);
  67364. allDone = false;
  67365. }
  67366. }
  67367. return allDone;
  67368. };
  67369. return _this;
  67370. }
  67371. return TextureOptimization;
  67372. }(SceneOptimization));
  67373. BABYLON.TextureOptimization = TextureOptimization;
  67374. var HardwareScalingOptimization = (function (_super) {
  67375. __extends(HardwareScalingOptimization, _super);
  67376. function HardwareScalingOptimization(priority, maximumScale) {
  67377. if (priority === void 0) { priority = 0; }
  67378. if (maximumScale === void 0) { maximumScale = 2; }
  67379. var _this = _super.call(this, priority) || this;
  67380. _this.priority = priority;
  67381. _this.maximumScale = maximumScale;
  67382. _this._currentScale = 1;
  67383. _this.apply = function (scene) {
  67384. _this._currentScale++;
  67385. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  67386. return _this._currentScale >= _this.maximumScale;
  67387. };
  67388. return _this;
  67389. }
  67390. return HardwareScalingOptimization;
  67391. }(SceneOptimization));
  67392. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  67393. var ShadowsOptimization = (function (_super) {
  67394. __extends(ShadowsOptimization, _super);
  67395. function ShadowsOptimization() {
  67396. var _this = _super !== null && _super.apply(this, arguments) || this;
  67397. _this.apply = function (scene) {
  67398. scene.shadowsEnabled = false;
  67399. return true;
  67400. };
  67401. return _this;
  67402. }
  67403. return ShadowsOptimization;
  67404. }(SceneOptimization));
  67405. BABYLON.ShadowsOptimization = ShadowsOptimization;
  67406. var PostProcessesOptimization = (function (_super) {
  67407. __extends(PostProcessesOptimization, _super);
  67408. function PostProcessesOptimization() {
  67409. var _this = _super !== null && _super.apply(this, arguments) || this;
  67410. _this.apply = function (scene) {
  67411. scene.postProcessesEnabled = false;
  67412. return true;
  67413. };
  67414. return _this;
  67415. }
  67416. return PostProcessesOptimization;
  67417. }(SceneOptimization));
  67418. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  67419. var LensFlaresOptimization = (function (_super) {
  67420. __extends(LensFlaresOptimization, _super);
  67421. function LensFlaresOptimization() {
  67422. var _this = _super !== null && _super.apply(this, arguments) || this;
  67423. _this.apply = function (scene) {
  67424. scene.lensFlaresEnabled = false;
  67425. return true;
  67426. };
  67427. return _this;
  67428. }
  67429. return LensFlaresOptimization;
  67430. }(SceneOptimization));
  67431. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  67432. var ParticlesOptimization = (function (_super) {
  67433. __extends(ParticlesOptimization, _super);
  67434. function ParticlesOptimization() {
  67435. var _this = _super !== null && _super.apply(this, arguments) || this;
  67436. _this.apply = function (scene) {
  67437. scene.particlesEnabled = false;
  67438. return true;
  67439. };
  67440. return _this;
  67441. }
  67442. return ParticlesOptimization;
  67443. }(SceneOptimization));
  67444. BABYLON.ParticlesOptimization = ParticlesOptimization;
  67445. var RenderTargetsOptimization = (function (_super) {
  67446. __extends(RenderTargetsOptimization, _super);
  67447. function RenderTargetsOptimization() {
  67448. var _this = _super !== null && _super.apply(this, arguments) || this;
  67449. _this.apply = function (scene) {
  67450. scene.renderTargetsEnabled = false;
  67451. return true;
  67452. };
  67453. return _this;
  67454. }
  67455. return RenderTargetsOptimization;
  67456. }(SceneOptimization));
  67457. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  67458. var MergeMeshesOptimization = (function (_super) {
  67459. __extends(MergeMeshesOptimization, _super);
  67460. function MergeMeshesOptimization() {
  67461. var _this = _super !== null && _super.apply(this, arguments) || this;
  67462. _this._canBeMerged = function (abstractMesh) {
  67463. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  67464. return false;
  67465. }
  67466. var mesh = abstractMesh;
  67467. if (!mesh.isVisible || !mesh.isEnabled()) {
  67468. return false;
  67469. }
  67470. if (mesh.instances.length > 0) {
  67471. return false;
  67472. }
  67473. if (mesh.skeleton || mesh.hasLODLevels) {
  67474. return false;
  67475. }
  67476. if (mesh.parent) {
  67477. return false;
  67478. }
  67479. return true;
  67480. };
  67481. _this.apply = function (scene, updateSelectionTree) {
  67482. var globalPool = scene.meshes.slice(0);
  67483. var globalLength = globalPool.length;
  67484. for (var index = 0; index < globalLength; index++) {
  67485. var currentPool = new Array();
  67486. var current = globalPool[index];
  67487. // Checks
  67488. if (!_this._canBeMerged(current)) {
  67489. continue;
  67490. }
  67491. currentPool.push(current);
  67492. // Find compatible meshes
  67493. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  67494. var otherMesh = globalPool[subIndex];
  67495. if (!_this._canBeMerged(otherMesh)) {
  67496. continue;
  67497. }
  67498. if (otherMesh.material !== current.material) {
  67499. continue;
  67500. }
  67501. if (otherMesh.checkCollisions !== current.checkCollisions) {
  67502. continue;
  67503. }
  67504. currentPool.push(otherMesh);
  67505. globalLength--;
  67506. globalPool.splice(subIndex, 1);
  67507. subIndex--;
  67508. }
  67509. if (currentPool.length < 2) {
  67510. continue;
  67511. }
  67512. // Merge meshes
  67513. BABYLON.Mesh.MergeMeshes(currentPool);
  67514. }
  67515. if (updateSelectionTree != undefined) {
  67516. if (updateSelectionTree) {
  67517. scene.createOrUpdateSelectionOctree();
  67518. }
  67519. }
  67520. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  67521. scene.createOrUpdateSelectionOctree();
  67522. }
  67523. return true;
  67524. };
  67525. return _this;
  67526. }
  67527. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  67528. get: function () {
  67529. return MergeMeshesOptimization._UpdateSelectionTree;
  67530. },
  67531. set: function (value) {
  67532. MergeMeshesOptimization._UpdateSelectionTree = value;
  67533. },
  67534. enumerable: true,
  67535. configurable: true
  67536. });
  67537. MergeMeshesOptimization._UpdateSelectionTree = false;
  67538. return MergeMeshesOptimization;
  67539. }(SceneOptimization));
  67540. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  67541. // Options
  67542. var SceneOptimizerOptions = (function () {
  67543. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  67544. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  67545. if (trackerDuration === void 0) { trackerDuration = 2000; }
  67546. this.targetFrameRate = targetFrameRate;
  67547. this.trackerDuration = trackerDuration;
  67548. this.optimizations = new Array();
  67549. }
  67550. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  67551. var result = new SceneOptimizerOptions(targetFrameRate);
  67552. var priority = 0;
  67553. result.optimizations.push(new MergeMeshesOptimization(priority));
  67554. result.optimizations.push(new ShadowsOptimization(priority));
  67555. result.optimizations.push(new LensFlaresOptimization(priority));
  67556. // Next priority
  67557. priority++;
  67558. result.optimizations.push(new PostProcessesOptimization(priority));
  67559. result.optimizations.push(new ParticlesOptimization(priority));
  67560. // Next priority
  67561. priority++;
  67562. result.optimizations.push(new TextureOptimization(priority, 1024));
  67563. return result;
  67564. };
  67565. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  67566. var result = new SceneOptimizerOptions(targetFrameRate);
  67567. var priority = 0;
  67568. result.optimizations.push(new MergeMeshesOptimization(priority));
  67569. result.optimizations.push(new ShadowsOptimization(priority));
  67570. result.optimizations.push(new LensFlaresOptimization(priority));
  67571. // Next priority
  67572. priority++;
  67573. result.optimizations.push(new PostProcessesOptimization(priority));
  67574. result.optimizations.push(new ParticlesOptimization(priority));
  67575. // Next priority
  67576. priority++;
  67577. result.optimizations.push(new TextureOptimization(priority, 512));
  67578. // Next priority
  67579. priority++;
  67580. result.optimizations.push(new RenderTargetsOptimization(priority));
  67581. // Next priority
  67582. priority++;
  67583. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  67584. return result;
  67585. };
  67586. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  67587. var result = new SceneOptimizerOptions(targetFrameRate);
  67588. var priority = 0;
  67589. result.optimizations.push(new MergeMeshesOptimization(priority));
  67590. result.optimizations.push(new ShadowsOptimization(priority));
  67591. result.optimizations.push(new LensFlaresOptimization(priority));
  67592. // Next priority
  67593. priority++;
  67594. result.optimizations.push(new PostProcessesOptimization(priority));
  67595. result.optimizations.push(new ParticlesOptimization(priority));
  67596. // Next priority
  67597. priority++;
  67598. result.optimizations.push(new TextureOptimization(priority, 256));
  67599. // Next priority
  67600. priority++;
  67601. result.optimizations.push(new RenderTargetsOptimization(priority));
  67602. // Next priority
  67603. priority++;
  67604. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  67605. return result;
  67606. };
  67607. return SceneOptimizerOptions;
  67608. }());
  67609. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  67610. // Scene optimizer tool
  67611. var SceneOptimizer = (function () {
  67612. function SceneOptimizer() {
  67613. }
  67614. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  67615. // TODO: add an epsilon
  67616. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  67617. if (onSuccess) {
  67618. onSuccess();
  67619. }
  67620. return;
  67621. }
  67622. // Apply current level of optimizations
  67623. var allDone = true;
  67624. var noOptimizationApplied = true;
  67625. for (var index = 0; index < options.optimizations.length; index++) {
  67626. var optimization = options.optimizations[index];
  67627. if (optimization.priority === currentPriorityLevel) {
  67628. noOptimizationApplied = false;
  67629. allDone = allDone && optimization.apply(scene);
  67630. }
  67631. }
  67632. // If no optimization was applied, this is a failure :(
  67633. if (noOptimizationApplied) {
  67634. if (onFailure) {
  67635. onFailure();
  67636. }
  67637. return;
  67638. }
  67639. // If all optimizations were done, move to next level
  67640. if (allDone) {
  67641. currentPriorityLevel++;
  67642. }
  67643. // Let's the system running for a specific amount of time before checking FPS
  67644. scene.executeWhenReady(function () {
  67645. setTimeout(function () {
  67646. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  67647. }, options.trackerDuration);
  67648. });
  67649. };
  67650. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  67651. if (!options) {
  67652. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  67653. }
  67654. // Let's the system running for a specific amount of time before checking FPS
  67655. scene.executeWhenReady(function () {
  67656. setTimeout(function () {
  67657. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  67658. }, options.trackerDuration);
  67659. });
  67660. };
  67661. return SceneOptimizer;
  67662. }());
  67663. BABYLON.SceneOptimizer = SceneOptimizer;
  67664. })(BABYLON || (BABYLON = {}));
  67665. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  67666. var BABYLON;
  67667. (function (BABYLON) {
  67668. var OutlineRenderer = (function () {
  67669. function OutlineRenderer(scene) {
  67670. this.zOffset = 1;
  67671. this._scene = scene;
  67672. }
  67673. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  67674. var _this = this;
  67675. if (useOverlay === void 0) { useOverlay = false; }
  67676. var scene = this._scene;
  67677. var engine = this._scene.getEngine();
  67678. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67679. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  67680. return;
  67681. }
  67682. var mesh = subMesh.getRenderingMesh();
  67683. var material = subMesh.getMaterial();
  67684. engine.enableEffect(this._effect);
  67685. // Logarithmic depth
  67686. if (material.useLogarithmicDepth) {
  67687. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  67688. }
  67689. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  67690. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  67691. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67692. // Bones
  67693. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67694. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67695. }
  67696. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  67697. // Alpha test
  67698. if (material && material.needAlphaTesting()) {
  67699. var alphaTexture = material.getAlphaTestTexture();
  67700. if (alphaTexture) {
  67701. this._effect.setTexture("diffuseSampler", alphaTexture);
  67702. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67703. }
  67704. }
  67705. engine.setZOffset(-this.zOffset);
  67706. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  67707. engine.setZOffset(0);
  67708. };
  67709. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  67710. var defines = [];
  67711. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67712. var mesh = subMesh.getMesh();
  67713. var material = subMesh.getMaterial();
  67714. if (material) {
  67715. // Alpha test
  67716. if (material.needAlphaTesting()) {
  67717. defines.push("#define ALPHATEST");
  67718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67719. attribs.push(BABYLON.VertexBuffer.UVKind);
  67720. defines.push("#define UV1");
  67721. }
  67722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67723. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67724. defines.push("#define UV2");
  67725. }
  67726. }
  67727. //Logarithmic depth
  67728. if (material.useLogarithmicDepth) {
  67729. defines.push("#define LOGARITHMICDEPTH");
  67730. }
  67731. }
  67732. // Bones
  67733. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67736. if (mesh.numBoneInfluencers > 4) {
  67737. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67738. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67739. }
  67740. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67741. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67742. }
  67743. else {
  67744. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67745. }
  67746. // Instances
  67747. if (useInstances) {
  67748. defines.push("#define INSTANCES");
  67749. attribs.push("world0");
  67750. attribs.push("world1");
  67751. attribs.push("world2");
  67752. attribs.push("world3");
  67753. }
  67754. // Get correct effect
  67755. var join = defines.join("\n");
  67756. if (this._cachedDefines !== join) {
  67757. this._cachedDefines = join;
  67758. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  67759. }
  67760. return this._effect.isReady();
  67761. };
  67762. return OutlineRenderer;
  67763. }());
  67764. BABYLON.OutlineRenderer = OutlineRenderer;
  67765. })(BABYLON || (BABYLON = {}));
  67766. //# sourceMappingURL=babylon.outlineRenderer.js.map
  67767. var BABYLON;
  67768. (function (BABYLON) {
  67769. var FaceAdjacencies = (function () {
  67770. function FaceAdjacencies() {
  67771. this.edges = new Array();
  67772. this.edgesConnectedCount = 0;
  67773. }
  67774. return FaceAdjacencies;
  67775. }());
  67776. var EdgesRenderer = (function () {
  67777. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  67778. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  67779. if (epsilon === void 0) { epsilon = 0.95; }
  67780. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  67781. this.edgesWidthScalerForOrthographic = 1000.0;
  67782. this.edgesWidthScalerForPerspective = 50.0;
  67783. this._linesPositions = new Array();
  67784. this._linesNormals = new Array();
  67785. this._linesIndices = new Array();
  67786. this._buffers = {};
  67787. this._checkVerticesInsteadOfIndices = false;
  67788. this._source = source;
  67789. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  67790. this._epsilon = epsilon;
  67791. this._prepareRessources();
  67792. this._generateEdgesLines();
  67793. }
  67794. EdgesRenderer.prototype._prepareRessources = function () {
  67795. if (this._lineShader) {
  67796. return;
  67797. }
  67798. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  67799. attributes: ["position", "normal"],
  67800. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  67801. });
  67802. this._lineShader.disableDepthWrite = true;
  67803. this._lineShader.backFaceCulling = false;
  67804. };
  67805. EdgesRenderer.prototype._rebuild = function () {
  67806. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  67807. if (buffer) {
  67808. buffer._rebuild();
  67809. }
  67810. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  67811. if (buffer) {
  67812. buffer._rebuild();
  67813. }
  67814. var scene = this._source.getScene();
  67815. var engine = scene.getEngine();
  67816. this._ib = engine.createIndexBuffer(this._linesIndices);
  67817. };
  67818. EdgesRenderer.prototype.dispose = function () {
  67819. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  67820. if (buffer) {
  67821. buffer.dispose();
  67822. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  67823. }
  67824. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  67825. if (buffer) {
  67826. buffer.dispose();
  67827. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  67828. }
  67829. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  67830. this._lineShader.dispose();
  67831. };
  67832. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  67833. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  67834. return 0;
  67835. }
  67836. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  67837. return 1;
  67838. }
  67839. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  67840. return 2;
  67841. }
  67842. return -1;
  67843. };
  67844. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  67845. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  67846. return 0;
  67847. }
  67848. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  67849. return 1;
  67850. }
  67851. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  67852. return 2;
  67853. }
  67854. return -1;
  67855. };
  67856. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  67857. var needToCreateLine;
  67858. if (edge === undefined) {
  67859. needToCreateLine = true;
  67860. }
  67861. else {
  67862. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  67863. needToCreateLine = dotProduct < this._epsilon;
  67864. }
  67865. if (needToCreateLine) {
  67866. var offset = this._linesPositions.length / 3;
  67867. var normal = p0.subtract(p1);
  67868. normal.normalize();
  67869. // Positions
  67870. this._linesPositions.push(p0.x);
  67871. this._linesPositions.push(p0.y);
  67872. this._linesPositions.push(p0.z);
  67873. this._linesPositions.push(p0.x);
  67874. this._linesPositions.push(p0.y);
  67875. this._linesPositions.push(p0.z);
  67876. this._linesPositions.push(p1.x);
  67877. this._linesPositions.push(p1.y);
  67878. this._linesPositions.push(p1.z);
  67879. this._linesPositions.push(p1.x);
  67880. this._linesPositions.push(p1.y);
  67881. this._linesPositions.push(p1.z);
  67882. // Normals
  67883. this._linesNormals.push(p1.x);
  67884. this._linesNormals.push(p1.y);
  67885. this._linesNormals.push(p1.z);
  67886. this._linesNormals.push(-1);
  67887. this._linesNormals.push(p1.x);
  67888. this._linesNormals.push(p1.y);
  67889. this._linesNormals.push(p1.z);
  67890. this._linesNormals.push(1);
  67891. this._linesNormals.push(p0.x);
  67892. this._linesNormals.push(p0.y);
  67893. this._linesNormals.push(p0.z);
  67894. this._linesNormals.push(-1);
  67895. this._linesNormals.push(p0.x);
  67896. this._linesNormals.push(p0.y);
  67897. this._linesNormals.push(p0.z);
  67898. this._linesNormals.push(1);
  67899. // Indices
  67900. this._linesIndices.push(offset);
  67901. this._linesIndices.push(offset + 1);
  67902. this._linesIndices.push(offset + 2);
  67903. this._linesIndices.push(offset);
  67904. this._linesIndices.push(offset + 2);
  67905. this._linesIndices.push(offset + 3);
  67906. }
  67907. };
  67908. EdgesRenderer.prototype._generateEdgesLines = function () {
  67909. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67910. var indices = this._source.getIndices();
  67911. // First let's find adjacencies
  67912. var adjacencies = new Array();
  67913. var faceNormals = new Array();
  67914. var index;
  67915. var faceAdjacencies;
  67916. // Prepare faces
  67917. for (index = 0; index < indices.length; index += 3) {
  67918. faceAdjacencies = new FaceAdjacencies();
  67919. var p0Index = indices[index];
  67920. var p1Index = indices[index + 1];
  67921. var p2Index = indices[index + 2];
  67922. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  67923. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  67924. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  67925. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  67926. faceNormal.normalize();
  67927. faceNormals.push(faceNormal);
  67928. adjacencies.push(faceAdjacencies);
  67929. }
  67930. // Scan
  67931. for (index = 0; index < adjacencies.length; index++) {
  67932. faceAdjacencies = adjacencies[index];
  67933. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  67934. var otherFaceAdjacencies = adjacencies[otherIndex];
  67935. if (faceAdjacencies.edgesConnectedCount === 3) {
  67936. break;
  67937. }
  67938. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  67939. continue;
  67940. }
  67941. var otherP0 = indices[otherIndex * 3];
  67942. var otherP1 = indices[otherIndex * 3 + 1];
  67943. var otherP2 = indices[otherIndex * 3 + 2];
  67944. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  67945. var otherEdgeIndex;
  67946. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  67947. continue;
  67948. }
  67949. switch (edgeIndex) {
  67950. case 0:
  67951. if (this._checkVerticesInsteadOfIndices) {
  67952. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67953. }
  67954. else {
  67955. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  67956. }
  67957. break;
  67958. case 1:
  67959. if (this._checkVerticesInsteadOfIndices) {
  67960. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67961. }
  67962. else {
  67963. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  67964. }
  67965. break;
  67966. case 2:
  67967. if (this._checkVerticesInsteadOfIndices) {
  67968. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67969. }
  67970. else {
  67971. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  67972. }
  67973. break;
  67974. }
  67975. if (otherEdgeIndex === -1) {
  67976. continue;
  67977. }
  67978. faceAdjacencies.edges[edgeIndex] = otherIndex;
  67979. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  67980. faceAdjacencies.edgesConnectedCount++;
  67981. otherFaceAdjacencies.edgesConnectedCount++;
  67982. if (faceAdjacencies.edgesConnectedCount === 3) {
  67983. break;
  67984. }
  67985. }
  67986. }
  67987. }
  67988. // Create lines
  67989. for (index = 0; index < adjacencies.length; index++) {
  67990. // 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
  67991. var current = adjacencies[index];
  67992. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  67993. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  67994. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  67995. }
  67996. // Merge into a single mesh
  67997. var engine = this._source.getScene().getEngine();
  67998. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  67999. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  68000. this._ib = engine.createIndexBuffer(this._linesIndices);
  68001. this._indicesCount = this._linesIndices.length;
  68002. };
  68003. EdgesRenderer.prototype.render = function () {
  68004. if (!this._lineShader.isReady()) {
  68005. return;
  68006. }
  68007. var scene = this._source.getScene();
  68008. var engine = scene.getEngine();
  68009. this._lineShader._preBind();
  68010. // VBOs
  68011. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  68012. scene.resetCachedMaterial();
  68013. this._lineShader.setColor4("color", this._source.edgesColor);
  68014. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  68015. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  68016. }
  68017. else {
  68018. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  68019. }
  68020. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  68021. this._lineShader.bind(this._source.getWorldMatrix());
  68022. // Draw order
  68023. engine.draw(true, 0, this._indicesCount);
  68024. this._lineShader.unbind();
  68025. engine.setDepthWrite(true);
  68026. };
  68027. return EdgesRenderer;
  68028. }());
  68029. BABYLON.EdgesRenderer = EdgesRenderer;
  68030. })(BABYLON || (BABYLON = {}));
  68031. //# sourceMappingURL=babylon.edgesRenderer.js.map
  68032. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  68033. /// <reference path="..\Math\babylon.math.ts" />
  68034. var BABYLON;
  68035. (function (BABYLON) {
  68036. /**
  68037. * Special Glow Blur post process only blurring the alpha channel
  68038. * It enforces keeping the most luminous color in the color channel.
  68039. */
  68040. var GlowBlurPostProcess = (function (_super) {
  68041. __extends(GlowBlurPostProcess, _super);
  68042. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  68043. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68044. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  68045. _this.direction = direction;
  68046. _this.kernel = kernel;
  68047. _this.onApplyObservable.add(function (effect) {
  68048. effect.setFloat2("screenSize", _this.width, _this.height);
  68049. effect.setVector2("direction", _this.direction);
  68050. effect.setFloat("blurWidth", _this.kernel);
  68051. });
  68052. return _this;
  68053. }
  68054. return GlowBlurPostProcess;
  68055. }(BABYLON.PostProcess));
  68056. /**
  68057. * The highlight layer Helps adding a glow effect around a mesh.
  68058. *
  68059. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  68060. * glowy meshes to your scene.
  68061. *
  68062. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  68063. */
  68064. var HighlightLayer = (function () {
  68065. /**
  68066. * Instantiates a new highlight Layer and references it to the scene..
  68067. * @param name The name of the layer
  68068. * @param scene The scene to use the layer in
  68069. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  68070. */
  68071. function HighlightLayer(name, scene, options) {
  68072. this.name = name;
  68073. this._vertexBuffers = {};
  68074. this._mainTextureDesiredSize = { width: 0, height: 0 };
  68075. this._meshes = {};
  68076. this._maxSize = 0;
  68077. this._shouldRender = false;
  68078. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  68079. this._excludedMeshes = {};
  68080. /**
  68081. * Specifies whether or not the inner glow is ACTIVE in the layer.
  68082. */
  68083. this.innerGlow = true;
  68084. /**
  68085. * Specifies whether or not the outer glow is ACTIVE in the layer.
  68086. */
  68087. this.outerGlow = true;
  68088. /**
  68089. * Specifies wether the highlight layer is enabled or not.
  68090. */
  68091. this.isEnabled = true;
  68092. /**
  68093. * An event triggered when the highlight layer has been disposed.
  68094. * @type {BABYLON.Observable}
  68095. */
  68096. this.onDisposeObservable = new BABYLON.Observable();
  68097. /**
  68098. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  68099. * @type {BABYLON.Observable}
  68100. */
  68101. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  68102. /**
  68103. * An event triggered when the highlight layer is being blurred.
  68104. * @type {BABYLON.Observable}
  68105. */
  68106. this.onBeforeBlurObservable = new BABYLON.Observable();
  68107. /**
  68108. * An event triggered when the highlight layer has been blurred.
  68109. * @type {BABYLON.Observable}
  68110. */
  68111. this.onAfterBlurObservable = new BABYLON.Observable();
  68112. /**
  68113. * An event triggered when the glowing blurred texture is being merged in the scene.
  68114. * @type {BABYLON.Observable}
  68115. */
  68116. this.onBeforeComposeObservable = new BABYLON.Observable();
  68117. /**
  68118. * An event triggered when the glowing blurred texture has been merged in the scene.
  68119. * @type {BABYLON.Observable}
  68120. */
  68121. this.onAfterComposeObservable = new BABYLON.Observable();
  68122. /**
  68123. * An event triggered when the highlight layer changes its size.
  68124. * @type {BABYLON.Observable}
  68125. */
  68126. this.onSizeChangedObservable = new BABYLON.Observable();
  68127. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68128. var engine = scene.getEngine();
  68129. this._engine = engine;
  68130. this._maxSize = this._engine.getCaps().maxTextureSize;
  68131. this._scene.highlightLayers.push(this);
  68132. // Warn on stencil.
  68133. if (!this._engine.isStencilEnable) {
  68134. 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 }");
  68135. }
  68136. // Adapt options
  68137. this._options = options || {
  68138. mainTextureRatio: 0.5,
  68139. blurTextureSizeRatio: 0.5,
  68140. blurHorizontalSize: 1.0,
  68141. blurVerticalSize: 1.0,
  68142. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  68143. };
  68144. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  68145. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  68146. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  68147. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  68148. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  68149. // VBO
  68150. var vertices = [];
  68151. vertices.push(1, 1);
  68152. vertices.push(-1, 1);
  68153. vertices.push(-1, -1);
  68154. vertices.push(1, -1);
  68155. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68156. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  68157. this._createIndexBuffer();
  68158. // Effect
  68159. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  68160. // Render target
  68161. this.setMainTextureSize();
  68162. // Create Textures and post processes
  68163. this.createTextureAndPostProcesses();
  68164. }
  68165. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  68166. /**
  68167. * Gets the horizontal size of the blur.
  68168. */
  68169. get: function () {
  68170. return this._horizontalBlurPostprocess.kernel;
  68171. },
  68172. /**
  68173. * Specifies the horizontal size of the blur.
  68174. */
  68175. set: function (value) {
  68176. this._horizontalBlurPostprocess.kernel = value;
  68177. },
  68178. enumerable: true,
  68179. configurable: true
  68180. });
  68181. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  68182. /**
  68183. * Gets the vertical size of the blur.
  68184. */
  68185. get: function () {
  68186. return this._verticalBlurPostprocess.kernel;
  68187. },
  68188. /**
  68189. * Specifies the vertical size of the blur.
  68190. */
  68191. set: function (value) {
  68192. this._verticalBlurPostprocess.kernel = value;
  68193. },
  68194. enumerable: true,
  68195. configurable: true
  68196. });
  68197. Object.defineProperty(HighlightLayer.prototype, "camera", {
  68198. /**
  68199. * Gets the camera attached to the layer.
  68200. */
  68201. get: function () {
  68202. return this._options.camera;
  68203. },
  68204. enumerable: true,
  68205. configurable: true
  68206. });
  68207. HighlightLayer.prototype._createIndexBuffer = function () {
  68208. var engine = this._scene.getEngine();
  68209. // Indices
  68210. var indices = [];
  68211. indices.push(0);
  68212. indices.push(1);
  68213. indices.push(2);
  68214. indices.push(0);
  68215. indices.push(2);
  68216. indices.push(3);
  68217. this._indexBuffer = engine.createIndexBuffer(indices);
  68218. };
  68219. HighlightLayer.prototype._rebuild = function () {
  68220. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  68221. this._createIndexBuffer();
  68222. };
  68223. /**
  68224. * Creates the render target textures and post processes used in the highlight layer.
  68225. */
  68226. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  68227. var _this = this;
  68228. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  68229. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  68230. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  68231. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  68232. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  68233. width: this._mainTextureDesiredSize.width,
  68234. height: this._mainTextureDesiredSize.height
  68235. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68236. this._mainTexture.activeCamera = this._options.camera;
  68237. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68238. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68239. this._mainTexture.anisotropicFilteringLevel = 1;
  68240. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68241. this._mainTexture.renderParticles = false;
  68242. this._mainTexture.renderList = null;
  68243. this._mainTexture.ignoreCameraViewport = true;
  68244. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  68245. width: blurTextureWidth,
  68246. height: blurTextureHeight
  68247. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68248. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68249. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68250. this._blurTexture.anisotropicFilteringLevel = 16;
  68251. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68252. this._blurTexture.renderParticles = false;
  68253. this._blurTexture.ignoreCameraViewport = true;
  68254. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68255. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  68256. effect.setTexture("textureSampler", _this._mainTexture);
  68257. });
  68258. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  68259. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68260. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  68261. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68262. });
  68263. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68264. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  68265. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68266. });
  68267. }
  68268. else {
  68269. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68270. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  68271. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68272. });
  68273. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68274. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  68275. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68276. });
  68277. }
  68278. this._mainTexture.onAfterUnbindObservable.add(function () {
  68279. _this.onBeforeBlurObservable.notifyObservers(_this);
  68280. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  68281. _this.onAfterBlurObservable.notifyObservers(_this);
  68282. });
  68283. // Custom render function
  68284. var renderSubMesh = function (subMesh) {
  68285. var mesh = subMesh.getRenderingMesh();
  68286. var scene = _this._scene;
  68287. var engine = scene.getEngine();
  68288. // Culling
  68289. engine.setState(subMesh.getMaterial().backFaceCulling);
  68290. // Managing instances
  68291. var batch = mesh._getInstancesRenderList(subMesh._id);
  68292. if (batch.mustReturn) {
  68293. return;
  68294. }
  68295. // Excluded Mesh
  68296. if (_this._excludedMeshes[mesh.uniqueId]) {
  68297. return;
  68298. }
  68299. ;
  68300. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68301. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  68302. var material = subMesh.getMaterial();
  68303. var emissiveTexture = null;
  68304. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  68305. emissiveTexture = material.emissiveTexture;
  68306. }
  68307. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  68308. engine.enableEffect(_this._glowMapGenerationEffect);
  68309. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  68310. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  68311. if (highlightLayerMesh) {
  68312. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  68313. }
  68314. else {
  68315. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  68316. }
  68317. // Alpha test
  68318. if (material && material.needAlphaTesting()) {
  68319. var alphaTexture = material.getAlphaTestTexture();
  68320. if (alphaTexture) {
  68321. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  68322. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68323. }
  68324. }
  68325. // Glow emissive only
  68326. if (emissiveTexture) {
  68327. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  68328. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  68329. }
  68330. // Bones
  68331. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68332. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68333. }
  68334. // Draw
  68335. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  68336. }
  68337. else {
  68338. // Need to reset refresh rate of the shadowMap
  68339. _this._mainTexture.resetRefreshCounter();
  68340. }
  68341. };
  68342. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68343. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  68344. var index;
  68345. var engine = _this._scene.getEngine();
  68346. if (depthOnlySubMeshes.length) {
  68347. engine.setColorWrite(false);
  68348. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68349. renderSubMesh(depthOnlySubMeshes.data[index]);
  68350. }
  68351. engine.setColorWrite(true);
  68352. }
  68353. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68354. renderSubMesh(opaqueSubMeshes.data[index]);
  68355. }
  68356. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68357. renderSubMesh(alphaTestSubMeshes.data[index]);
  68358. }
  68359. for (index = 0; index < transparentSubMeshes.length; index++) {
  68360. renderSubMesh(transparentSubMeshes.data[index]);
  68361. }
  68362. };
  68363. this._mainTexture.onClearObservable.add(function (engine) {
  68364. engine.clear(HighlightLayer.neutralColor, true, true, true);
  68365. });
  68366. };
  68367. /**
  68368. * Checks for the readiness of the element composing the layer.
  68369. * @param subMesh the mesh to check for
  68370. * @param useInstances specify wether or not to use instances to render the mesh
  68371. * @param emissiveTexture the associated emissive texture used to generate the glow
  68372. * @return true if ready otherwise, false
  68373. */
  68374. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  68375. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  68376. return false;
  68377. }
  68378. var defines = [];
  68379. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68380. var mesh = subMesh.getMesh();
  68381. var material = subMesh.getMaterial();
  68382. var uv1 = false;
  68383. var uv2 = false;
  68384. // Alpha test
  68385. if (material && material.needAlphaTesting()) {
  68386. var alphaTexture = material.getAlphaTestTexture();
  68387. if (alphaTexture) {
  68388. defines.push("#define ALPHATEST");
  68389. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  68390. alphaTexture.coordinatesIndex === 1) {
  68391. defines.push("#define DIFFUSEUV2");
  68392. uv2 = true;
  68393. }
  68394. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68395. defines.push("#define DIFFUSEUV1");
  68396. uv1 = true;
  68397. }
  68398. }
  68399. }
  68400. // Emissive
  68401. if (emissiveTexture) {
  68402. defines.push("#define EMISSIVE");
  68403. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  68404. emissiveTexture.coordinatesIndex === 1) {
  68405. defines.push("#define EMISSIVEUV2");
  68406. uv2 = true;
  68407. }
  68408. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68409. defines.push("#define EMISSIVEUV1");
  68410. uv1 = true;
  68411. }
  68412. }
  68413. if (uv1) {
  68414. attribs.push(BABYLON.VertexBuffer.UVKind);
  68415. defines.push("#define UV1");
  68416. }
  68417. if (uv2) {
  68418. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68419. defines.push("#define UV2");
  68420. }
  68421. // Bones
  68422. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68423. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68424. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68425. if (mesh.numBoneInfluencers > 4) {
  68426. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68427. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68428. }
  68429. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68430. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68431. }
  68432. else {
  68433. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68434. }
  68435. // Instances
  68436. if (useInstances) {
  68437. defines.push("#define INSTANCES");
  68438. attribs.push("world0");
  68439. attribs.push("world1");
  68440. attribs.push("world2");
  68441. attribs.push("world3");
  68442. }
  68443. // Get correct effect
  68444. var join = defines.join("\n");
  68445. if (this._cachedDefines !== join) {
  68446. this._cachedDefines = join;
  68447. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  68448. }
  68449. return this._glowMapGenerationEffect.isReady();
  68450. };
  68451. /**
  68452. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  68453. */
  68454. HighlightLayer.prototype.render = function () {
  68455. var currentEffect = this._glowMapMergeEffect;
  68456. // Check
  68457. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  68458. return;
  68459. var engine = this._scene.getEngine();
  68460. this.onBeforeComposeObservable.notifyObservers(this);
  68461. // Render
  68462. engine.enableEffect(currentEffect);
  68463. engine.setState(false);
  68464. // Cache
  68465. var previousStencilBuffer = engine.getStencilBuffer();
  68466. var previousStencilFunction = engine.getStencilFunction();
  68467. var previousStencilMask = engine.getStencilMask();
  68468. var previousStencilOperationPass = engine.getStencilOperationPass();
  68469. var previousStencilOperationFail = engine.getStencilOperationFail();
  68470. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  68471. var previousAlphaMode = engine.getAlphaMode();
  68472. // Texture
  68473. currentEffect.setTexture("textureSampler", this._blurTexture);
  68474. // VBOs
  68475. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  68476. // Stencil operations
  68477. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  68478. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  68479. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  68480. // Draw order
  68481. engine.setAlphaMode(this._options.alphaBlendingMode);
  68482. engine.setStencilMask(0x00);
  68483. engine.setStencilBuffer(true);
  68484. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  68485. if (this.outerGlow) {
  68486. currentEffect.setFloat("offset", 0);
  68487. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  68488. engine.draw(true, 0, 6);
  68489. }
  68490. if (this.innerGlow) {
  68491. currentEffect.setFloat("offset", 1);
  68492. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  68493. engine.draw(true, 0, 6);
  68494. }
  68495. // Restore Cache
  68496. engine.setStencilFunction(previousStencilFunction);
  68497. engine.setStencilMask(previousStencilMask);
  68498. engine.setAlphaMode(previousAlphaMode);
  68499. engine.setStencilBuffer(previousStencilBuffer);
  68500. engine.setStencilOperationPass(previousStencilOperationPass);
  68501. engine.setStencilOperationFail(previousStencilOperationFail);
  68502. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  68503. engine._stencilState.reset();
  68504. this.onAfterComposeObservable.notifyObservers(this);
  68505. // Handle size changes.
  68506. var size = this._mainTexture.getSize();
  68507. this.setMainTextureSize();
  68508. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  68509. // Recreate RTT and post processes on size change.
  68510. this.onSizeChangedObservable.notifyObservers(this);
  68511. this.disposeTextureAndPostProcesses();
  68512. this.createTextureAndPostProcesses();
  68513. }
  68514. };
  68515. /**
  68516. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  68517. * @param mesh The mesh to exclude from the highlight layer
  68518. */
  68519. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  68520. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  68521. if (!meshExcluded) {
  68522. this._excludedMeshes[mesh.uniqueId] = {
  68523. mesh: mesh,
  68524. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  68525. mesh.getEngine().setStencilBuffer(false);
  68526. }),
  68527. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  68528. mesh.getEngine().setStencilBuffer(true);
  68529. }),
  68530. };
  68531. }
  68532. };
  68533. /**
  68534. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  68535. * @param mesh The mesh to highlight
  68536. */
  68537. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  68538. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  68539. if (meshExcluded) {
  68540. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  68541. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  68542. }
  68543. this._excludedMeshes[mesh.uniqueId] = undefined;
  68544. };
  68545. /**
  68546. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  68547. * @param mesh The mesh to highlight
  68548. * @param color The color of the highlight
  68549. * @param glowEmissiveOnly Extract the glow from the emissive texture
  68550. */
  68551. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  68552. var _this = this;
  68553. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  68554. var meshHighlight = this._meshes[mesh.uniqueId];
  68555. if (meshHighlight) {
  68556. meshHighlight.color = color;
  68557. }
  68558. else {
  68559. this._meshes[mesh.uniqueId] = {
  68560. mesh: mesh,
  68561. color: color,
  68562. // Lambda required for capture due to Observable this context
  68563. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  68564. if (_this._excludedMeshes[mesh.uniqueId]) {
  68565. _this.defaultStencilReference(mesh);
  68566. }
  68567. else {
  68568. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  68569. }
  68570. }),
  68571. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  68572. glowEmissiveOnly: glowEmissiveOnly
  68573. };
  68574. }
  68575. this._shouldRender = true;
  68576. };
  68577. /**
  68578. * Remove a mesh from the highlight layer in order to make it stop glowing.
  68579. * @param mesh The mesh to highlight
  68580. */
  68581. HighlightLayer.prototype.removeMesh = function (mesh) {
  68582. var meshHighlight = this._meshes[mesh.uniqueId];
  68583. if (meshHighlight) {
  68584. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  68585. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  68586. }
  68587. this._meshes[mesh.uniqueId] = undefined;
  68588. this._shouldRender = false;
  68589. for (var meshHighlightToCheck in this._meshes) {
  68590. if (meshHighlightToCheck) {
  68591. this._shouldRender = true;
  68592. break;
  68593. }
  68594. }
  68595. };
  68596. /**
  68597. * Returns true if the layer contains information to display, otherwise false.
  68598. */
  68599. HighlightLayer.prototype.shouldRender = function () {
  68600. return this.isEnabled && this._shouldRender;
  68601. };
  68602. /**
  68603. * Sets the main texture desired size which is the closest power of two
  68604. * of the engine canvas size.
  68605. */
  68606. HighlightLayer.prototype.setMainTextureSize = function () {
  68607. if (this._options.mainTextureFixedSize) {
  68608. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  68609. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  68610. }
  68611. else {
  68612. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  68613. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  68614. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  68615. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  68616. }
  68617. };
  68618. /**
  68619. * Force the stencil to the normal expected value for none glowing parts
  68620. */
  68621. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  68622. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  68623. };
  68624. /**
  68625. * Dispose only the render target textures and post process.
  68626. */
  68627. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  68628. this._blurTexture.dispose();
  68629. this._mainTexture.dispose();
  68630. this._downSamplePostprocess.dispose();
  68631. this._horizontalBlurPostprocess.dispose();
  68632. this._verticalBlurPostprocess.dispose();
  68633. };
  68634. /**
  68635. * Dispose the highlight layer and free resources.
  68636. */
  68637. HighlightLayer.prototype.dispose = function () {
  68638. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68639. if (vertexBuffer) {
  68640. vertexBuffer.dispose();
  68641. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68642. }
  68643. if (this._indexBuffer) {
  68644. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68645. this._indexBuffer = null;
  68646. }
  68647. // Clean textures and post processes
  68648. this.disposeTextureAndPostProcesses();
  68649. // Clean mesh references
  68650. for (var id in this._meshes) {
  68651. var meshHighlight = this._meshes[id];
  68652. if (meshHighlight && meshHighlight.mesh) {
  68653. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  68654. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  68655. }
  68656. }
  68657. this._meshes = null;
  68658. for (var id in this._excludedMeshes) {
  68659. var meshHighlight = this._excludedMeshes[id];
  68660. if (meshHighlight) {
  68661. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  68662. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  68663. }
  68664. }
  68665. this._excludedMeshes = null;
  68666. // Remove from scene
  68667. var index = this._scene.highlightLayers.indexOf(this, 0);
  68668. if (index > -1) {
  68669. this._scene.highlightLayers.splice(index, 1);
  68670. }
  68671. // Callback
  68672. this.onDisposeObservable.notifyObservers(this);
  68673. this.onDisposeObservable.clear();
  68674. this.onBeforeRenderMainTextureObservable.clear();
  68675. this.onBeforeBlurObservable.clear();
  68676. this.onBeforeComposeObservable.clear();
  68677. this.onAfterComposeObservable.clear();
  68678. this.onSizeChangedObservable.clear();
  68679. };
  68680. /**
  68681. * The neutral color used during the preparation of the glow effect.
  68682. * This is black by default as the blend operation is a blend operation.
  68683. */
  68684. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  68685. /**
  68686. * Stencil value used for glowing meshes.
  68687. */
  68688. HighlightLayer.glowingMeshStencilReference = 0x02;
  68689. /**
  68690. * Stencil value used for the other meshes in the scene.
  68691. */
  68692. HighlightLayer.normalMeshStencilReference = 0x01;
  68693. return HighlightLayer;
  68694. }());
  68695. BABYLON.HighlightLayer = HighlightLayer;
  68696. })(BABYLON || (BABYLON = {}));
  68697. //# sourceMappingURL=babylon.highlightlayer.js.map
  68698. var BABYLON;
  68699. (function (BABYLON) {
  68700. var MeshAssetTask = (function () {
  68701. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  68702. this.name = name;
  68703. this.meshesNames = meshesNames;
  68704. this.rootUrl = rootUrl;
  68705. this.sceneFilename = sceneFilename;
  68706. this.isCompleted = false;
  68707. }
  68708. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68709. var _this = this;
  68710. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  68711. _this.loadedMeshes = meshes;
  68712. _this.loadedParticleSystems = particleSystems;
  68713. _this.loadedSkeletons = skeletons;
  68714. _this.isCompleted = true;
  68715. if (_this.onSuccess) {
  68716. _this.onSuccess(_this);
  68717. }
  68718. onSuccess();
  68719. }, null, function () {
  68720. if (_this.onError) {
  68721. _this.onError(_this);
  68722. }
  68723. onError();
  68724. });
  68725. };
  68726. return MeshAssetTask;
  68727. }());
  68728. BABYLON.MeshAssetTask = MeshAssetTask;
  68729. var TextFileAssetTask = (function () {
  68730. function TextFileAssetTask(name, url) {
  68731. this.name = name;
  68732. this.url = url;
  68733. this.isCompleted = false;
  68734. }
  68735. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68736. var _this = this;
  68737. BABYLON.Tools.LoadFile(this.url, function (data) {
  68738. _this.text = data;
  68739. _this.isCompleted = true;
  68740. if (_this.onSuccess) {
  68741. _this.onSuccess(_this);
  68742. }
  68743. onSuccess();
  68744. }, null, scene.database, false, function () {
  68745. if (_this.onError) {
  68746. _this.onError(_this);
  68747. }
  68748. onError();
  68749. });
  68750. };
  68751. return TextFileAssetTask;
  68752. }());
  68753. BABYLON.TextFileAssetTask = TextFileAssetTask;
  68754. var BinaryFileAssetTask = (function () {
  68755. function BinaryFileAssetTask(name, url) {
  68756. this.name = name;
  68757. this.url = url;
  68758. this.isCompleted = false;
  68759. }
  68760. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68761. var _this = this;
  68762. BABYLON.Tools.LoadFile(this.url, function (data) {
  68763. _this.data = data;
  68764. _this.isCompleted = true;
  68765. if (_this.onSuccess) {
  68766. _this.onSuccess(_this);
  68767. }
  68768. onSuccess();
  68769. }, null, scene.database, true, function () {
  68770. if (_this.onError) {
  68771. _this.onError(_this);
  68772. }
  68773. onError();
  68774. });
  68775. };
  68776. return BinaryFileAssetTask;
  68777. }());
  68778. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  68779. var ImageAssetTask = (function () {
  68780. function ImageAssetTask(name, url) {
  68781. this.name = name;
  68782. this.url = url;
  68783. this.isCompleted = false;
  68784. }
  68785. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68786. var _this = this;
  68787. var img = new Image();
  68788. BABYLON.Tools.SetCorsBehavior(this.url, img);
  68789. img.onload = function () {
  68790. _this.image = img;
  68791. _this.isCompleted = true;
  68792. if (_this.onSuccess) {
  68793. _this.onSuccess(_this);
  68794. }
  68795. onSuccess();
  68796. };
  68797. img.onerror = function () {
  68798. if (_this.onError) {
  68799. _this.onError(_this);
  68800. }
  68801. onError();
  68802. };
  68803. img.src = this.url;
  68804. };
  68805. return ImageAssetTask;
  68806. }());
  68807. BABYLON.ImageAssetTask = ImageAssetTask;
  68808. var TextureAssetTask = (function () {
  68809. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  68810. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68811. this.name = name;
  68812. this.url = url;
  68813. this.noMipmap = noMipmap;
  68814. this.invertY = invertY;
  68815. this.samplingMode = samplingMode;
  68816. this.isCompleted = false;
  68817. }
  68818. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68819. var _this = this;
  68820. var onload = function () {
  68821. _this.isCompleted = true;
  68822. if (_this.onSuccess) {
  68823. _this.onSuccess(_this);
  68824. }
  68825. onSuccess();
  68826. };
  68827. var onerror = function () {
  68828. if (_this.onError) {
  68829. _this.onError(_this);
  68830. }
  68831. onError();
  68832. };
  68833. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  68834. };
  68835. return TextureAssetTask;
  68836. }());
  68837. BABYLON.TextureAssetTask = TextureAssetTask;
  68838. var CubeTextureAssetTask = (function () {
  68839. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  68840. this.name = name;
  68841. this.url = url;
  68842. this.extensions = extensions;
  68843. this.noMipmap = noMipmap;
  68844. this.files = files;
  68845. this.isCompleted = false;
  68846. }
  68847. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68848. var _this = this;
  68849. var onload = function () {
  68850. _this.isCompleted = true;
  68851. if (_this.onSuccess) {
  68852. _this.onSuccess(_this);
  68853. }
  68854. onSuccess();
  68855. };
  68856. var onerror = function () {
  68857. if (_this.onError) {
  68858. _this.onError(_this);
  68859. }
  68860. onError();
  68861. };
  68862. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  68863. };
  68864. return CubeTextureAssetTask;
  68865. }());
  68866. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  68867. var HDRCubeTextureAssetTask = (function () {
  68868. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  68869. if (noMipmap === void 0) { noMipmap = false; }
  68870. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68871. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68872. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68873. this.name = name;
  68874. this.url = url;
  68875. this.size = size;
  68876. this.noMipmap = noMipmap;
  68877. this.generateHarmonics = generateHarmonics;
  68878. this.useInGammaSpace = useInGammaSpace;
  68879. this.usePMREMGenerator = usePMREMGenerator;
  68880. this.isCompleted = false;
  68881. }
  68882. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68883. var _this = this;
  68884. var onload = function () {
  68885. _this.isCompleted = true;
  68886. if (_this.onSuccess) {
  68887. _this.onSuccess(_this);
  68888. }
  68889. onSuccess();
  68890. };
  68891. var onerror = function () {
  68892. if (_this.onError) {
  68893. _this.onError(_this);
  68894. }
  68895. onError();
  68896. };
  68897. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  68898. };
  68899. return HDRCubeTextureAssetTask;
  68900. }());
  68901. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  68902. var AssetsManager = (function () {
  68903. function AssetsManager(scene) {
  68904. this.tasks = new Array();
  68905. this.waitingTasksCount = 0;
  68906. this.useDefaultLoadingScreen = true;
  68907. this._scene = scene;
  68908. }
  68909. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  68910. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  68911. this.tasks.push(task);
  68912. return task;
  68913. };
  68914. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  68915. var task = new TextFileAssetTask(taskName, url);
  68916. this.tasks.push(task);
  68917. return task;
  68918. };
  68919. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  68920. var task = new BinaryFileAssetTask(taskName, url);
  68921. this.tasks.push(task);
  68922. return task;
  68923. };
  68924. AssetsManager.prototype.addImageTask = function (taskName, url) {
  68925. var task = new ImageAssetTask(taskName, url);
  68926. this.tasks.push(task);
  68927. return task;
  68928. };
  68929. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  68930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68931. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  68932. this.tasks.push(task);
  68933. return task;
  68934. };
  68935. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  68936. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  68937. this.tasks.push(task);
  68938. return task;
  68939. };
  68940. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  68941. if (noMipmap === void 0) { noMipmap = false; }
  68942. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68943. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68944. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68945. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  68946. this.tasks.push(task);
  68947. return task;
  68948. };
  68949. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  68950. this.waitingTasksCount--;
  68951. if (this.waitingTasksCount === 0) {
  68952. if (this.onFinish) {
  68953. this.onFinish(this.tasks);
  68954. }
  68955. this._scene.getEngine().hideLoadingUI();
  68956. }
  68957. };
  68958. AssetsManager.prototype._runTask = function (task) {
  68959. var _this = this;
  68960. task.run(this._scene, function () {
  68961. if (_this.onTaskSuccess) {
  68962. _this.onTaskSuccess(task);
  68963. }
  68964. _this._decreaseWaitingTasksCount();
  68965. }, function () {
  68966. if (_this.onTaskError) {
  68967. _this.onTaskError(task);
  68968. }
  68969. _this._decreaseWaitingTasksCount();
  68970. });
  68971. };
  68972. AssetsManager.prototype.reset = function () {
  68973. this.tasks = new Array();
  68974. return this;
  68975. };
  68976. AssetsManager.prototype.load = function () {
  68977. this.waitingTasksCount = this.tasks.length;
  68978. if (this.waitingTasksCount === 0) {
  68979. if (this.onFinish) {
  68980. this.onFinish(this.tasks);
  68981. }
  68982. return this;
  68983. }
  68984. if (this.useDefaultLoadingScreen) {
  68985. this._scene.getEngine().displayLoadingUI();
  68986. }
  68987. for (var index = 0; index < this.tasks.length; index++) {
  68988. var task = this.tasks[index];
  68989. this._runTask(task);
  68990. }
  68991. return this;
  68992. };
  68993. return AssetsManager;
  68994. }());
  68995. BABYLON.AssetsManager = AssetsManager;
  68996. })(BABYLON || (BABYLON = {}));
  68997. //# sourceMappingURL=babylon.assetsManager.js.map
  68998. var BABYLON;
  68999. (function (BABYLON) {
  69000. var MapTexture = (function (_super) {
  69001. __extends(MapTexture, _super);
  69002. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  69003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69004. if (useMipMap === void 0) { useMipMap = false; }
  69005. if (margin === void 0) { margin = 0; }
  69006. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  69007. _this.name = name;
  69008. _this._size = size;
  69009. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69010. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69011. // Create the rectPackMap that will allocate portion of the texture
  69012. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  69013. // Create the texture that will store the content
  69014. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  69015. return _this;
  69016. }
  69017. /**
  69018. * Allocate a rectangle of a given size in the texture map
  69019. * @param size the size of the rectangle to allocation
  69020. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  69021. */
  69022. MapTexture.prototype.allocateRect = function (size) {
  69023. return this._rectPackingMap.addRect(size);
  69024. };
  69025. /**
  69026. * Free a given rectangle from the texture map
  69027. * @param rectInfo the instance corresponding to the rect to free.
  69028. */
  69029. MapTexture.prototype.freeRect = function (rectInfo) {
  69030. if (rectInfo) {
  69031. rectInfo.freeContent();
  69032. }
  69033. };
  69034. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  69035. /**
  69036. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  69037. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  69038. * @returns {}
  69039. */
  69040. get: function () {
  69041. return this._rectPackingMap.freeSpace;
  69042. },
  69043. enumerable: true,
  69044. configurable: true
  69045. });
  69046. /**
  69047. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  69048. * 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.
  69049. * Don't forget to call unbindTexture when you're done rendering
  69050. * @param rect the zone to render to
  69051. * @param clear true to clear the portion's color/depth data
  69052. */
  69053. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  69054. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  69055. };
  69056. /**
  69057. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  69058. * 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.
  69059. * Don't forget to call unbindTexture when you're done rendering
  69060. * @param pos the position into the texture
  69061. * @param size the portion to fit the clip space to
  69062. * @param clear true to clear the portion's color/depth data
  69063. */
  69064. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  69065. var engine = this.getScene().getEngine();
  69066. engine.bindFramebuffer(this._texture);
  69067. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  69068. if (clear) {
  69069. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  69070. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  69071. }
  69072. };
  69073. /**
  69074. * Unbind the texture map from the rendering engine.
  69075. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  69076. * @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.
  69077. */
  69078. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  69079. // Dump ?
  69080. if (dumpForDebug) {
  69081. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  69082. }
  69083. var engine = this.getScene().getEngine();
  69084. if (this._replacedViewport) {
  69085. engine.setViewport(this._replacedViewport);
  69086. this._replacedViewport = null;
  69087. }
  69088. engine.unBindFramebuffer(this._texture);
  69089. };
  69090. Object.defineProperty(MapTexture.prototype, "canRescale", {
  69091. get: function () {
  69092. return false;
  69093. },
  69094. enumerable: true,
  69095. configurable: true
  69096. });
  69097. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  69098. // Anyway, there's not much point to use this method for this kind of texture I guess
  69099. MapTexture.prototype.clone = function () {
  69100. return null;
  69101. };
  69102. return MapTexture;
  69103. }(BABYLON.Texture));
  69104. BABYLON.MapTexture = MapTexture;
  69105. })(BABYLON || (BABYLON = {}));
  69106. //# sourceMappingURL=babylon.mapTexture.js.map
  69107. var BABYLON;
  69108. (function (BABYLON) {
  69109. /**
  69110. * This class describe a rectangle that were added to the map.
  69111. * You have access to its coordinates either in pixel or normalized (UV)
  69112. */
  69113. var PackedRect = (function () {
  69114. function PackedRect(root, parent, pos, size) {
  69115. this._pos = pos;
  69116. this._size = size;
  69117. this._root = root;
  69118. this._parent = parent;
  69119. this._contentSize = null;
  69120. this._bottomNode = null;
  69121. this._leftNode = null;
  69122. this._initialSize = null;
  69123. this._rightNode = null;
  69124. }
  69125. Object.defineProperty(PackedRect.prototype, "pos", {
  69126. /**
  69127. * @returns the position of this node into the map
  69128. */
  69129. get: function () {
  69130. return this._pos;
  69131. },
  69132. enumerable: true,
  69133. configurable: true
  69134. });
  69135. Object.defineProperty(PackedRect.prototype, "contentSize", {
  69136. /**
  69137. * @returns the size of the rectangle this node handles
  69138. */
  69139. get: function () {
  69140. return this._contentSize;
  69141. },
  69142. enumerable: true,
  69143. configurable: true
  69144. });
  69145. /**
  69146. * Retrieve the inner position (considering the margin) and stores it into the res object
  69147. * @param res must be a valid Vector2 that will contain the inner position after this call
  69148. */
  69149. PackedRect.prototype.getInnerPosToRef = function (res) {
  69150. var m = this._root._margin;
  69151. res.x = this._pos.x + m;
  69152. res.y = this._pos.y + m;
  69153. };
  69154. /**
  69155. * Retrieve the inner size (considering the margin) and stores it into the res object
  69156. * @param res must be a valid Size that will contain the inner size after this call
  69157. */
  69158. PackedRect.prototype.getInnerSizeToRef = function (res) {
  69159. var m = this._root._margin;
  69160. res.width = this._contentSize.width - (m * 2);
  69161. res.height = this._contentSize.height - (m * 2);
  69162. };
  69163. Object.defineProperty(PackedRect.prototype, "UVs", {
  69164. /**
  69165. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  69166. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  69167. */
  69168. get: function () {
  69169. if (!this._contentSize) {
  69170. throw new Error("Can't compute UVs for this object because it's nor allocated");
  69171. }
  69172. return this.getUVsForCustomSize(this._contentSize);
  69173. },
  69174. enumerable: true,
  69175. configurable: true
  69176. });
  69177. /**
  69178. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  69179. * and then using only a part of the PackRect.
  69180. * This method will return the UVs for this part by given the custom size of what you really use
  69181. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  69182. */
  69183. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  69184. var mainWidth = this._root._size.width;
  69185. var mainHeight = this._root._size.height;
  69186. var margin = this._root._margin;
  69187. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  69188. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  69189. var uvs = new Array();
  69190. uvs.push(topLeft);
  69191. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  69192. uvs.push(rightBottom);
  69193. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  69194. return uvs;
  69195. };
  69196. /**
  69197. * Free this rectangle from the map.
  69198. * Call this method when you no longer need the rectangle to be in the map.
  69199. */
  69200. PackedRect.prototype.freeContent = function () {
  69201. if (!this.contentSize) {
  69202. return;
  69203. }
  69204. this._contentSize = null;
  69205. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  69206. this.attemptDefrag();
  69207. };
  69208. Object.defineProperty(PackedRect.prototype, "isUsed", {
  69209. get: function () {
  69210. return this._contentSize != null || this._leftNode != null;
  69211. },
  69212. enumerable: true,
  69213. configurable: true
  69214. });
  69215. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  69216. var node = this.findNode(contentSize);
  69217. // Not enough space...
  69218. if (!node) {
  69219. return null;
  69220. }
  69221. node.splitNode(contentSize);
  69222. return node;
  69223. };
  69224. PackedRect.prototype.findNode = function (size) {
  69225. var resNode = null;
  69226. var margin = this._root._margin * 2;
  69227. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  69228. if (this.isUsed) {
  69229. if (this._leftNode) {
  69230. resNode = this._leftNode.findNode(size);
  69231. }
  69232. if (!resNode && this._rightNode) {
  69233. resNode = this._rightNode.findNode(size);
  69234. }
  69235. if (!resNode && this._bottomNode) {
  69236. resNode = this._bottomNode.findNode(size);
  69237. }
  69238. }
  69239. else if (this._initialSize) {
  69240. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  69241. resNode = this;
  69242. }
  69243. else {
  69244. return null;
  69245. }
  69246. }
  69247. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  69248. resNode = this;
  69249. }
  69250. return resNode;
  69251. };
  69252. PackedRect.prototype.splitNode = function (contentSize) {
  69253. var cs = PackedRect.TpsSize;
  69254. var margin = this._root._margin * 2;
  69255. cs.copyFrom(contentSize);
  69256. cs.width += margin;
  69257. cs.height += margin;
  69258. // 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)
  69259. if (!this._contentSize && this._initialSize) {
  69260. this._contentSize = cs.clone();
  69261. 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));
  69262. return this._leftNode.splitNode(contentSize);
  69263. }
  69264. else {
  69265. this._contentSize = cs.clone();
  69266. this._initialSize = cs.clone();
  69267. if (cs.width !== this._size.width) {
  69268. 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));
  69269. }
  69270. if (cs.height !== this._size.height) {
  69271. 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));
  69272. }
  69273. return this;
  69274. }
  69275. };
  69276. PackedRect.prototype.attemptDefrag = function () {
  69277. if (!this.isUsed && this.isRecursiveFree) {
  69278. this.clearNode();
  69279. if (this._parent) {
  69280. this._parent.attemptDefrag();
  69281. }
  69282. }
  69283. };
  69284. PackedRect.prototype.clearNode = function () {
  69285. this._initialSize = null;
  69286. this._rightNode = null;
  69287. this._bottomNode = null;
  69288. };
  69289. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  69290. get: function () {
  69291. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  69292. },
  69293. enumerable: true,
  69294. configurable: true
  69295. });
  69296. PackedRect.prototype.evalFreeSize = function (size) {
  69297. var levelSize = 0;
  69298. if (!this.isUsed) {
  69299. var margin = this._root._margin;
  69300. var is = this._initialSize;
  69301. if (is) {
  69302. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  69303. }
  69304. else {
  69305. var size_1 = this._size;
  69306. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  69307. }
  69308. }
  69309. if (this._rightNode) {
  69310. levelSize += this._rightNode.evalFreeSize(0);
  69311. }
  69312. if (this._bottomNode) {
  69313. levelSize += this._bottomNode.evalFreeSize(0);
  69314. }
  69315. return levelSize + size;
  69316. };
  69317. PackedRect.TpsSize = BABYLON.Size.Zero();
  69318. return PackedRect;
  69319. }());
  69320. BABYLON.PackedRect = PackedRect;
  69321. /**
  69322. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  69323. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  69324. * 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.
  69325. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  69326. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  69327. */
  69328. var RectPackingMap = (function (_super) {
  69329. __extends(RectPackingMap, _super);
  69330. /**
  69331. * Create an instance of the object with a dimension using the given size
  69332. * @param size The dimension of the rectangle that will contain all the sub ones.
  69333. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  69334. */
  69335. function RectPackingMap(size, margin) {
  69336. if (margin === void 0) { margin = 0; }
  69337. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  69338. _this._margin = margin;
  69339. _this._root = _this;
  69340. return _this;
  69341. }
  69342. /**
  69343. * Add a rectangle, finding the best location to store it into the map
  69344. * @param size the dimension of the rectangle to store
  69345. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  69346. */
  69347. RectPackingMap.prototype.addRect = function (size) {
  69348. var node = this.findAndSplitNode(size);
  69349. return node;
  69350. };
  69351. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  69352. /**
  69353. * Return the current space free normalized between [0;1]
  69354. * @returns {}
  69355. */
  69356. get: function () {
  69357. var freeSize = 0;
  69358. freeSize = this.evalFreeSize(freeSize);
  69359. return freeSize / (this._size.width * this._size.height);
  69360. },
  69361. enumerable: true,
  69362. configurable: true
  69363. });
  69364. return RectPackingMap;
  69365. }(PackedRect));
  69366. BABYLON.RectPackingMap = RectPackingMap;
  69367. })(BABYLON || (BABYLON = {}));
  69368. //# sourceMappingURL=babylon.rectPackingMap.js.map
  69369. var BABYLON;
  69370. (function (BABYLON) {
  69371. /**
  69372. * This groups together the common properties used for image processing either in direct forward pass
  69373. * or through post processing effect depending on the use of the image processing pipeline in your scene
  69374. * or not.
  69375. */
  69376. var ImageProcessingConfiguration = (function () {
  69377. function ImageProcessingConfiguration() {
  69378. /**
  69379. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  69380. */
  69381. this.colorCurves = new BABYLON.ColorCurves();
  69382. this._colorCurvesEnabled = false;
  69383. this._colorGradingEnabled = false;
  69384. this._colorGradingWithGreenDepth = false;
  69385. this._colorGradingBGR = false;
  69386. this._exposure = 1.0;
  69387. this._toneMappingEnabled = false;
  69388. this._contrast = 1.0;
  69389. /**
  69390. * Vignette stretch size.
  69391. */
  69392. this.vignetteStretch = 0;
  69393. /**
  69394. * Vignette centre X Offset.
  69395. */
  69396. this.vignetteCentreX = 0;
  69397. /**
  69398. * Vignette centre Y Offset.
  69399. */
  69400. this.vignetteCentreY = 0;
  69401. /**
  69402. * Vignette weight or intensity of the vignette effect.
  69403. */
  69404. this.vignetteWeight = 1.5;
  69405. /**
  69406. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69407. * if vignetteEnabled is set to true.
  69408. */
  69409. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  69410. /**
  69411. * Camera field of view used by the Vignette effect.
  69412. */
  69413. this.vignetteCameraFov = 0.5;
  69414. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  69415. this._vignetteEnabled = false;
  69416. this._applyByPostProcess = false;
  69417. /**
  69418. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  69419. * @type {BABYLON.Observable}
  69420. */
  69421. this.onUpdateParameters = new BABYLON.Observable();
  69422. }
  69423. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  69424. /**
  69425. * Gets wether the color curves effect is enabled.
  69426. */
  69427. get: function () {
  69428. return this._colorCurvesEnabled;
  69429. },
  69430. /**
  69431. * Sets wether the color curves effect is enabled.
  69432. */
  69433. set: function (value) {
  69434. if (this._colorCurvesEnabled === value) {
  69435. return;
  69436. }
  69437. this._colorCurvesEnabled = value;
  69438. this._updateParameters();
  69439. },
  69440. enumerable: true,
  69441. configurable: true
  69442. });
  69443. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  69444. /**
  69445. * Gets wether the color grading effect is enabled.
  69446. */
  69447. get: function () {
  69448. return this._colorGradingEnabled;
  69449. },
  69450. /**
  69451. * Sets wether the color grading effect is enabled.
  69452. */
  69453. set: function (value) {
  69454. if (this._colorGradingEnabled === value) {
  69455. return;
  69456. }
  69457. this._colorGradingEnabled = value;
  69458. this._updateParameters();
  69459. },
  69460. enumerable: true,
  69461. configurable: true
  69462. });
  69463. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  69464. /**
  69465. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  69466. */
  69467. get: function () {
  69468. return this._colorGradingWithGreenDepth;
  69469. },
  69470. /**
  69471. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  69472. */
  69473. set: function (value) {
  69474. if (this._colorGradingWithGreenDepth === value) {
  69475. return;
  69476. }
  69477. this._colorGradingWithGreenDepth = value;
  69478. this._updateParameters();
  69479. },
  69480. enumerable: true,
  69481. configurable: true
  69482. });
  69483. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  69484. /**
  69485. * Gets wether the color grading texture contains BGR values.
  69486. */
  69487. get: function () {
  69488. return this._colorGradingBGR;
  69489. },
  69490. /**
  69491. * Sets wether the color grading texture contains BGR values.
  69492. */
  69493. set: function (value) {
  69494. if (this._colorGradingBGR === value) {
  69495. return;
  69496. }
  69497. this._colorGradingBGR = value;
  69498. this._updateParameters();
  69499. },
  69500. enumerable: true,
  69501. configurable: true
  69502. });
  69503. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  69504. /**
  69505. * Gets the Exposure used in the effect.
  69506. */
  69507. get: function () {
  69508. return this._exposure;
  69509. },
  69510. /**
  69511. * Sets the Exposure used in the effect.
  69512. */
  69513. set: function (value) {
  69514. if (this._exposure === value) {
  69515. return;
  69516. }
  69517. this._exposure = value;
  69518. this._updateParameters();
  69519. },
  69520. enumerable: true,
  69521. configurable: true
  69522. });
  69523. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  69524. /**
  69525. * Gets wether the tone mapping effect is enabled.
  69526. */
  69527. get: function () {
  69528. return this._toneMappingEnabled;
  69529. },
  69530. /**
  69531. * Sets wether the tone mapping effect is enabled.
  69532. */
  69533. set: function (value) {
  69534. if (this._toneMappingEnabled === value) {
  69535. return;
  69536. }
  69537. this._toneMappingEnabled = value;
  69538. this._updateParameters();
  69539. },
  69540. enumerable: true,
  69541. configurable: true
  69542. });
  69543. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  69544. /**
  69545. * Gets the contrast used in the effect.
  69546. */
  69547. get: function () {
  69548. return this._contrast;
  69549. },
  69550. /**
  69551. * Sets the contrast used in the effect.
  69552. */
  69553. set: function (value) {
  69554. if (this._contrast === value) {
  69555. return;
  69556. }
  69557. this._contrast = value;
  69558. this._updateParameters();
  69559. },
  69560. enumerable: true,
  69561. configurable: true
  69562. });
  69563. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  69564. /**
  69565. * Gets the vignette blend mode allowing different kind of effect.
  69566. */
  69567. get: function () {
  69568. return this._vignetteBlendMode;
  69569. },
  69570. /**
  69571. * Sets the vignette blend mode allowing different kind of effect.
  69572. */
  69573. set: function (value) {
  69574. if (this._vignetteBlendMode === value) {
  69575. return;
  69576. }
  69577. this._vignetteBlendMode = value;
  69578. this._updateParameters();
  69579. },
  69580. enumerable: true,
  69581. configurable: true
  69582. });
  69583. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  69584. /**
  69585. * Gets wether the vignette effect is enabled.
  69586. */
  69587. get: function () {
  69588. return this._vignetteEnabled;
  69589. },
  69590. /**
  69591. * Sets wether the vignette effect is enabled.
  69592. */
  69593. set: function (value) {
  69594. if (this._vignetteEnabled === value) {
  69595. return;
  69596. }
  69597. this._vignetteEnabled = value;
  69598. this._updateParameters();
  69599. },
  69600. enumerable: true,
  69601. configurable: true
  69602. });
  69603. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  69604. /**
  69605. * Gets wether the image processing is applied through a post process or not.
  69606. */
  69607. get: function () {
  69608. return this._applyByPostProcess;
  69609. },
  69610. /**
  69611. * Sets wether the image processing is applied through a post process or not.
  69612. */
  69613. set: function (value) {
  69614. if (this._applyByPostProcess === value) {
  69615. return;
  69616. }
  69617. this._applyByPostProcess = value;
  69618. this._updateParameters();
  69619. },
  69620. enumerable: true,
  69621. configurable: true
  69622. });
  69623. /**
  69624. * Method called each time the image processing information changes requires to recompile the effect.
  69625. */
  69626. ImageProcessingConfiguration.prototype._updateParameters = function () {
  69627. this.onUpdateParameters.notifyObservers(this);
  69628. };
  69629. ImageProcessingConfiguration.prototype.getClassName = function () {
  69630. return "ImageProcessingConfiguration";
  69631. };
  69632. /**
  69633. * Prepare the list of uniforms associated with the Image Processing effects.
  69634. * @param uniformsList The list of uniforms used in the effect
  69635. * @param defines the list of defines currently in use
  69636. */
  69637. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  69638. if (defines.EXPOSURE) {
  69639. uniforms.push("exposureLinear");
  69640. }
  69641. if (defines.CONTRAST) {
  69642. uniforms.push("contrast");
  69643. }
  69644. if (defines.COLORGRADING) {
  69645. uniforms.push("colorTransformSettings");
  69646. }
  69647. if (defines.VIGNETTE) {
  69648. uniforms.push("vInverseScreenSize");
  69649. uniforms.push("vignetteSettings1");
  69650. uniforms.push("vignetteSettings2");
  69651. }
  69652. if (defines.COLORCURVES) {
  69653. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  69654. }
  69655. };
  69656. /**
  69657. * Prepare the list of samplers associated with the Image Processing effects.
  69658. * @param uniformsList The list of uniforms used in the effect
  69659. * @param defines the list of defines currently in use
  69660. */
  69661. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  69662. if (defines.COLORGRADING) {
  69663. samplersList.push("txColorTransform");
  69664. }
  69665. };
  69666. /**
  69667. * Prepare the list of defines associated to the shader.
  69668. * @param defines the list of defines to complete
  69669. */
  69670. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  69671. defines.VIGNETTE = this.vignetteEnabled;
  69672. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  69673. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  69674. defines.TONEMAPPING = this.toneMappingEnabled;
  69675. defines.CONTRAST = (this.contrast !== 1.0);
  69676. defines.EXPOSURE = (this.exposure !== 1.0);
  69677. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  69678. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  69679. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  69680. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  69681. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  69682. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  69683. };
  69684. /**
  69685. * Returns true if all the image processing information are ready.
  69686. */
  69687. ImageProcessingConfiguration.prototype.isReady = function () {
  69688. // Color Grading texure can not be none blocking.
  69689. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  69690. };
  69691. /**
  69692. * Binds the image processing to the shader.
  69693. * @param effect The effect to bind to
  69694. */
  69695. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  69696. if (aspectRatio === void 0) { aspectRatio = 1; }
  69697. // Color Curves
  69698. if (this._colorCurvesEnabled) {
  69699. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  69700. }
  69701. // Vignette
  69702. if (this._vignetteEnabled) {
  69703. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  69704. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  69705. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  69706. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  69707. var vignetteScaleX = vignetteScaleY * aspectRatio;
  69708. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  69709. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  69710. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  69711. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  69712. var vignettePower = -2.0 * this.vignetteWeight;
  69713. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  69714. }
  69715. // Exposure
  69716. effect.setFloat("exposureLinear", this.exposure);
  69717. // Contrast
  69718. effect.setFloat("contrast", this.contrast);
  69719. // Color transform settings
  69720. if (this.colorGradingTexture) {
  69721. effect.setTexture("txColorTransform", this.colorGradingTexture);
  69722. var textureSize = this.colorGradingTexture.getSize().height;
  69723. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  69724. 0.5 / textureSize, // textureOffset
  69725. textureSize, // textureSize
  69726. this.colorGradingTexture.level // weight
  69727. );
  69728. }
  69729. };
  69730. /**
  69731. * Clones the current image processing instance.
  69732. * @return The cloned image processing
  69733. */
  69734. ImageProcessingConfiguration.prototype.clone = function () {
  69735. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  69736. };
  69737. /**
  69738. * Serializes the current image processing instance to a json representation.
  69739. * @return a JSON representation
  69740. */
  69741. ImageProcessingConfiguration.prototype.serialize = function () {
  69742. return BABYLON.SerializationHelper.Serialize(this);
  69743. };
  69744. /**
  69745. * Parses the image processing from a json representation.
  69746. * @param source the JSON source to parse
  69747. * @return The parsed image processing
  69748. */
  69749. ImageProcessingConfiguration.Parse = function (source) {
  69750. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  69751. };
  69752. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  69753. /**
  69754. * Used to apply the vignette as a mix with the pixel color.
  69755. */
  69756. get: function () {
  69757. return this._VIGNETTEMODE_MULTIPLY;
  69758. },
  69759. enumerable: true,
  69760. configurable: true
  69761. });
  69762. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  69763. /**
  69764. * Used to apply the vignette as a replacement of the pixel color.
  69765. */
  69766. get: function () {
  69767. return this._VIGNETTEMODE_OPAQUE;
  69768. },
  69769. enumerable: true,
  69770. configurable: true
  69771. });
  69772. // Static constants associated to the image processing.
  69773. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  69774. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  69775. __decorate([
  69776. BABYLON.serializeAsColorCurves()
  69777. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  69778. __decorate([
  69779. BABYLON.serialize()
  69780. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  69781. __decorate([
  69782. BABYLON.serializeAsTexture()
  69783. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  69784. __decorate([
  69785. BABYLON.serialize()
  69786. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  69787. __decorate([
  69788. BABYLON.serialize()
  69789. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  69790. __decorate([
  69791. BABYLON.serialize()
  69792. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  69793. __decorate([
  69794. BABYLON.serialize()
  69795. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  69796. __decorate([
  69797. BABYLON.serialize()
  69798. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  69799. __decorate([
  69800. BABYLON.serialize()
  69801. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  69802. __decorate([
  69803. BABYLON.serialize()
  69804. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  69805. __decorate([
  69806. BABYLON.serialize()
  69807. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  69808. __decorate([
  69809. BABYLON.serialize()
  69810. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  69811. __decorate([
  69812. BABYLON.serialize()
  69813. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  69814. __decorate([
  69815. BABYLON.serializeAsColor4()
  69816. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  69817. __decorate([
  69818. BABYLON.serialize()
  69819. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  69820. __decorate([
  69821. BABYLON.serialize()
  69822. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  69823. __decorate([
  69824. BABYLON.serialize()
  69825. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  69826. __decorate([
  69827. BABYLON.serialize()
  69828. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  69829. return ImageProcessingConfiguration;
  69830. }());
  69831. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  69832. })(BABYLON || (BABYLON = {}));
  69833. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  69834. var BABYLON;
  69835. (function (BABYLON) {
  69836. var serializedGeometries = [];
  69837. var serializeGeometry = function (geometry, serializationGeometries) {
  69838. if (serializedGeometries[geometry.id]) {
  69839. return;
  69840. }
  69841. if (geometry.doNotSerialize) {
  69842. return;
  69843. }
  69844. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  69845. serializationGeometries.boxes.push(geometry.serialize());
  69846. }
  69847. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  69848. serializationGeometries.spheres.push(geometry.serialize());
  69849. }
  69850. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  69851. serializationGeometries.cylinders.push(geometry.serialize());
  69852. }
  69853. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  69854. serializationGeometries.toruses.push(geometry.serialize());
  69855. }
  69856. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  69857. serializationGeometries.grounds.push(geometry.serialize());
  69858. }
  69859. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  69860. serializationGeometries.planes.push(geometry.serialize());
  69861. }
  69862. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  69863. serializationGeometries.torusKnots.push(geometry.serialize());
  69864. }
  69865. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  69866. throw new Error("Unknown primitive type");
  69867. }
  69868. else {
  69869. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  69870. }
  69871. serializedGeometries[geometry.id] = true;
  69872. };
  69873. var serializeMesh = function (mesh, serializationScene) {
  69874. var serializationObject = {};
  69875. // Geometry
  69876. var geometry = mesh._geometry;
  69877. if (geometry) {
  69878. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  69879. // 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
  69880. serializeGeometry(geometry, serializationScene.geometries);
  69881. }
  69882. }
  69883. // Custom
  69884. if (mesh.serialize) {
  69885. mesh.serialize(serializationObject);
  69886. }
  69887. return serializationObject;
  69888. };
  69889. var finalizeSingleMesh = function (mesh, serializationObject) {
  69890. //only works if the mesh is already loaded
  69891. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  69892. //serialize material
  69893. if (mesh.material) {
  69894. if (mesh.material instanceof BABYLON.StandardMaterial) {
  69895. serializationObject.materials = serializationObject.materials || [];
  69896. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  69897. serializationObject.materials.push(mesh.material.serialize());
  69898. }
  69899. }
  69900. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  69901. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  69902. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  69903. serializationObject.multiMaterials.push(mesh.material.serialize());
  69904. }
  69905. }
  69906. }
  69907. //serialize geometry
  69908. var geometry = mesh._geometry;
  69909. if (geometry) {
  69910. if (!serializationObject.geometries) {
  69911. serializationObject.geometries = {};
  69912. serializationObject.geometries.boxes = [];
  69913. serializationObject.geometries.spheres = [];
  69914. serializationObject.geometries.cylinders = [];
  69915. serializationObject.geometries.toruses = [];
  69916. serializationObject.geometries.grounds = [];
  69917. serializationObject.geometries.planes = [];
  69918. serializationObject.geometries.torusKnots = [];
  69919. serializationObject.geometries.vertexData = [];
  69920. }
  69921. serializeGeometry(geometry, serializationObject.geometries);
  69922. }
  69923. // Skeletons
  69924. if (mesh.skeleton) {
  69925. serializationObject.skeletons = serializationObject.skeletons || [];
  69926. serializationObject.skeletons.push(mesh.skeleton.serialize());
  69927. }
  69928. //serialize the actual mesh
  69929. serializationObject.meshes = serializationObject.meshes || [];
  69930. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  69931. }
  69932. };
  69933. var SceneSerializer = (function () {
  69934. function SceneSerializer() {
  69935. }
  69936. SceneSerializer.ClearCache = function () {
  69937. serializedGeometries = [];
  69938. };
  69939. SceneSerializer.Serialize = function (scene) {
  69940. var serializationObject = {};
  69941. SceneSerializer.ClearCache();
  69942. // Scene
  69943. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  69944. serializationObject.autoClear = scene.autoClear;
  69945. serializationObject.clearColor = scene.clearColor.asArray();
  69946. serializationObject.ambientColor = scene.ambientColor.asArray();
  69947. serializationObject.gravity = scene.gravity.asArray();
  69948. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  69949. serializationObject.workerCollisions = scene.workerCollisions;
  69950. // Fog
  69951. if (scene.fogMode && scene.fogMode !== 0) {
  69952. serializationObject.fogMode = scene.fogMode;
  69953. serializationObject.fogColor = scene.fogColor.asArray();
  69954. serializationObject.fogStart = scene.fogStart;
  69955. serializationObject.fogEnd = scene.fogEnd;
  69956. serializationObject.fogDensity = scene.fogDensity;
  69957. }
  69958. //Physics
  69959. if (scene.isPhysicsEnabled()) {
  69960. serializationObject.physicsEnabled = true;
  69961. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  69962. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  69963. }
  69964. // Metadata
  69965. if (scene.metadata) {
  69966. serializationObject.metadata = scene.metadata;
  69967. }
  69968. // Morph targets
  69969. serializationObject.morphTargetManagers = [];
  69970. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  69971. var abstractMesh = _a[_i];
  69972. var manager = abstractMesh.morphTargetManager;
  69973. if (manager) {
  69974. serializationObject.morphTargetManagers.push(manager.serialize());
  69975. }
  69976. }
  69977. // Lights
  69978. serializationObject.lights = [];
  69979. var index;
  69980. var light;
  69981. for (index = 0; index < scene.lights.length; index++) {
  69982. light = scene.lights[index];
  69983. if (!light.doNotSerialize) {
  69984. serializationObject.lights.push(light.serialize());
  69985. }
  69986. }
  69987. // Cameras
  69988. serializationObject.cameras = [];
  69989. for (index = 0; index < scene.cameras.length; index++) {
  69990. var camera = scene.cameras[index];
  69991. if (!camera.doNotSerialize) {
  69992. serializationObject.cameras.push(camera.serialize());
  69993. }
  69994. }
  69995. if (scene.activeCamera) {
  69996. serializationObject.activeCameraID = scene.activeCamera.id;
  69997. }
  69998. // Animations
  69999. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  70000. // Materials
  70001. serializationObject.materials = [];
  70002. serializationObject.multiMaterials = [];
  70003. var material;
  70004. for (index = 0; index < scene.materials.length; index++) {
  70005. material = scene.materials[index];
  70006. if (!material.doNotSerialize) {
  70007. serializationObject.materials.push(material.serialize());
  70008. }
  70009. }
  70010. // MultiMaterials
  70011. serializationObject.multiMaterials = [];
  70012. for (index = 0; index < scene.multiMaterials.length; index++) {
  70013. var multiMaterial = scene.multiMaterials[index];
  70014. serializationObject.multiMaterials.push(multiMaterial.serialize());
  70015. }
  70016. // Skeletons
  70017. serializationObject.skeletons = [];
  70018. for (index = 0; index < scene.skeletons.length; index++) {
  70019. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  70020. }
  70021. // Geometries
  70022. serializationObject.geometries = {};
  70023. serializationObject.geometries.boxes = [];
  70024. serializationObject.geometries.spheres = [];
  70025. serializationObject.geometries.cylinders = [];
  70026. serializationObject.geometries.toruses = [];
  70027. serializationObject.geometries.grounds = [];
  70028. serializationObject.geometries.planes = [];
  70029. serializationObject.geometries.torusKnots = [];
  70030. serializationObject.geometries.vertexData = [];
  70031. serializedGeometries = [];
  70032. var geometries = scene.getGeometries();
  70033. for (index = 0; index < geometries.length; index++) {
  70034. var geometry = geometries[index];
  70035. if (geometry.isReady()) {
  70036. serializeGeometry(geometry, serializationObject.geometries);
  70037. }
  70038. }
  70039. // Meshes
  70040. serializationObject.meshes = [];
  70041. for (index = 0; index < scene.meshes.length; index++) {
  70042. var abstractMesh = scene.meshes[index];
  70043. if (abstractMesh instanceof BABYLON.Mesh) {
  70044. var mesh = abstractMesh;
  70045. if (!mesh.doNotSerialize) {
  70046. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  70047. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  70048. }
  70049. }
  70050. }
  70051. }
  70052. // Particles Systems
  70053. serializationObject.particleSystems = [];
  70054. for (index = 0; index < scene.particleSystems.length; index++) {
  70055. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  70056. }
  70057. // Lens flares
  70058. serializationObject.lensFlareSystems = [];
  70059. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  70060. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  70061. }
  70062. // Shadows
  70063. serializationObject.shadowGenerators = [];
  70064. for (index = 0; index < scene.lights.length; index++) {
  70065. light = scene.lights[index];
  70066. var shadowGenerator = light.getShadowGenerator();
  70067. if (shadowGenerator) {
  70068. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  70069. }
  70070. }
  70071. // Action Manager
  70072. if (scene.actionManager) {
  70073. serializationObject.actions = scene.actionManager.serialize("scene");
  70074. }
  70075. // Audio
  70076. serializationObject.sounds = [];
  70077. for (index = 0; index < scene.soundTracks.length; index++) {
  70078. var soundtrack = scene.soundTracks[index];
  70079. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70080. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70081. }
  70082. }
  70083. return serializationObject;
  70084. };
  70085. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  70086. if (withParents === void 0) { withParents = false; }
  70087. if (withChildren === void 0) { withChildren = false; }
  70088. var serializationObject = {};
  70089. SceneSerializer.ClearCache();
  70090. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  70091. if (withParents || withChildren) {
  70092. //deliberate for loop! not for each, appended should be processed as well.
  70093. for (var i = 0; i < toSerialize.length; ++i) {
  70094. if (withChildren) {
  70095. toSerialize[i].getDescendants().forEach(function (node) {
  70096. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  70097. toSerialize.push(node);
  70098. }
  70099. });
  70100. }
  70101. //make sure the array doesn't contain the object already
  70102. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  70103. toSerialize.push(toSerialize[i].parent);
  70104. }
  70105. }
  70106. }
  70107. toSerialize.forEach(function (mesh) {
  70108. finalizeSingleMesh(mesh, serializationObject);
  70109. });
  70110. return serializationObject;
  70111. };
  70112. return SceneSerializer;
  70113. }());
  70114. BABYLON.SceneSerializer = SceneSerializer;
  70115. })(BABYLON || (BABYLON = {}));
  70116. //# sourceMappingURL=babylon.sceneSerializer.js.map
  70117. var BABYLON;
  70118. (function (BABYLON) {
  70119. var ReflectionProbe = (function () {
  70120. function ReflectionProbe(name, size, scene, generateMipMaps) {
  70121. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70122. var _this = this;
  70123. this.name = name;
  70124. this._viewMatrix = BABYLON.Matrix.Identity();
  70125. this._target = BABYLON.Vector3.Zero();
  70126. this._add = BABYLON.Vector3.Zero();
  70127. this.invertYAxis = false;
  70128. this.position = BABYLON.Vector3.Zero();
  70129. this._scene = scene;
  70130. this._scene.reflectionProbes.push(this);
  70131. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  70132. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  70133. switch (faceIndex) {
  70134. case 0:
  70135. _this._add.copyFromFloats(1, 0, 0);
  70136. break;
  70137. case 1:
  70138. _this._add.copyFromFloats(-1, 0, 0);
  70139. break;
  70140. case 2:
  70141. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  70142. break;
  70143. case 3:
  70144. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  70145. break;
  70146. case 4:
  70147. _this._add.copyFromFloats(0, 0, 1);
  70148. break;
  70149. case 5:
  70150. _this._add.copyFromFloats(0, 0, -1);
  70151. break;
  70152. }
  70153. if (_this._attachedMesh) {
  70154. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  70155. }
  70156. _this.position.addToRef(_this._add, _this._target);
  70157. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  70158. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  70159. });
  70160. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  70161. scene.updateTransformMatrix(true);
  70162. });
  70163. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70164. }
  70165. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  70166. get: function () {
  70167. return this._renderTargetTexture.samples;
  70168. },
  70169. set: function (value) {
  70170. this._renderTargetTexture.samples = value;
  70171. },
  70172. enumerable: true,
  70173. configurable: true
  70174. });
  70175. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  70176. get: function () {
  70177. return this._renderTargetTexture.refreshRate;
  70178. },
  70179. set: function (value) {
  70180. this._renderTargetTexture.refreshRate = value;
  70181. },
  70182. enumerable: true,
  70183. configurable: true
  70184. });
  70185. ReflectionProbe.prototype.getScene = function () {
  70186. return this._scene;
  70187. };
  70188. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  70189. get: function () {
  70190. return this._renderTargetTexture;
  70191. },
  70192. enumerable: true,
  70193. configurable: true
  70194. });
  70195. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  70196. get: function () {
  70197. return this._renderTargetTexture.renderList;
  70198. },
  70199. enumerable: true,
  70200. configurable: true
  70201. });
  70202. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  70203. this._attachedMesh = mesh;
  70204. };
  70205. /**
  70206. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70207. *
  70208. * @param renderingGroupId The rendering group id corresponding to its index
  70209. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70210. */
  70211. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70212. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70213. };
  70214. ReflectionProbe.prototype.dispose = function () {
  70215. var index = this._scene.reflectionProbes.indexOf(this);
  70216. if (index !== -1) {
  70217. // Remove from the scene if found
  70218. this._scene.reflectionProbes.splice(index, 1);
  70219. }
  70220. if (this._renderTargetTexture) {
  70221. this._renderTargetTexture.dispose();
  70222. this._renderTargetTexture = null;
  70223. }
  70224. };
  70225. return ReflectionProbe;
  70226. }());
  70227. BABYLON.ReflectionProbe = ReflectionProbe;
  70228. })(BABYLON || (BABYLON = {}));
  70229. //# sourceMappingURL=babylon.reflectionProbe.js.map
  70230. var BABYLON;
  70231. (function (BABYLON) {
  70232. var Layer = (function () {
  70233. function Layer(name, imgUrl, scene, isBackground, color) {
  70234. this.name = name;
  70235. this.scale = new BABYLON.Vector2(1, 1);
  70236. this.offset = new BABYLON.Vector2(0, 0);
  70237. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  70238. this.layerMask = 0x0FFFFFFF;
  70239. this._vertexBuffers = {};
  70240. // Events
  70241. /**
  70242. * An event triggered when the layer is disposed.
  70243. * @type {BABYLON.Observable}
  70244. */
  70245. this.onDisposeObservable = new BABYLON.Observable();
  70246. /**
  70247. * An event triggered before rendering the scene
  70248. * @type {BABYLON.Observable}
  70249. */
  70250. this.onBeforeRenderObservable = new BABYLON.Observable();
  70251. /**
  70252. * An event triggered after rendering the scene
  70253. * @type {BABYLON.Observable}
  70254. */
  70255. this.onAfterRenderObservable = new BABYLON.Observable();
  70256. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  70257. this.isBackground = isBackground === undefined ? true : isBackground;
  70258. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  70259. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70260. this._scene.layers.push(this);
  70261. var engine = this._scene.getEngine();
  70262. // VBO
  70263. var vertices = [];
  70264. vertices.push(1, 1);
  70265. vertices.push(-1, 1);
  70266. vertices.push(-1, -1);
  70267. vertices.push(1, -1);
  70268. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70269. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  70270. this._createIndexBuffer();
  70271. // Effects
  70272. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  70273. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  70274. }
  70275. Object.defineProperty(Layer.prototype, "onDispose", {
  70276. set: function (callback) {
  70277. if (this._onDisposeObserver) {
  70278. this.onDisposeObservable.remove(this._onDisposeObserver);
  70279. }
  70280. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  70281. },
  70282. enumerable: true,
  70283. configurable: true
  70284. });
  70285. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  70286. set: function (callback) {
  70287. if (this._onBeforeRenderObserver) {
  70288. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  70289. }
  70290. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  70291. },
  70292. enumerable: true,
  70293. configurable: true
  70294. });
  70295. Object.defineProperty(Layer.prototype, "onAfterRender", {
  70296. set: function (callback) {
  70297. if (this._onAfterRenderObserver) {
  70298. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  70299. }
  70300. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  70301. },
  70302. enumerable: true,
  70303. configurable: true
  70304. });
  70305. Layer.prototype._createIndexBuffer = function () {
  70306. var engine = this._scene.getEngine();
  70307. // Indices
  70308. var indices = [];
  70309. indices.push(0);
  70310. indices.push(1);
  70311. indices.push(2);
  70312. indices.push(0);
  70313. indices.push(2);
  70314. indices.push(3);
  70315. this._indexBuffer = engine.createIndexBuffer(indices);
  70316. };
  70317. Layer.prototype._rebuild = function () {
  70318. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  70319. this._createIndexBuffer();
  70320. };
  70321. Layer.prototype.render = function () {
  70322. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  70323. // Check
  70324. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  70325. return;
  70326. var engine = this._scene.getEngine();
  70327. this.onBeforeRenderObservable.notifyObservers(this);
  70328. // Render
  70329. engine.enableEffect(currentEffect);
  70330. engine.setState(false);
  70331. // Texture
  70332. currentEffect.setTexture("textureSampler", this.texture);
  70333. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  70334. // Color
  70335. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  70336. // Scale / offset
  70337. currentEffect.setVector2("offset", this.offset);
  70338. currentEffect.setVector2("scale", this.scale);
  70339. // VBOs
  70340. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  70341. // Draw order
  70342. if (!this.alphaTest) {
  70343. engine.setAlphaMode(this.alphaBlendingMode);
  70344. engine.draw(true, 0, 6);
  70345. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70346. }
  70347. else {
  70348. engine.draw(true, 0, 6);
  70349. }
  70350. this.onAfterRenderObservable.notifyObservers(this);
  70351. };
  70352. Layer.prototype.dispose = function () {
  70353. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70354. if (vertexBuffer) {
  70355. vertexBuffer.dispose();
  70356. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70357. }
  70358. if (this._indexBuffer) {
  70359. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70360. this._indexBuffer = null;
  70361. }
  70362. if (this.texture) {
  70363. this.texture.dispose();
  70364. this.texture = null;
  70365. }
  70366. // Remove from scene
  70367. var index = this._scene.layers.indexOf(this);
  70368. this._scene.layers.splice(index, 1);
  70369. // Callback
  70370. this.onDisposeObservable.notifyObservers(this);
  70371. this.onDisposeObservable.clear();
  70372. this.onAfterRenderObservable.clear();
  70373. this.onBeforeRenderObservable.clear();
  70374. };
  70375. return Layer;
  70376. }());
  70377. BABYLON.Layer = Layer;
  70378. })(BABYLON || (BABYLON = {}));
  70379. //# sourceMappingURL=babylon.layer.js.map
  70380. var BABYLON;
  70381. (function (BABYLON) {
  70382. var TextureTools = (function () {
  70383. function TextureTools() {
  70384. }
  70385. /**
  70386. * Uses the GPU to create a copy texture rescaled at a given size
  70387. * @param texture Texture to copy from
  70388. * @param width Desired width
  70389. * @param height Desired height
  70390. * @return Generated texture
  70391. */
  70392. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  70393. if (useBilinearMode === void 0) { useBilinearMode = true; }
  70394. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  70395. var scene = texture.getScene();
  70396. var engine = scene.getEngine();
  70397. rtt.wrapU = texture.wrapU;
  70398. rtt.wrapV = texture.wrapV;
  70399. rtt.uOffset = texture.uOffset;
  70400. rtt.vOffset = texture.vOffset;
  70401. rtt.uScale = texture.uScale;
  70402. rtt.vScale = texture.vScale;
  70403. rtt.uAng = texture.uAng;
  70404. rtt.vAng = texture.vAng;
  70405. rtt.wAng = texture.wAng;
  70406. rtt.coordinatesIndex = texture.coordinatesIndex;
  70407. rtt.level = texture.level;
  70408. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  70409. rtt._texture.isReady = false;
  70410. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70411. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70412. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70413. passPostProcess.getEffect().executeWhenCompiled(function () {
  70414. passPostProcess.onApply = function (effect) {
  70415. effect.setTexture("textureSampler", texture);
  70416. };
  70417. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  70418. engine.unBindFramebuffer(rtt.getInternalTexture());
  70419. rtt.disposeFramebufferObjects();
  70420. passPostProcess.dispose();
  70421. rtt._texture.isReady = true;
  70422. });
  70423. return rtt;
  70424. };
  70425. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  70426. if (!scene._environmentBRDFTexture) {
  70427. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70428. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70429. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70430. scene._environmentBRDFTexture = texture;
  70431. }
  70432. return scene._environmentBRDFTexture;
  70433. };
  70434. 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=";
  70435. return TextureTools;
  70436. }());
  70437. BABYLON.TextureTools = TextureTools;
  70438. })(BABYLON || (BABYLON = {}));
  70439. //# sourceMappingURL=babylon.textureTools.js.map
  70440. var BABYLON;
  70441. (function (BABYLON) {
  70442. var FramingBehavior = (function () {
  70443. function FramingBehavior() {
  70444. this._mode = FramingBehavior.FitFrustumSidesMode;
  70445. this._radiusScale = 1.0;
  70446. this._positionScale = 0.5;
  70447. this._defaultElevation = 0.3;
  70448. this._elevationReturnTime = 1500;
  70449. this._elevationReturnWaitTime = 1000;
  70450. this._zoomStopsAnimation = false;
  70451. this._framingTime = 1500;
  70452. this._isPointerDown = false;
  70453. this._lastFrameTime = null;
  70454. this._lastInteractionTime = -Infinity;
  70455. // Framing control
  70456. this._animatables = new Array();
  70457. this._betaIsAnimating = false;
  70458. this._lastFrameRadius = 0;
  70459. }
  70460. Object.defineProperty(FramingBehavior.prototype, "name", {
  70461. get: function () {
  70462. return "Framing";
  70463. },
  70464. enumerable: true,
  70465. configurable: true
  70466. });
  70467. Object.defineProperty(FramingBehavior.prototype, "mode", {
  70468. /**
  70469. * Gets current mode used by the behavior.
  70470. */
  70471. get: function () {
  70472. return this._mode;
  70473. },
  70474. /**
  70475. * Sets the current mode used by the behavior
  70476. */
  70477. set: function (mode) {
  70478. this._mode = mode;
  70479. },
  70480. enumerable: true,
  70481. configurable: true
  70482. });
  70483. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  70484. /**
  70485. * Gets the scale applied to the radius
  70486. */
  70487. get: function () {
  70488. return this._radiusScale;
  70489. },
  70490. /**
  70491. * Sets the scale applied to the radius (1 by default)
  70492. */
  70493. set: function (radius) {
  70494. this._radiusScale = radius;
  70495. },
  70496. enumerable: true,
  70497. configurable: true
  70498. });
  70499. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  70500. /**
  70501. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  70502. */
  70503. get: function () {
  70504. return this._positionScale;
  70505. },
  70506. /**
  70507. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  70508. */
  70509. set: function (scale) {
  70510. this._positionScale = scale;
  70511. },
  70512. enumerable: true,
  70513. configurable: true
  70514. });
  70515. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  70516. /**
  70517. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  70518. * behaviour is triggered, in radians.
  70519. */
  70520. get: function () {
  70521. return this._defaultElevation;
  70522. },
  70523. /**
  70524. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  70525. * behaviour is triggered, in radians.
  70526. */
  70527. set: function (elevation) {
  70528. this._defaultElevation = elevation;
  70529. },
  70530. enumerable: true,
  70531. configurable: true
  70532. });
  70533. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  70534. /**
  70535. * Gets the time (in milliseconds) taken to return to the default beta position.
  70536. * Negative value indicates camera should not return to default.
  70537. */
  70538. get: function () {
  70539. return this._elevationReturnTime;
  70540. },
  70541. /**
  70542. * Sets the time (in milliseconds) taken to return to the default beta position.
  70543. * Negative value indicates camera should not return to default.
  70544. */
  70545. set: function (speed) {
  70546. this._elevationReturnTime = speed;
  70547. },
  70548. enumerable: true,
  70549. configurable: true
  70550. });
  70551. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  70552. /**
  70553. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  70554. */
  70555. get: function () {
  70556. return this._elevationReturnWaitTime;
  70557. },
  70558. /**
  70559. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  70560. */
  70561. set: function (time) {
  70562. this._elevationReturnWaitTime = time;
  70563. },
  70564. enumerable: true,
  70565. configurable: true
  70566. });
  70567. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  70568. /**
  70569. * Gets the flag that indicates if user zooming should stop animation.
  70570. */
  70571. get: function () {
  70572. return this._zoomStopsAnimation;
  70573. },
  70574. /**
  70575. * Sets the flag that indicates if user zooming should stop animation.
  70576. */
  70577. set: function (flag) {
  70578. this._zoomStopsAnimation = flag;
  70579. },
  70580. enumerable: true,
  70581. configurable: true
  70582. });
  70583. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  70584. /**
  70585. * Gets the transition time when framing the mesh, in milliseconds
  70586. */
  70587. get: function () {
  70588. return this._framingTime;
  70589. },
  70590. /**
  70591. * Sets the transition time when framing the mesh, in milliseconds
  70592. */
  70593. set: function (time) {
  70594. this._framingTime = time;
  70595. },
  70596. enumerable: true,
  70597. configurable: true
  70598. });
  70599. FramingBehavior.prototype.attach = function (camera) {
  70600. var _this = this;
  70601. this._attachedCamera = camera;
  70602. var scene = this._attachedCamera.getScene();
  70603. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  70604. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  70605. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70606. _this._isPointerDown = true;
  70607. return;
  70608. }
  70609. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  70610. _this._isPointerDown = false;
  70611. }
  70612. });
  70613. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  70614. if (mesh) {
  70615. _this.zoomOnMesh(mesh);
  70616. }
  70617. });
  70618. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70619. // Stop the animation if there is user interaction and the animation should stop for this interaction
  70620. _this._applyUserInteraction();
  70621. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  70622. // back to the default position after a given timeout
  70623. _this._maintainCameraAboveGround();
  70624. });
  70625. };
  70626. FramingBehavior.prototype.detach = function () {
  70627. var scene = this._attachedCamera.getScene();
  70628. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  70629. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70630. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70631. this._attachedCamera = null;
  70632. };
  70633. /**
  70634. * Targets the given mesh and updates zoom level accordingly.
  70635. * @param mesh The mesh to target.
  70636. * @param radius Optional. If a cached radius position already exists, overrides default.
  70637. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  70638. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  70639. * @param onAnimationEnd Callback triggered at the end of the framing animation
  70640. */
  70641. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  70642. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  70643. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  70644. mesh.computeWorldMatrix(true);
  70645. var boundingBox = mesh.getBoundingInfo().boundingBox;
  70646. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  70647. };
  70648. /**
  70649. * Targets the given mesh and updates zoom level accordingly.
  70650. * @param mesh The mesh to target.
  70651. * @param radius Optional. If a cached radius position already exists, overrides default.
  70652. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  70653. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  70654. * @param onAnimationEnd Callback triggered at the end of the framing animation
  70655. */
  70656. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  70657. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  70658. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  70659. var zoomTarget;
  70660. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  70661. var bottom = minimumWorld.y;
  70662. var top = maximumWorld.y;
  70663. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  70664. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  70665. if (focusOnOriginXZ) {
  70666. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  70667. }
  70668. else {
  70669. var centerWorld = minimumWorld.add(radiusWorld);
  70670. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  70671. }
  70672. if (!this._vectorTransition) {
  70673. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  70674. }
  70675. this._betaIsAnimating = true;
  70676. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  70677. // sets the radius and lower radius bounds
  70678. // Small delta ensures camera is not always at lower zoom limit.
  70679. var delta = 0.1;
  70680. var radius = 0;
  70681. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  70682. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70683. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  70684. radius = position;
  70685. }
  70686. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70687. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70688. if (this._attachedCamera.lowerRadiusLimit === null) {
  70689. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  70690. }
  70691. }
  70692. // transition to new radius
  70693. if (!this._radiusTransition) {
  70694. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70695. }
  70696. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, onAnimationEnd));
  70697. };
  70698. /**
  70699. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  70700. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  70701. * frustum width.
  70702. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  70703. * to fully enclose the mesh in the viewing frustum.
  70704. */
  70705. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  70706. var size = maximumWorld.subtract(minimumWorld);
  70707. var boxVectorGlobalDiagonal = size.length();
  70708. var frustumSlope = this._getFrustumSlope();
  70709. // Formula for setting distance
  70710. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  70711. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  70712. // Horizon distance
  70713. var radius = radiusWithoutFraming * this._radiusScale;
  70714. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  70715. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  70716. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  70717. var camera = this._attachedCamera;
  70718. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70719. // Don't exceed the requested limit
  70720. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  70721. }
  70722. // Don't exceed the upper radius limit
  70723. if (camera.upperRadiusLimit) {
  70724. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  70725. }
  70726. return distance;
  70727. };
  70728. /**
  70729. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  70730. * is automatically returned to its default position (expected to be above ground plane).
  70731. */
  70732. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  70733. var _this = this;
  70734. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  70735. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  70736. var limitBeta = Math.PI * 0.5;
  70737. // Bring the camera back up if below the ground plane
  70738. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  70739. this._betaIsAnimating = true;
  70740. //Transition to new position
  70741. this.stopAllAnimations();
  70742. if (!this._betaTransition) {
  70743. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70744. }
  70745. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  70746. _this._clearAnimationLocks();
  70747. _this.stopAllAnimations();
  70748. }));
  70749. }
  70750. };
  70751. /**
  70752. * Returns the frustum slope based on the canvas ratio and camera FOV
  70753. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  70754. */
  70755. FramingBehavior.prototype._getFrustumSlope = function () {
  70756. // Calculate the viewport ratio
  70757. // Aspect Ratio is Height/Width.
  70758. var camera = this._attachedCamera;
  70759. var engine = camera.getScene().getEngine();
  70760. var aspectRatio = engine.getAspectRatio(camera);
  70761. // Camera FOV is the vertical field of view (top-bottom) in radians.
  70762. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  70763. var frustumSlopeY = Math.tan(camera.fov / 2);
  70764. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  70765. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  70766. // along the forward vector.
  70767. var frustumSlopeX = frustumSlopeY * aspectRatio;
  70768. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  70769. };
  70770. /**
  70771. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  70772. */
  70773. FramingBehavior.prototype._clearAnimationLocks = function () {
  70774. this._betaIsAnimating = false;
  70775. };
  70776. /**
  70777. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  70778. */
  70779. FramingBehavior.prototype._applyUserInteraction = function () {
  70780. if (this.isUserIsMoving) {
  70781. this._lastInteractionTime = BABYLON.Tools.Now;
  70782. this.stopAllAnimations();
  70783. this._clearAnimationLocks();
  70784. }
  70785. };
  70786. /**
  70787. * Stops and removes all animations that have been applied to the camera
  70788. */
  70789. FramingBehavior.prototype.stopAllAnimations = function () {
  70790. this._attachedCamera.animations = [];
  70791. while (this._animatables.length) {
  70792. if (this._animatables[0]) {
  70793. this._animatables[0].onAnimationEnd = null;
  70794. this._animatables[0].stop();
  70795. }
  70796. this._animatables.shift();
  70797. }
  70798. };
  70799. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  70800. /**
  70801. * Gets a value indicating if the user is moving the camera
  70802. */
  70803. get: function () {
  70804. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  70805. this._attachedCamera.inertialBetaOffset !== 0 ||
  70806. this._attachedCamera.inertialRadiusOffset !== 0 ||
  70807. this._attachedCamera.inertialPanningX !== 0 ||
  70808. this._attachedCamera.inertialPanningY !== 0 ||
  70809. this._isPointerDown;
  70810. },
  70811. enumerable: true,
  70812. configurable: true
  70813. });
  70814. /**
  70815. * The easing function used by animations
  70816. */
  70817. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  70818. /**
  70819. * The easing mode used by animations
  70820. */
  70821. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  70822. // Statics
  70823. /**
  70824. * The camera can move all the way towards the mesh.
  70825. */
  70826. FramingBehavior.IgnoreBoundsSizeMode = 0;
  70827. /**
  70828. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  70829. */
  70830. FramingBehavior.FitFrustumSidesMode = 1;
  70831. return FramingBehavior;
  70832. }());
  70833. BABYLON.FramingBehavior = FramingBehavior;
  70834. })(BABYLON || (BABYLON = {}));
  70835. //# sourceMappingURL=babylon.framingBehavior.js.map
  70836. var BABYLON;
  70837. (function (BABYLON) {
  70838. /**
  70839. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  70840. */
  70841. var BouncingBehavior = (function () {
  70842. function BouncingBehavior() {
  70843. /**
  70844. * The duration of the animation, in milliseconds
  70845. */
  70846. this.transitionDuration = 450;
  70847. /**
  70848. * Length of the distance animated by the transition when lower radius is reached
  70849. */
  70850. this.lowerRadiusTransitionRange = 2;
  70851. /**
  70852. * Length of the distance animated by the transition when upper radius is reached
  70853. */
  70854. this.upperRadiusTransitionRange = -2;
  70855. this._autoTransitionRange = false;
  70856. // Animations
  70857. this._radiusIsAnimating = false;
  70858. this._radiusBounceTransition = null;
  70859. this._animatables = new Array();
  70860. }
  70861. Object.defineProperty(BouncingBehavior.prototype, "name", {
  70862. get: function () {
  70863. return "Bouncing";
  70864. },
  70865. enumerable: true,
  70866. configurable: true
  70867. });
  70868. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  70869. /**
  70870. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  70871. */
  70872. get: function () {
  70873. return this._autoTransitionRange;
  70874. },
  70875. /**
  70876. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  70877. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  70878. */
  70879. set: function (value) {
  70880. var _this = this;
  70881. if (this._autoTransitionRange === value) {
  70882. return;
  70883. }
  70884. this._autoTransitionRange = value;
  70885. var camera = this._attachedCamera;
  70886. if (value) {
  70887. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  70888. if (!mesh) {
  70889. return;
  70890. }
  70891. mesh.computeWorldMatrix(true);
  70892. var diagonal = mesh.getBoundingInfo().diagonalLength;
  70893. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  70894. _this.upperRadiusTransitionRange = diagonal * 0.05;
  70895. });
  70896. }
  70897. else if (this._onMeshTargetChangedObserver) {
  70898. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70899. }
  70900. },
  70901. enumerable: true,
  70902. configurable: true
  70903. });
  70904. BouncingBehavior.prototype.attach = function (camera) {
  70905. var _this = this;
  70906. this._attachedCamera = camera;
  70907. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70908. // Add the bounce animation to the lower radius limit
  70909. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  70910. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  70911. }
  70912. // Add the bounce animation to the upper radius limit
  70913. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  70914. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  70915. }
  70916. });
  70917. };
  70918. BouncingBehavior.prototype.detach = function () {
  70919. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70920. if (this._onMeshTargetChangedObserver) {
  70921. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70922. }
  70923. this._attachedCamera = null;
  70924. };
  70925. /**
  70926. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  70927. * @param radiusLimit The limit to check against.
  70928. * @return Bool to indicate if at limit.
  70929. */
  70930. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  70931. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  70932. return true;
  70933. }
  70934. return false;
  70935. };
  70936. /**
  70937. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  70938. * @param radiusDelta The delta by which to animate to. Can be negative.
  70939. */
  70940. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  70941. var _this = this;
  70942. if (!this._radiusBounceTransition) {
  70943. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  70944. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  70945. }
  70946. // Prevent zoom until bounce has completed
  70947. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  70948. this._attachedCamera.wheelPrecision = Infinity;
  70949. this._attachedCamera.inertialRadiusOffset = 0;
  70950. // Animate to the radius limit
  70951. this.stopAllAnimations();
  70952. this._radiusIsAnimating = true;
  70953. 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(); }));
  70954. };
  70955. /**
  70956. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  70957. */
  70958. BouncingBehavior.prototype._clearAnimationLocks = function () {
  70959. this._radiusIsAnimating = false;
  70960. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  70961. };
  70962. /**
  70963. * Stops and removes all animations that have been applied to the camera
  70964. */
  70965. BouncingBehavior.prototype.stopAllAnimations = function () {
  70966. this._attachedCamera.animations = [];
  70967. while (this._animatables.length) {
  70968. this._animatables[0].onAnimationEnd = null;
  70969. this._animatables[0].stop();
  70970. this._animatables.shift();
  70971. }
  70972. };
  70973. /**
  70974. * The easing function used by animations
  70975. */
  70976. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  70977. /**
  70978. * The easing mode used by animations
  70979. */
  70980. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  70981. return BouncingBehavior;
  70982. }());
  70983. BABYLON.BouncingBehavior = BouncingBehavior;
  70984. })(BABYLON || (BABYLON = {}));
  70985. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  70986. var BABYLON;
  70987. (function (BABYLON) {
  70988. var AutoRotationBehavior = (function () {
  70989. function AutoRotationBehavior() {
  70990. this._zoomStopsAnimation = false;
  70991. this._idleRotationSpeed = 0.05;
  70992. this._idleRotationWaitTime = 2000;
  70993. this._idleRotationSpinupTime = 2000;
  70994. this._isPointerDown = false;
  70995. this._lastFrameTime = null;
  70996. this._lastInteractionTime = -Infinity;
  70997. this._cameraRotationSpeed = 0;
  70998. this._lastFrameRadius = 0;
  70999. }
  71000. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  71001. get: function () {
  71002. return "AutoRotation";
  71003. },
  71004. enumerable: true,
  71005. configurable: true
  71006. });
  71007. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  71008. /**
  71009. * Gets the flag that indicates if user zooming should stop animation.
  71010. */
  71011. get: function () {
  71012. return this._zoomStopsAnimation;
  71013. },
  71014. /**
  71015. * Sets the flag that indicates if user zooming should stop animation.
  71016. */
  71017. set: function (flag) {
  71018. this._zoomStopsAnimation = flag;
  71019. },
  71020. enumerable: true,
  71021. configurable: true
  71022. });
  71023. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  71024. /**
  71025. * Gets the default speed at which the camera rotates around the model.
  71026. */
  71027. get: function () {
  71028. return this._idleRotationSpeed;
  71029. },
  71030. /**
  71031. * Sets the default speed at which the camera rotates around the model.
  71032. */
  71033. set: function (speed) {
  71034. this._idleRotationSpeed = speed;
  71035. },
  71036. enumerable: true,
  71037. configurable: true
  71038. });
  71039. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  71040. /**
  71041. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  71042. */
  71043. get: function () {
  71044. return this._idleRotationWaitTime;
  71045. },
  71046. /**
  71047. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  71048. */
  71049. set: function (time) {
  71050. this._idleRotationWaitTime = time;
  71051. },
  71052. enumerable: true,
  71053. configurable: true
  71054. });
  71055. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  71056. /**
  71057. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71058. */
  71059. get: function () {
  71060. return this._idleRotationSpinupTime;
  71061. },
  71062. /**
  71063. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71064. */
  71065. set: function (time) {
  71066. this._idleRotationSpinupTime = time;
  71067. },
  71068. enumerable: true,
  71069. configurable: true
  71070. });
  71071. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  71072. /**
  71073. * Gets a value indicating if the camera is currently rotating because of this behavior
  71074. */
  71075. get: function () {
  71076. return Math.abs(this._cameraRotationSpeed) > 0;
  71077. },
  71078. enumerable: true,
  71079. configurable: true
  71080. });
  71081. AutoRotationBehavior.prototype.attach = function (camera) {
  71082. var _this = this;
  71083. this._attachedCamera = camera;
  71084. var scene = this._attachedCamera.getScene();
  71085. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71086. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71087. _this._isPointerDown = true;
  71088. return;
  71089. }
  71090. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71091. _this._isPointerDown = false;
  71092. }
  71093. });
  71094. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71095. var now = BABYLON.Tools.Now;
  71096. var dt = 0;
  71097. if (_this._lastFrameTime != null) {
  71098. dt = now - _this._lastFrameTime;
  71099. }
  71100. _this._lastFrameTime = now;
  71101. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71102. _this._applyUserInteraction();
  71103. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  71104. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  71105. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  71106. // Step camera rotation by rotation speed
  71107. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  71108. });
  71109. };
  71110. AutoRotationBehavior.prototype.detach = function () {
  71111. var scene = this._attachedCamera.getScene();
  71112. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71113. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71114. this._attachedCamera = null;
  71115. };
  71116. /**
  71117. * Returns true if user is scrolling.
  71118. * @return true if user is scrolling.
  71119. */
  71120. AutoRotationBehavior.prototype._userIsZooming = function () {
  71121. return this._attachedCamera.inertialRadiusOffset !== 0;
  71122. };
  71123. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  71124. var zoomHasHitLimit = false;
  71125. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  71126. zoomHasHitLimit = true;
  71127. }
  71128. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  71129. this._lastFrameRadius = this._attachedCamera.radius;
  71130. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  71131. };
  71132. /**
  71133. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  71134. */
  71135. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  71136. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  71137. this._lastInteractionTime = BABYLON.Tools.Now;
  71138. }
  71139. };
  71140. // Tools
  71141. AutoRotationBehavior.prototype._userIsMoving = function () {
  71142. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  71143. this._attachedCamera.inertialBetaOffset !== 0 ||
  71144. this._attachedCamera.inertialRadiusOffset !== 0 ||
  71145. this._attachedCamera.inertialPanningX !== 0 ||
  71146. this._attachedCamera.inertialPanningY !== 0 ||
  71147. this._isPointerDown;
  71148. };
  71149. return AutoRotationBehavior;
  71150. }());
  71151. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  71152. })(BABYLON || (BABYLON = {}));
  71153. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  71154. 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;\n\nuniform mat4 view;\nuniform mat4 projection;\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;\nvUV=offset;\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}"};
  71155. 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};"};
  71156. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  71157. var BABYLON;
  71158. (function (BABYLON) {
  71159. var GridMaterialDefines = (function (_super) {
  71160. __extends(GridMaterialDefines, _super);
  71161. function GridMaterialDefines() {
  71162. var _this = _super.call(this) || this;
  71163. _this.TRANSPARENT = false;
  71164. _this.FOG = false;
  71165. _this.PREMULTIPLYALPHA = false;
  71166. _this.rebuild();
  71167. return _this;
  71168. }
  71169. return GridMaterialDefines;
  71170. }(BABYLON.MaterialDefines));
  71171. /**
  71172. * The grid materials allows you to wrap any shape with a grid.
  71173. * Colors are customizable.
  71174. */
  71175. var GridMaterial = (function (_super) {
  71176. __extends(GridMaterial, _super);
  71177. /**
  71178. * constructor
  71179. * @param name The name given to the material in order to identify it afterwards.
  71180. * @param scene The scene the material is used in.
  71181. */
  71182. function GridMaterial(name, scene) {
  71183. var _this = _super.call(this, name, scene) || this;
  71184. /**
  71185. * Main color of the grid (e.g. between lines)
  71186. */
  71187. _this.mainColor = BABYLON.Color3.Black();
  71188. /**
  71189. * Color of the grid lines.
  71190. */
  71191. _this.lineColor = BABYLON.Color3.Teal();
  71192. /**
  71193. * The scale of the grid compared to unit.
  71194. */
  71195. _this.gridRatio = 1.0;
  71196. /**
  71197. * The frequency of thicker lines.
  71198. */
  71199. _this.majorUnitFrequency = 10;
  71200. /**
  71201. * The visibility of minor units in the grid.
  71202. */
  71203. _this.minorUnitVisibility = 0.33;
  71204. /**
  71205. * The grid opacity outside of the lines.
  71206. */
  71207. _this.opacity = 1.0;
  71208. /**
  71209. * Determine RBG output is premultiplied by alpha value.
  71210. */
  71211. _this.preMultiplyAlpha = false;
  71212. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  71213. return _this;
  71214. }
  71215. /**
  71216. * Returns wehter or not the grid requires alpha blending.
  71217. */
  71218. GridMaterial.prototype.needAlphaBlending = function () {
  71219. return this.opacity < 1.0;
  71220. };
  71221. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71222. if (this.isFrozen) {
  71223. if (this._wasPreviouslyReady && subMesh.effect) {
  71224. return true;
  71225. }
  71226. }
  71227. if (!subMesh._materialDefines) {
  71228. subMesh._materialDefines = new GridMaterialDefines();
  71229. }
  71230. var defines = subMesh._materialDefines;
  71231. var scene = this.getScene();
  71232. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  71233. if (this._renderId === scene.getRenderId()) {
  71234. return true;
  71235. }
  71236. }
  71237. var engine = scene.getEngine();
  71238. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  71239. defines.TRANSPARENT = !defines.TRANSPARENT;
  71240. defines.markAsUnprocessed();
  71241. }
  71242. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  71243. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  71244. defines.markAsUnprocessed();
  71245. }
  71246. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  71247. // Get correct effect
  71248. if (defines.isDirty) {
  71249. defines.markAsProcessed();
  71250. scene.resetCachedMaterial();
  71251. // Attributes
  71252. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71253. // Defines
  71254. var join = defines.toString();
  71255. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  71256. }
  71257. if (!subMesh.effect.isReady()) {
  71258. return false;
  71259. }
  71260. this._renderId = scene.getRenderId();
  71261. this._wasPreviouslyReady = true;
  71262. return true;
  71263. };
  71264. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  71265. var scene = this.getScene();
  71266. var defines = subMesh._materialDefines;
  71267. if (!defines) {
  71268. return;
  71269. }
  71270. var effect = subMesh.effect;
  71271. this._activeEffect = effect;
  71272. // Matrices
  71273. this.bindOnlyWorldMatrix(world);
  71274. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  71275. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  71276. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  71277. // Uniforms
  71278. if (this._mustRebind(scene, effect)) {
  71279. this._activeEffect.setColor3("mainColor", this.mainColor);
  71280. this._activeEffect.setColor3("lineColor", this.lineColor);
  71281. this._gridControl.x = this.gridRatio;
  71282. this._gridControl.y = Math.round(this.majorUnitFrequency);
  71283. this._gridControl.z = this.minorUnitVisibility;
  71284. this._gridControl.w = this.opacity;
  71285. this._activeEffect.setVector4("gridControl", this._gridControl);
  71286. }
  71287. // Fog
  71288. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  71289. this._afterBind(mesh, this._activeEffect);
  71290. };
  71291. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  71292. _super.prototype.dispose.call(this, forceDisposeEffect);
  71293. };
  71294. GridMaterial.prototype.clone = function (name) {
  71295. var _this = this;
  71296. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  71297. };
  71298. GridMaterial.prototype.serialize = function () {
  71299. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71300. serializationObject.customType = "BABYLON.GridMaterial";
  71301. return serializationObject;
  71302. };
  71303. GridMaterial.prototype.getClassName = function () {
  71304. return "GridMaterial";
  71305. };
  71306. GridMaterial.Parse = function (source, scene, rootUrl) {
  71307. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  71308. };
  71309. __decorate([
  71310. BABYLON.serializeAsColor3()
  71311. ], GridMaterial.prototype, "mainColor", void 0);
  71312. __decorate([
  71313. BABYLON.serializeAsColor3()
  71314. ], GridMaterial.prototype, "lineColor", void 0);
  71315. __decorate([
  71316. BABYLON.serialize()
  71317. ], GridMaterial.prototype, "gridRatio", void 0);
  71318. __decorate([
  71319. BABYLON.serialize()
  71320. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  71321. __decorate([
  71322. BABYLON.serialize()
  71323. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  71324. __decorate([
  71325. BABYLON.serialize()
  71326. ], GridMaterial.prototype, "opacity", void 0);
  71327. __decorate([
  71328. BABYLON.serialize()
  71329. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  71330. return GridMaterial;
  71331. }(BABYLON.PushMaterial));
  71332. BABYLON.GridMaterial = GridMaterial;
  71333. })(BABYLON || (BABYLON = {}));
  71334. //# sourceMappingURL=babylon.gridmaterial.js.map
  71335. 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}";
  71336. 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}";
  71337. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  71338. var BABYLON;
  71339. (function (BABYLON) {
  71340. var GLTFLoaderCoordinateSystemMode;
  71341. (function (GLTFLoaderCoordinateSystemMode) {
  71342. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  71343. // 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.
  71344. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  71345. // The glTF right-handed data is not transformed in any form and is loaded directly.
  71346. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  71347. // Sets the useRightHandedSystem flag on the scene.
  71348. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  71349. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  71350. var GLTFFileLoader = (function () {
  71351. function GLTFFileLoader() {
  71352. // V2 options
  71353. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  71354. this.name = "gltf";
  71355. this.extensions = {
  71356. ".gltf": { isBinary: false },
  71357. ".glb": { isBinary: true }
  71358. };
  71359. }
  71360. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  71361. var loaderData = GLTFFileLoader._parse(data, onError);
  71362. if (!loaderData) {
  71363. return;
  71364. }
  71365. var loader = this._getLoader(loaderData, onError);
  71366. if (!loader) {
  71367. return;
  71368. }
  71369. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  71370. };
  71371. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  71372. var loaderData = GLTFFileLoader._parse(data, onError);
  71373. if (!loaderData) {
  71374. return;
  71375. }
  71376. var loader = this._getLoader(loaderData, onError);
  71377. if (!loader) {
  71378. return;
  71379. }
  71380. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  71381. };
  71382. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  71383. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  71384. };
  71385. GLTFFileLoader._parse = function (data, onError) {
  71386. if (data instanceof ArrayBuffer) {
  71387. return GLTFFileLoader._parseBinary(data, onError);
  71388. }
  71389. try {
  71390. return {
  71391. json: JSON.parse(data),
  71392. bin: null
  71393. };
  71394. }
  71395. catch (e) {
  71396. onError(e.message);
  71397. return null;
  71398. }
  71399. };
  71400. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  71401. var loaderVersion = { major: 2, minor: 0 };
  71402. var asset = loaderData.json.asset || {};
  71403. var version = GLTFFileLoader._parseVersion(asset.version);
  71404. if (!version) {
  71405. onError("Invalid version: " + asset.version);
  71406. return null;
  71407. }
  71408. if (asset.minVersion !== undefined) {
  71409. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  71410. if (!minVersion) {
  71411. onError("Invalid minimum version: " + asset.minVersion);
  71412. return null;
  71413. }
  71414. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  71415. onError("Incompatible minimum version: " + asset.minVersion);
  71416. return null;
  71417. }
  71418. }
  71419. var createLoaders = {
  71420. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  71421. 2: GLTFFileLoader.CreateGLTFLoaderV2
  71422. };
  71423. var createLoader = createLoaders[version.major];
  71424. if (!createLoader) {
  71425. onError("Unsupported version: " + asset.version);
  71426. return null;
  71427. }
  71428. return createLoader(this);
  71429. };
  71430. GLTFFileLoader._parseBinary = function (data, onError) {
  71431. var Binary = {
  71432. Magic: 0x46546C67
  71433. };
  71434. var binaryReader = new BinaryReader(data);
  71435. var magic = binaryReader.readUint32();
  71436. if (magic !== Binary.Magic) {
  71437. onError("Unexpected magic: " + magic);
  71438. return null;
  71439. }
  71440. var version = binaryReader.readUint32();
  71441. switch (version) {
  71442. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  71443. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  71444. }
  71445. onError("Unsupported version: " + version);
  71446. return null;
  71447. };
  71448. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  71449. var ContentFormat = {
  71450. JSON: 0
  71451. };
  71452. var length = binaryReader.readUint32();
  71453. if (length != binaryReader.getLength()) {
  71454. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  71455. return null;
  71456. }
  71457. var contentLength = binaryReader.readUint32();
  71458. var contentFormat = binaryReader.readUint32();
  71459. var content;
  71460. switch (contentFormat) {
  71461. case ContentFormat.JSON:
  71462. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  71463. break;
  71464. default:
  71465. onError("Unexpected content format: " + contentFormat);
  71466. return null;
  71467. }
  71468. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  71469. var body = binaryReader.readUint8Array(bytesRemaining);
  71470. return {
  71471. json: content,
  71472. bin: body
  71473. };
  71474. };
  71475. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  71476. var ChunkFormat = {
  71477. JSON: 0x4E4F534A,
  71478. BIN: 0x004E4942
  71479. };
  71480. var length = binaryReader.readUint32();
  71481. if (length !== binaryReader.getLength()) {
  71482. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  71483. return null;
  71484. }
  71485. // JSON chunk
  71486. var chunkLength = binaryReader.readUint32();
  71487. var chunkFormat = binaryReader.readUint32();
  71488. if (chunkFormat !== ChunkFormat.JSON) {
  71489. onError("First chunk format is not JSON");
  71490. return null;
  71491. }
  71492. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  71493. // Look for BIN chunk
  71494. var bin = null;
  71495. while (binaryReader.getPosition() < binaryReader.getLength()) {
  71496. chunkLength = binaryReader.readUint32();
  71497. chunkFormat = binaryReader.readUint32();
  71498. switch (chunkFormat) {
  71499. case ChunkFormat.JSON:
  71500. onError("Unexpected JSON chunk");
  71501. return null;
  71502. case ChunkFormat.BIN:
  71503. bin = binaryReader.readUint8Array(chunkLength);
  71504. break;
  71505. default:
  71506. // ignore unrecognized chunkFormat
  71507. binaryReader.skipBytes(chunkLength);
  71508. break;
  71509. }
  71510. }
  71511. return {
  71512. json: json,
  71513. bin: bin
  71514. };
  71515. };
  71516. GLTFFileLoader._parseVersion = function (version) {
  71517. if (!version) {
  71518. return null;
  71519. }
  71520. var parts = version.split(".");
  71521. if (parts.length != 2) {
  71522. return null;
  71523. }
  71524. var major = +parts[0];
  71525. if (isNaN(major)) {
  71526. return null;
  71527. }
  71528. var minor = +parts[1];
  71529. if (isNaN(minor)) {
  71530. return null;
  71531. }
  71532. return {
  71533. major: major,
  71534. minor: minor
  71535. };
  71536. };
  71537. GLTFFileLoader._compareVersion = function (a, b) {
  71538. if (a.major > b.major)
  71539. return 1;
  71540. if (a.major < b.major)
  71541. return -1;
  71542. if (a.minor > b.minor)
  71543. return 1;
  71544. if (a.minor < b.minor)
  71545. return -1;
  71546. return 0;
  71547. };
  71548. GLTFFileLoader._decodeBufferToText = function (view) {
  71549. var result = "";
  71550. var length = view.byteLength;
  71551. for (var i = 0; i < length; ++i) {
  71552. result += String.fromCharCode(view[i]);
  71553. }
  71554. return result;
  71555. };
  71556. // V1 options
  71557. GLTFFileLoader.HomogeneousCoordinates = false;
  71558. GLTFFileLoader.IncrementalLoading = true;
  71559. return GLTFFileLoader;
  71560. }());
  71561. BABYLON.GLTFFileLoader = GLTFFileLoader;
  71562. var BinaryReader = (function () {
  71563. function BinaryReader(arrayBuffer) {
  71564. this._arrayBuffer = arrayBuffer;
  71565. this._dataView = new DataView(arrayBuffer);
  71566. this._byteOffset = 0;
  71567. }
  71568. BinaryReader.prototype.getPosition = function () {
  71569. return this._byteOffset;
  71570. };
  71571. BinaryReader.prototype.getLength = function () {
  71572. return this._arrayBuffer.byteLength;
  71573. };
  71574. BinaryReader.prototype.readUint32 = function () {
  71575. var value = this._dataView.getUint32(this._byteOffset, true);
  71576. this._byteOffset += 4;
  71577. return value;
  71578. };
  71579. BinaryReader.prototype.readUint8Array = function (length) {
  71580. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  71581. this._byteOffset += length;
  71582. return value;
  71583. };
  71584. BinaryReader.prototype.skipBytes = function (length) {
  71585. this._byteOffset += length;
  71586. };
  71587. return BinaryReader;
  71588. }());
  71589. if (BABYLON.SceneLoader) {
  71590. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  71591. }
  71592. })(BABYLON || (BABYLON = {}));
  71593. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  71594. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  71595. var BABYLON;
  71596. (function (BABYLON) {
  71597. var GLTF1;
  71598. (function (GLTF1) {
  71599. /**
  71600. * Enums
  71601. */
  71602. var EComponentType;
  71603. (function (EComponentType) {
  71604. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  71605. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  71606. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  71607. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  71608. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  71609. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  71610. var EShaderType;
  71611. (function (EShaderType) {
  71612. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  71613. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  71614. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  71615. var EParameterType;
  71616. (function (EParameterType) {
  71617. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  71618. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  71619. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  71620. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  71621. EParameterType[EParameterType["INT"] = 5124] = "INT";
  71622. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  71623. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  71624. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  71625. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  71626. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  71627. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  71628. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  71629. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  71630. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  71631. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  71632. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  71633. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  71634. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  71635. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  71636. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  71637. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  71638. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  71639. var ETextureWrapMode;
  71640. (function (ETextureWrapMode) {
  71641. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  71642. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  71643. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  71644. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  71645. var ETextureFilterType;
  71646. (function (ETextureFilterType) {
  71647. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  71648. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  71649. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  71650. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  71651. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  71652. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  71653. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  71654. var ETextureFormat;
  71655. (function (ETextureFormat) {
  71656. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  71657. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  71658. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  71659. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  71660. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  71661. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  71662. var ECullingType;
  71663. (function (ECullingType) {
  71664. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  71665. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  71666. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  71667. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  71668. var EBlendingFunction;
  71669. (function (EBlendingFunction) {
  71670. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  71671. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  71672. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  71673. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  71674. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  71675. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  71676. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  71677. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  71678. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  71679. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  71680. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  71681. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  71682. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  71683. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  71684. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  71685. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  71686. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  71687. })(BABYLON || (BABYLON = {}));
  71688. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  71689. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  71690. var BABYLON;
  71691. (function (BABYLON) {
  71692. var GLTF1;
  71693. (function (GLTF1) {
  71694. /**
  71695. * Tokenizer. Used for shaders compatibility
  71696. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  71697. */
  71698. var ETokenType;
  71699. (function (ETokenType) {
  71700. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  71701. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  71702. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  71703. })(ETokenType || (ETokenType = {}));
  71704. var Tokenizer = (function () {
  71705. function Tokenizer(toParse) {
  71706. this._pos = 0;
  71707. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  71708. this._toParse = toParse;
  71709. this._maxPos = toParse.length;
  71710. }
  71711. Tokenizer.prototype.getNextToken = function () {
  71712. if (this.isEnd())
  71713. return ETokenType.END_OF_INPUT;
  71714. this.currentString = this.read();
  71715. this.currentToken = ETokenType.UNKNOWN;
  71716. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  71717. this.currentToken = ETokenType.IDENTIFIER;
  71718. this.currentIdentifier = this.currentString;
  71719. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  71720. this.currentIdentifier += this.currentString;
  71721. this.forward();
  71722. }
  71723. }
  71724. return this.currentToken;
  71725. };
  71726. Tokenizer.prototype.peek = function () {
  71727. return this._toParse[this._pos];
  71728. };
  71729. Tokenizer.prototype.read = function () {
  71730. return this._toParse[this._pos++];
  71731. };
  71732. Tokenizer.prototype.forward = function () {
  71733. this._pos++;
  71734. };
  71735. Tokenizer.prototype.isEnd = function () {
  71736. return this._pos >= this._maxPos;
  71737. };
  71738. return Tokenizer;
  71739. }());
  71740. /**
  71741. * Values
  71742. */
  71743. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  71744. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  71745. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  71746. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  71747. /**
  71748. * Parse
  71749. */
  71750. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  71751. for (var buf in parsedBuffers) {
  71752. var parsedBuffer = parsedBuffers[buf];
  71753. gltfRuntime.buffers[buf] = parsedBuffer;
  71754. gltfRuntime.buffersCount++;
  71755. }
  71756. };
  71757. var parseShaders = function (parsedShaders, gltfRuntime) {
  71758. for (var sha in parsedShaders) {
  71759. var parsedShader = parsedShaders[sha];
  71760. gltfRuntime.shaders[sha] = parsedShader;
  71761. gltfRuntime.shaderscount++;
  71762. }
  71763. };
  71764. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  71765. for (var object in parsedObjects) {
  71766. var parsedObject = parsedObjects[object];
  71767. gltfRuntime[runtimeProperty][object] = parsedObject;
  71768. }
  71769. };
  71770. /**
  71771. * Utils
  71772. */
  71773. var normalizeUVs = function (buffer) {
  71774. if (!buffer) {
  71775. return;
  71776. }
  71777. for (var i = 0; i < buffer.length / 2; i++) {
  71778. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  71779. }
  71780. };
  71781. var replaceInString = function (str, searchValue, replaceValue) {
  71782. while (str.indexOf(searchValue) !== -1) {
  71783. str = str.replace(searchValue, replaceValue);
  71784. }
  71785. return str;
  71786. };
  71787. var getAttribute = function (attributeParameter) {
  71788. if (attributeParameter.semantic === "NORMAL") {
  71789. return "normal";
  71790. }
  71791. else if (attributeParameter.semantic === "POSITION") {
  71792. return "position";
  71793. }
  71794. else if (attributeParameter.semantic === "JOINT") {
  71795. return "matricesIndices";
  71796. }
  71797. else if (attributeParameter.semantic === "WEIGHT") {
  71798. return "matricesWeights";
  71799. }
  71800. else if (attributeParameter.semantic === "COLOR") {
  71801. return "color";
  71802. }
  71803. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  71804. var channel = Number(attributeParameter.semantic.split("_")[1]);
  71805. return "uv" + (channel === 0 ? "" : channel + 1);
  71806. }
  71807. };
  71808. /**
  71809. * Returns the animation path (glTF -> Babylon)
  71810. */
  71811. var getAnimationPath = function (path) {
  71812. var index = glTFAnimationPaths.indexOf(path);
  71813. if (index !== -1) {
  71814. return babylonAnimationPaths[index];
  71815. }
  71816. return path;
  71817. };
  71818. /**
  71819. * Loads and creates animations
  71820. */
  71821. var loadAnimations = function (gltfRuntime) {
  71822. for (var anim in gltfRuntime.animations) {
  71823. var animation = gltfRuntime.animations[anim];
  71824. var lastAnimation = null;
  71825. for (var i = 0; i < animation.channels.length; i++) {
  71826. // Get parameters and load buffers
  71827. var channel = animation.channels[i];
  71828. var sampler = animation.samplers[channel.sampler];
  71829. if (!sampler) {
  71830. continue;
  71831. }
  71832. var inputData = null;
  71833. var outputData = null;
  71834. if (animation.parameters) {
  71835. inputData = animation.parameters[sampler.input];
  71836. outputData = animation.parameters[sampler.output];
  71837. }
  71838. else {
  71839. inputData = sampler.input;
  71840. outputData = sampler.output;
  71841. }
  71842. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  71843. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  71844. var targetID = channel.target.id;
  71845. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  71846. if (targetNode === null) {
  71847. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  71848. }
  71849. if (targetNode === null) {
  71850. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  71851. continue;
  71852. }
  71853. var isBone = targetNode instanceof BABYLON.Bone;
  71854. // Get target path (position, rotation or scaling)
  71855. var targetPath = channel.target.path;
  71856. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  71857. if (targetPathIndex !== -1) {
  71858. targetPath = babylonAnimationPaths[targetPathIndex];
  71859. }
  71860. // Determine animation type
  71861. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  71862. if (!isBone) {
  71863. if (targetPath === "rotationQuaternion") {
  71864. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  71865. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  71866. }
  71867. else {
  71868. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  71869. }
  71870. }
  71871. // Create animation and key frames
  71872. var babylonAnimation = null;
  71873. var keys = [];
  71874. var arrayOffset = 0;
  71875. var modifyKey = false;
  71876. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  71877. babylonAnimation = lastAnimation;
  71878. modifyKey = true;
  71879. }
  71880. if (!modifyKey) {
  71881. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  71882. }
  71883. // For each frame
  71884. for (var j = 0; j < bufferInput.length; j++) {
  71885. var value = null;
  71886. if (targetPath === "rotationQuaternion") {
  71887. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  71888. arrayOffset += 4;
  71889. }
  71890. else {
  71891. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  71892. arrayOffset += 3;
  71893. }
  71894. if (isBone) {
  71895. var bone = targetNode;
  71896. var translation = BABYLON.Vector3.Zero();
  71897. var rotationQuaternion = new BABYLON.Quaternion();
  71898. var scaling = BABYLON.Vector3.Zero();
  71899. // Warning on decompose
  71900. var mat = bone.getBaseMatrix();
  71901. if (modifyKey) {
  71902. mat = lastAnimation.getKeys()[j].value;
  71903. }
  71904. mat.decompose(scaling, rotationQuaternion, translation);
  71905. if (targetPath === "position") {
  71906. translation = value;
  71907. }
  71908. else if (targetPath === "rotationQuaternion") {
  71909. rotationQuaternion = value;
  71910. }
  71911. else {
  71912. scaling = value;
  71913. }
  71914. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  71915. }
  71916. if (!modifyKey) {
  71917. keys.push({
  71918. frame: bufferInput[j],
  71919. value: value
  71920. });
  71921. }
  71922. else {
  71923. lastAnimation.getKeys()[j].value = value;
  71924. }
  71925. }
  71926. // Finish
  71927. if (!modifyKey) {
  71928. babylonAnimation.setKeys(keys);
  71929. targetNode.animations.push(babylonAnimation);
  71930. }
  71931. lastAnimation = babylonAnimation;
  71932. gltfRuntime.scene.stopAnimation(targetNode);
  71933. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  71934. }
  71935. }
  71936. };
  71937. /**
  71938. * Returns the bones transformation matrix
  71939. */
  71940. var configureBoneTransformation = function (node) {
  71941. var mat = null;
  71942. if (node.translation || node.rotation || node.scale) {
  71943. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  71944. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  71945. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  71946. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  71947. }
  71948. else {
  71949. mat = BABYLON.Matrix.FromArray(node.matrix);
  71950. }
  71951. return mat;
  71952. };
  71953. /**
  71954. * Returns the parent bone
  71955. */
  71956. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  71957. // Try to find
  71958. for (var i = 0; i < newSkeleton.bones.length; i++) {
  71959. if (newSkeleton.bones[i].name === jointName) {
  71960. return newSkeleton.bones[i];
  71961. }
  71962. }
  71963. // Not found, search in gltf nodes
  71964. var nodes = gltfRuntime.nodes;
  71965. for (var nde in nodes) {
  71966. var node = nodes[nde];
  71967. if (!node.jointName) {
  71968. continue;
  71969. }
  71970. var children = node.children;
  71971. for (var i = 0; i < children.length; i++) {
  71972. var child = gltfRuntime.nodes[children[i]];
  71973. if (!child.jointName) {
  71974. continue;
  71975. }
  71976. if (child.jointName === jointName) {
  71977. var mat = configureBoneTransformation(node);
  71978. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  71979. bone.id = nde;
  71980. return bone;
  71981. }
  71982. }
  71983. }
  71984. return null;
  71985. };
  71986. /**
  71987. * Returns the appropriate root node
  71988. */
  71989. var getNodeToRoot = function (nodesToRoot, id) {
  71990. for (var i = 0; i < nodesToRoot.length; i++) {
  71991. var nodeToRoot = nodesToRoot[i];
  71992. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  71993. var child = nodeToRoot.node.children[j];
  71994. if (child === id) {
  71995. return nodeToRoot.bone;
  71996. }
  71997. }
  71998. }
  71999. return null;
  72000. };
  72001. /**
  72002. * Returns the node with the joint name
  72003. */
  72004. var getJointNode = function (gltfRuntime, jointName) {
  72005. var nodes = gltfRuntime.nodes;
  72006. var node = nodes[jointName];
  72007. if (node) {
  72008. return {
  72009. node: node,
  72010. id: jointName
  72011. };
  72012. }
  72013. for (var nde in nodes) {
  72014. node = nodes[nde];
  72015. if (node.jointName === jointName) {
  72016. return {
  72017. node: node,
  72018. id: nde
  72019. };
  72020. }
  72021. }
  72022. return null;
  72023. };
  72024. /**
  72025. * Checks if a nodes is in joints
  72026. */
  72027. var nodeIsInJoints = function (skins, id) {
  72028. for (var i = 0; i < skins.jointNames.length; i++) {
  72029. if (skins.jointNames[i] === id) {
  72030. return true;
  72031. }
  72032. }
  72033. return false;
  72034. };
  72035. /**
  72036. * Fills the nodes to root for bones and builds hierarchy
  72037. */
  72038. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  72039. // Creates nodes for root
  72040. for (var nde in gltfRuntime.nodes) {
  72041. var node = gltfRuntime.nodes[nde];
  72042. var id = nde;
  72043. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  72044. continue;
  72045. }
  72046. // Create node to root bone
  72047. var mat = configureBoneTransformation(node);
  72048. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  72049. bone.id = id;
  72050. nodesToRoot.push({ bone: bone, node: node, id: id });
  72051. }
  72052. // Parenting
  72053. for (var i = 0; i < nodesToRoot.length; i++) {
  72054. var nodeToRoot = nodesToRoot[i];
  72055. var children = nodeToRoot.node.children;
  72056. for (var j = 0; j < children.length; j++) {
  72057. var child = null;
  72058. for (var k = 0; k < nodesToRoot.length; k++) {
  72059. if (nodesToRoot[k].id === children[j]) {
  72060. child = nodesToRoot[k];
  72061. break;
  72062. }
  72063. }
  72064. if (child) {
  72065. child.bone._parent = nodeToRoot.bone;
  72066. nodeToRoot.bone.children.push(child.bone);
  72067. }
  72068. }
  72069. }
  72070. };
  72071. var printMat = function (m) {
  72072. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  72073. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  72074. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  72075. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  72076. };
  72077. /**
  72078. * Imports a skeleton
  72079. */
  72080. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  72081. if (!newSkeleton) {
  72082. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  72083. }
  72084. if (!skins.babylonSkeleton) {
  72085. return newSkeleton;
  72086. }
  72087. // Matrices
  72088. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  72089. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  72090. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  72091. // Find the root bones
  72092. var nodesToRoot = [];
  72093. var nodesToRootToAdd = [];
  72094. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  72095. newSkeleton.bones = [];
  72096. // Joints
  72097. for (var i = 0; i < skins.jointNames.length; i++) {
  72098. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  72099. var node = jointNode.node;
  72100. if (!node) {
  72101. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  72102. continue;
  72103. }
  72104. var id = jointNode.id;
  72105. // Optimize, if the bone already exists...
  72106. var existingBone = gltfRuntime.scene.getBoneByID(id);
  72107. if (existingBone) {
  72108. newSkeleton.bones.push(existingBone);
  72109. continue;
  72110. }
  72111. // Search for parent bone
  72112. var foundBone = false;
  72113. var parentBone = null;
  72114. for (var j = 0; j < i; j++) {
  72115. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  72116. if (!joint) {
  72117. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  72118. continue;
  72119. }
  72120. var children = joint.children;
  72121. if (!children) {
  72122. continue;
  72123. }
  72124. foundBone = false;
  72125. for (var k = 0; k < children.length; k++) {
  72126. if (children[k] === id) {
  72127. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  72128. foundBone = true;
  72129. break;
  72130. }
  72131. }
  72132. if (foundBone) {
  72133. break;
  72134. }
  72135. }
  72136. // Create bone
  72137. var mat = configureBoneTransformation(node);
  72138. if (!parentBone && nodesToRoot.length > 0) {
  72139. parentBone = getNodeToRoot(nodesToRoot, id);
  72140. if (parentBone) {
  72141. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  72142. nodesToRootToAdd.push(parentBone);
  72143. }
  72144. }
  72145. }
  72146. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  72147. bone.id = id;
  72148. }
  72149. // Polish
  72150. var bones = newSkeleton.bones;
  72151. newSkeleton.bones = [];
  72152. for (var i = 0; i < skins.jointNames.length; i++) {
  72153. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  72154. if (!jointNode) {
  72155. continue;
  72156. }
  72157. for (var j = 0; j < bones.length; j++) {
  72158. if (bones[j].id === jointNode.id) {
  72159. newSkeleton.bones.push(bones[j]);
  72160. break;
  72161. }
  72162. }
  72163. }
  72164. newSkeleton.prepare();
  72165. // Finish
  72166. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  72167. newSkeleton.bones.push(nodesToRootToAdd[i]);
  72168. }
  72169. return newSkeleton;
  72170. };
  72171. /**
  72172. * Imports a mesh and its geometries
  72173. */
  72174. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  72175. if (!newMesh) {
  72176. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  72177. newMesh.id = id;
  72178. }
  72179. if (!node.babylonNode) {
  72180. return newMesh;
  72181. }
  72182. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  72183. if (!newMesh.material) {
  72184. newMesh.material = multiMat;
  72185. }
  72186. var vertexData = new BABYLON.VertexData();
  72187. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  72188. var verticesStarts = [];
  72189. var verticesCounts = [];
  72190. var indexStarts = [];
  72191. var indexCounts = [];
  72192. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  72193. var meshID = meshes[meshIndex];
  72194. var mesh = gltfRuntime.meshes[meshID];
  72195. if (!mesh) {
  72196. continue;
  72197. }
  72198. // Positions, normals and UVs
  72199. for (var i = 0; i < mesh.primitives.length; i++) {
  72200. // Temporary vertex data
  72201. var tempVertexData = new BABYLON.VertexData();
  72202. var primitive = mesh.primitives[i];
  72203. if (primitive.mode !== 4) {
  72204. // continue;
  72205. }
  72206. var attributes = primitive.attributes;
  72207. var accessor = null;
  72208. var buffer = null;
  72209. // Set positions, normal and uvs
  72210. for (var semantic in attributes) {
  72211. // Link accessor and buffer view
  72212. accessor = gltfRuntime.accessors[attributes[semantic]];
  72213. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  72214. if (semantic === "NORMAL") {
  72215. tempVertexData.normals = new Float32Array(buffer.length);
  72216. tempVertexData.normals.set(buffer);
  72217. }
  72218. else if (semantic === "POSITION") {
  72219. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  72220. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  72221. for (var j = 0; j < buffer.length; j += 4) {
  72222. tempVertexData.positions[j] = buffer[j];
  72223. tempVertexData.positions[j + 1] = buffer[j + 1];
  72224. tempVertexData.positions[j + 2] = buffer[j + 2];
  72225. }
  72226. }
  72227. else {
  72228. tempVertexData.positions = new Float32Array(buffer.length);
  72229. tempVertexData.positions.set(buffer);
  72230. }
  72231. verticesCounts.push(tempVertexData.positions.length);
  72232. }
  72233. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  72234. var channel = Number(semantic.split("_")[1]);
  72235. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  72236. var uvs = new Float32Array(buffer.length);
  72237. uvs.set(buffer);
  72238. normalizeUVs(uvs);
  72239. tempVertexData.set(uvs, uvKind);
  72240. }
  72241. else if (semantic === "JOINT") {
  72242. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  72243. tempVertexData.matricesIndices.set(buffer);
  72244. }
  72245. else if (semantic === "WEIGHT") {
  72246. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  72247. tempVertexData.matricesWeights.set(buffer);
  72248. }
  72249. else if (semantic === "COLOR") {
  72250. tempVertexData.colors = new Float32Array(buffer.length);
  72251. tempVertexData.colors.set(buffer);
  72252. }
  72253. }
  72254. // Indices
  72255. accessor = gltfRuntime.accessors[primitive.indices];
  72256. if (accessor) {
  72257. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  72258. tempVertexData.indices = new Int32Array(buffer.length);
  72259. tempVertexData.indices.set(buffer);
  72260. indexCounts.push(tempVertexData.indices.length);
  72261. }
  72262. else {
  72263. // Set indices on the fly
  72264. var indices = [];
  72265. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  72266. indices.push(j);
  72267. }
  72268. tempVertexData.indices = new Int32Array(indices);
  72269. indexCounts.push(tempVertexData.indices.length);
  72270. }
  72271. vertexData.merge(tempVertexData);
  72272. tempVertexData = undefined;
  72273. // Sub material
  72274. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  72275. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  72276. // Update vertices start and index start
  72277. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  72278. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  72279. }
  72280. }
  72281. // Apply geometry
  72282. geometry.setAllVerticesData(vertexData, false);
  72283. newMesh.computeWorldMatrix(true);
  72284. // Apply submeshes
  72285. newMesh.subMeshes = [];
  72286. var index = 0;
  72287. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  72288. var meshID = meshes[meshIndex];
  72289. var mesh = gltfRuntime.meshes[meshID];
  72290. if (!mesh) {
  72291. continue;
  72292. }
  72293. for (var i = 0; i < mesh.primitives.length; i++) {
  72294. if (mesh.primitives[i].mode !== 4) {
  72295. //continue;
  72296. }
  72297. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  72298. index++;
  72299. }
  72300. }
  72301. // Finish
  72302. return newMesh;
  72303. };
  72304. /**
  72305. * Configure node transformation from position, rotation and scaling
  72306. */
  72307. var configureNode = function (newNode, position, rotation, scaling) {
  72308. if (newNode.position) {
  72309. newNode.position = position;
  72310. }
  72311. if (newNode.rotationQuaternion || newNode.rotation) {
  72312. newNode.rotationQuaternion = rotation;
  72313. }
  72314. if (newNode.scaling) {
  72315. newNode.scaling = scaling;
  72316. }
  72317. };
  72318. /**
  72319. * Configures node from transformation matrix
  72320. */
  72321. var configureNodeFromMatrix = function (newNode, node, parent) {
  72322. if (node.matrix) {
  72323. var position = new BABYLON.Vector3(0, 0, 0);
  72324. var rotation = new BABYLON.Quaternion();
  72325. var scaling = new BABYLON.Vector3(0, 0, 0);
  72326. var mat = BABYLON.Matrix.FromArray(node.matrix);
  72327. mat.decompose(scaling, rotation, position);
  72328. configureNode(newNode, position, rotation, scaling);
  72329. }
  72330. else {
  72331. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  72332. }
  72333. newNode.computeWorldMatrix(true);
  72334. };
  72335. /**
  72336. * Imports a node
  72337. */
  72338. var importNode = function (gltfRuntime, node, id, parent) {
  72339. var lastNode = null;
  72340. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  72341. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  72342. return null;
  72343. }
  72344. }
  72345. // Meshes
  72346. if (node.skin) {
  72347. if (node.meshes) {
  72348. var skin = gltfRuntime.skins[node.skin];
  72349. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  72350. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  72351. if (newMesh.skeleton === null) {
  72352. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  72353. if (!skin.babylonSkeleton) {
  72354. skin.babylonSkeleton = newMesh.skeleton;
  72355. }
  72356. }
  72357. lastNode = newMesh;
  72358. }
  72359. }
  72360. else if (node.meshes) {
  72361. /**
  72362. * Improve meshes property
  72363. */
  72364. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  72365. lastNode = newMesh;
  72366. }
  72367. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  72368. var light = gltfRuntime.lights[node.light];
  72369. if (light) {
  72370. if (light.type === "ambient") {
  72371. var ambienLight = light[light.type];
  72372. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72373. hemiLight.name = node.name;
  72374. if (ambienLight.color) {
  72375. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  72376. }
  72377. lastNode = hemiLight;
  72378. }
  72379. else if (light.type === "directional") {
  72380. var directionalLight = light[light.type];
  72381. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72382. dirLight.name = node.name;
  72383. if (directionalLight.color) {
  72384. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  72385. }
  72386. lastNode = dirLight;
  72387. }
  72388. else if (light.type === "point") {
  72389. var pointLight = light[light.type];
  72390. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72391. ptLight.name = node.name;
  72392. if (pointLight.color) {
  72393. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  72394. }
  72395. lastNode = ptLight;
  72396. }
  72397. else if (light.type === "spot") {
  72398. var spotLight = light[light.type];
  72399. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  72400. spLight.name = node.name;
  72401. if (spotLight.color) {
  72402. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  72403. }
  72404. if (spotLight.fallOfAngle) {
  72405. spLight.angle = spotLight.fallOfAngle;
  72406. }
  72407. if (spotLight.fallOffExponent) {
  72408. spLight.exponent = spotLight.fallOffExponent;
  72409. }
  72410. lastNode = spLight;
  72411. }
  72412. }
  72413. }
  72414. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  72415. var camera = gltfRuntime.cameras[node.camera];
  72416. if (camera) {
  72417. if (camera.type === "orthographic") {
  72418. var orthographicCamera = camera[camera.type];
  72419. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72420. orthoCamera.name = node.name;
  72421. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  72422. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  72423. lastNode = orthoCamera;
  72424. }
  72425. else if (camera.type === "perspective") {
  72426. var perspectiveCamera = camera[camera.type];
  72427. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  72428. persCamera.name = node.name;
  72429. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  72430. if (!perspectiveCamera.aspectRatio) {
  72431. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  72432. }
  72433. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  72434. persCamera.maxZ = perspectiveCamera.zfar;
  72435. persCamera.minZ = perspectiveCamera.znear;
  72436. }
  72437. lastNode = persCamera;
  72438. }
  72439. }
  72440. }
  72441. // Empty node
  72442. if (!node.jointName) {
  72443. if (node.babylonNode) {
  72444. return node.babylonNode;
  72445. }
  72446. else if (lastNode === null) {
  72447. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  72448. node.babylonNode = dummy;
  72449. lastNode = dummy;
  72450. }
  72451. }
  72452. if (lastNode !== null) {
  72453. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  72454. configureNodeFromMatrix(lastNode, node, parent);
  72455. }
  72456. else {
  72457. var translation = node.translation || [0, 0, 0];
  72458. var rotation = node.rotation || [0, 0, 0, 1];
  72459. var scale = node.scale || [1, 1, 1];
  72460. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  72461. }
  72462. lastNode.updateCache(true);
  72463. node.babylonNode = lastNode;
  72464. }
  72465. return lastNode;
  72466. };
  72467. /**
  72468. * Traverses nodes and creates them
  72469. */
  72470. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  72471. var node = gltfRuntime.nodes[id];
  72472. var newNode = null;
  72473. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  72474. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  72475. meshIncluded = true;
  72476. }
  72477. else {
  72478. meshIncluded = false;
  72479. }
  72480. }
  72481. else {
  72482. meshIncluded = true;
  72483. }
  72484. if (!node.jointName && meshIncluded) {
  72485. newNode = importNode(gltfRuntime, node, id, parent);
  72486. if (newNode !== null) {
  72487. newNode.id = id;
  72488. newNode.parent = parent;
  72489. }
  72490. }
  72491. if (node.children) {
  72492. for (var i = 0; i < node.children.length; i++) {
  72493. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  72494. }
  72495. }
  72496. };
  72497. /**
  72498. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  72499. */
  72500. var postLoad = function (gltfRuntime) {
  72501. // Nodes
  72502. var currentScene = gltfRuntime.currentScene;
  72503. if (currentScene) {
  72504. for (var i = 0; i < currentScene.nodes.length; i++) {
  72505. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  72506. }
  72507. }
  72508. else {
  72509. for (var thing in gltfRuntime.scenes) {
  72510. currentScene = gltfRuntime.scenes[thing];
  72511. for (var i = 0; i < currentScene.nodes.length; i++) {
  72512. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  72513. }
  72514. }
  72515. }
  72516. // Set animations
  72517. loadAnimations(gltfRuntime);
  72518. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  72519. var skeleton = gltfRuntime.scene.skeletons[i];
  72520. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  72521. }
  72522. };
  72523. /**
  72524. * onBind shaderrs callback to set uniforms and matrices
  72525. */
  72526. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  72527. var materialValues = material.values || technique.parameters;
  72528. for (var unif in unTreatedUniforms) {
  72529. var uniform = unTreatedUniforms[unif];
  72530. var type = uniform.type;
  72531. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  72532. if (uniform.semantic && !uniform.source && !uniform.node) {
  72533. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  72534. }
  72535. else if (uniform.semantic && (uniform.source || uniform.node)) {
  72536. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  72537. if (source === null) {
  72538. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  72539. }
  72540. if (source === null) {
  72541. continue;
  72542. }
  72543. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  72544. }
  72545. }
  72546. else {
  72547. var value = materialValues[technique.uniforms[unif]];
  72548. if (!value) {
  72549. continue;
  72550. }
  72551. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  72552. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  72553. if (texture === null || texture === undefined) {
  72554. continue;
  72555. }
  72556. shaderMaterial.getEffect().setTexture(unif, texture);
  72557. }
  72558. else {
  72559. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  72560. }
  72561. }
  72562. }
  72563. onSuccess(shaderMaterial);
  72564. };
  72565. /**
  72566. * Prepare uniforms to send the only one time
  72567. * Loads the appropriate textures
  72568. */
  72569. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  72570. var materialValues = material.values || technique.parameters;
  72571. var techniqueUniforms = technique.uniforms;
  72572. /**
  72573. * Prepare values here (not matrices)
  72574. */
  72575. for (var unif in unTreatedUniforms) {
  72576. var uniform = unTreatedUniforms[unif];
  72577. var type = uniform.type;
  72578. var value = materialValues[techniqueUniforms[unif]];
  72579. if (value === undefined) {
  72580. // In case the value is the same for all materials
  72581. value = uniform.value;
  72582. }
  72583. if (!value) {
  72584. continue;
  72585. }
  72586. var onLoadTexture = function (uniformName) {
  72587. return function (texture) {
  72588. if (uniform.value) {
  72589. // Static uniform
  72590. shaderMaterial.setTexture(uniformName, texture);
  72591. delete unTreatedUniforms[uniformName];
  72592. }
  72593. };
  72594. };
  72595. // Texture (sampler2D)
  72596. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  72597. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  72598. }
  72599. else {
  72600. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  72601. // Static uniform
  72602. delete unTreatedUniforms[unif];
  72603. }
  72604. }
  72605. }
  72606. };
  72607. /**
  72608. * Shader compilation failed
  72609. */
  72610. var onShaderCompileError = function (program, shaderMaterial, onError) {
  72611. return function (effect, error) {
  72612. shaderMaterial.dispose(true);
  72613. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  72614. };
  72615. };
  72616. /**
  72617. * Shader compilation success
  72618. */
  72619. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  72620. return function (_) {
  72621. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  72622. shaderMaterial.onBind = function (mesh) {
  72623. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  72624. };
  72625. };
  72626. };
  72627. /**
  72628. * Returns the appropriate uniform if already handled by babylon
  72629. */
  72630. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  72631. for (var unif in technique.uniforms) {
  72632. var uniform = technique.uniforms[unif];
  72633. var uniformParameter = technique.parameters[uniform];
  72634. if (tokenizer.currentIdentifier === unif) {
  72635. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  72636. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  72637. if (transformIndex !== -1) {
  72638. delete unTreatedUniforms[unif];
  72639. return babylonTransforms[transformIndex];
  72640. }
  72641. }
  72642. }
  72643. }
  72644. return tokenizer.currentIdentifier;
  72645. };
  72646. /**
  72647. * All shaders loaded. Create materials one by one
  72648. */
  72649. var importMaterials = function (gltfRuntime) {
  72650. // Create materials
  72651. for (var mat in gltfRuntime.materials) {
  72652. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  72653. }
  72654. };
  72655. /**
  72656. * Implementation of the base glTF spec
  72657. */
  72658. var GLTFLoaderBase = (function () {
  72659. function GLTFLoaderBase() {
  72660. }
  72661. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  72662. var gltfRuntime = {
  72663. extensions: {},
  72664. accessors: {},
  72665. buffers: {},
  72666. bufferViews: {},
  72667. meshes: {},
  72668. lights: {},
  72669. cameras: {},
  72670. nodes: {},
  72671. images: {},
  72672. textures: {},
  72673. shaders: {},
  72674. programs: {},
  72675. samplers: {},
  72676. techniques: {},
  72677. materials: {},
  72678. animations: {},
  72679. skins: {},
  72680. extensionsUsed: [],
  72681. scenes: {},
  72682. buffersCount: 0,
  72683. shaderscount: 0,
  72684. scene: scene,
  72685. rootUrl: rootUrl,
  72686. loadedBufferCount: 0,
  72687. loadedBufferViews: {},
  72688. loadedShaderCount: 0,
  72689. importOnlyMeshes: false,
  72690. dummyNodes: []
  72691. };
  72692. // Parse
  72693. if (parsedData.extensions) {
  72694. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  72695. }
  72696. if (parsedData.extensionsUsed) {
  72697. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  72698. }
  72699. if (parsedData.buffers) {
  72700. parseBuffers(parsedData.buffers, gltfRuntime);
  72701. }
  72702. if (parsedData.bufferViews) {
  72703. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  72704. }
  72705. if (parsedData.accessors) {
  72706. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  72707. }
  72708. if (parsedData.meshes) {
  72709. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  72710. }
  72711. if (parsedData.lights) {
  72712. parseObject(parsedData.lights, "lights", gltfRuntime);
  72713. }
  72714. if (parsedData.cameras) {
  72715. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  72716. }
  72717. if (parsedData.nodes) {
  72718. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  72719. }
  72720. if (parsedData.images) {
  72721. parseObject(parsedData.images, "images", gltfRuntime);
  72722. }
  72723. if (parsedData.textures) {
  72724. parseObject(parsedData.textures, "textures", gltfRuntime);
  72725. }
  72726. if (parsedData.shaders) {
  72727. parseShaders(parsedData.shaders, gltfRuntime);
  72728. }
  72729. if (parsedData.programs) {
  72730. parseObject(parsedData.programs, "programs", gltfRuntime);
  72731. }
  72732. if (parsedData.samplers) {
  72733. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  72734. }
  72735. if (parsedData.techniques) {
  72736. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  72737. }
  72738. if (parsedData.materials) {
  72739. parseObject(parsedData.materials, "materials", gltfRuntime);
  72740. }
  72741. if (parsedData.animations) {
  72742. parseObject(parsedData.animations, "animations", gltfRuntime);
  72743. }
  72744. if (parsedData.skins) {
  72745. parseObject(parsedData.skins, "skins", gltfRuntime);
  72746. }
  72747. if (parsedData.scenes) {
  72748. gltfRuntime.scenes = parsedData.scenes;
  72749. }
  72750. if (parsedData.scene && parsedData.scenes) {
  72751. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  72752. }
  72753. return gltfRuntime;
  72754. };
  72755. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  72756. var buffer = gltfRuntime.buffers[id];
  72757. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  72758. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  72759. }
  72760. else {
  72761. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  72762. onError(request.status + " " + request.statusText);
  72763. });
  72764. }
  72765. };
  72766. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  72767. var texture = gltfRuntime.textures[id];
  72768. if (!texture || !texture.source) {
  72769. onError(null);
  72770. return;
  72771. }
  72772. if (texture.babylonTexture) {
  72773. onSuccess(null);
  72774. return;
  72775. }
  72776. var source = gltfRuntime.images[texture.source];
  72777. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  72778. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  72779. }
  72780. else {
  72781. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  72782. onError(request.status + " " + request.statusText);
  72783. });
  72784. }
  72785. };
  72786. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  72787. var texture = gltfRuntime.textures[id];
  72788. if (texture.babylonTexture) {
  72789. onSuccess(texture.babylonTexture);
  72790. return;
  72791. }
  72792. var sampler = gltfRuntime.samplers[texture.sampler];
  72793. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  72794. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  72795. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  72796. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  72797. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  72798. var blob = new Blob([buffer]);
  72799. var blobURL = URL.createObjectURL(blob);
  72800. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  72801. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  72802. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  72803. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  72804. newTexture.name = id;
  72805. texture.babylonTexture = newTexture;
  72806. onSuccess(newTexture);
  72807. };
  72808. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  72809. var shader = gltfRuntime.shaders[id];
  72810. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  72811. var shaderString = atob(shader.uri.split(",")[1]);
  72812. onSuccess(shaderString);
  72813. }
  72814. else {
  72815. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  72816. onError(request.status + " " + request.statusText);
  72817. });
  72818. }
  72819. };
  72820. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  72821. var material = gltfRuntime.materials[id];
  72822. var technique = gltfRuntime.techniques[material.technique];
  72823. if (!technique) {
  72824. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  72825. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  72826. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  72827. onSuccess(defaultMaterial);
  72828. return;
  72829. }
  72830. var program = gltfRuntime.programs[technique.program];
  72831. var states = technique.states;
  72832. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  72833. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  72834. var newVertexShader = "";
  72835. var newPixelShader = "";
  72836. var vertexTokenizer = new Tokenizer(vertexShader);
  72837. var pixelTokenizer = new Tokenizer(pixelShader);
  72838. var unTreatedUniforms = {};
  72839. var uniforms = [];
  72840. var attributes = [];
  72841. var samplers = [];
  72842. // Fill uniform, sampler2D and attributes
  72843. for (var unif in technique.uniforms) {
  72844. var uniform = technique.uniforms[unif];
  72845. var uniformParameter = technique.parameters[uniform];
  72846. unTreatedUniforms[unif] = uniformParameter;
  72847. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  72848. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  72849. if (transformIndex !== -1) {
  72850. uniforms.push(babylonTransforms[transformIndex]);
  72851. delete unTreatedUniforms[unif];
  72852. }
  72853. else {
  72854. uniforms.push(unif);
  72855. }
  72856. }
  72857. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  72858. samplers.push(unif);
  72859. }
  72860. else {
  72861. uniforms.push(unif);
  72862. }
  72863. }
  72864. for (var attr in technique.attributes) {
  72865. var attribute = technique.attributes[attr];
  72866. var attributeParameter = technique.parameters[attribute];
  72867. if (attributeParameter.semantic) {
  72868. attributes.push(getAttribute(attributeParameter));
  72869. }
  72870. }
  72871. // Configure vertex shader
  72872. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  72873. var tokenType = vertexTokenizer.currentToken;
  72874. if (tokenType !== ETokenType.IDENTIFIER) {
  72875. newVertexShader += vertexTokenizer.currentString;
  72876. continue;
  72877. }
  72878. var foundAttribute = false;
  72879. for (var attr in technique.attributes) {
  72880. var attribute = technique.attributes[attr];
  72881. var attributeParameter = technique.parameters[attribute];
  72882. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  72883. newVertexShader += getAttribute(attributeParameter);
  72884. foundAttribute = true;
  72885. break;
  72886. }
  72887. }
  72888. if (foundAttribute) {
  72889. continue;
  72890. }
  72891. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  72892. }
  72893. // Configure pixel shader
  72894. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  72895. var tokenType = pixelTokenizer.currentToken;
  72896. if (tokenType !== ETokenType.IDENTIFIER) {
  72897. newPixelShader += pixelTokenizer.currentString;
  72898. continue;
  72899. }
  72900. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  72901. }
  72902. // Create shader material
  72903. var shaderPath = {
  72904. vertex: program.vertexShader + id,
  72905. fragment: program.fragmentShader + id
  72906. };
  72907. var options = {
  72908. attributes: attributes,
  72909. uniforms: uniforms,
  72910. samplers: samplers,
  72911. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  72912. };
  72913. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  72914. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  72915. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  72916. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  72917. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  72918. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  72919. if (states && states.functions) {
  72920. var functions = states.functions;
  72921. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  72922. shaderMaterial.backFaceCulling = false;
  72923. }
  72924. var blendFunc = functions.blendFuncSeparate;
  72925. if (blendFunc) {
  72926. 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) {
  72927. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  72928. }
  72929. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  72930. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72931. }
  72932. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  72933. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  72934. }
  72935. 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) {
  72936. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  72937. }
  72938. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  72939. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  72940. }
  72941. 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) {
  72942. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  72943. }
  72944. }
  72945. }
  72946. };
  72947. return GLTFLoaderBase;
  72948. }());
  72949. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  72950. /**
  72951. * glTF V1 Loader
  72952. */
  72953. var GLTFLoader = (function () {
  72954. function GLTFLoader() {
  72955. }
  72956. GLTFLoader.RegisterExtension = function (extension) {
  72957. if (GLTFLoader.Extensions[extension.name]) {
  72958. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  72959. return;
  72960. }
  72961. GLTFLoader.Extensions[extension.name] = extension;
  72962. };
  72963. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  72964. var _this = this;
  72965. scene.useRightHandedSystem = true;
  72966. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  72967. gltfRuntime.importOnlyMeshes = true;
  72968. if (meshesNames === "") {
  72969. gltfRuntime.importMeshesNames = [];
  72970. }
  72971. else if (typeof meshesNames === "string") {
  72972. gltfRuntime.importMeshesNames = [meshesNames];
  72973. }
  72974. else if (meshesNames && !(meshesNames instanceof Array)) {
  72975. gltfRuntime.importMeshesNames = [meshesNames];
  72976. }
  72977. else {
  72978. gltfRuntime.importMeshesNames = [];
  72979. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  72980. }
  72981. // Create nodes
  72982. _this._createNodes(gltfRuntime);
  72983. var meshes = [];
  72984. var skeletons = [];
  72985. // Fill arrays of meshes and skeletons
  72986. for (var nde in gltfRuntime.nodes) {
  72987. var node = gltfRuntime.nodes[nde];
  72988. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  72989. meshes.push(node.babylonNode);
  72990. }
  72991. }
  72992. for (var skl in gltfRuntime.skins) {
  72993. var skin = gltfRuntime.skins[skl];
  72994. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  72995. skeletons.push(skin.babylonSkeleton);
  72996. }
  72997. }
  72998. // Load buffers, shaders, materials, etc.
  72999. _this._loadBuffersAsync(gltfRuntime, function () {
  73000. _this._loadShadersAsync(gltfRuntime, function () {
  73001. importMaterials(gltfRuntime);
  73002. postLoad(gltfRuntime);
  73003. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  73004. onSuccess(meshes, null, skeletons);
  73005. }
  73006. });
  73007. }, onProgress);
  73008. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  73009. onSuccess(meshes, null, skeletons);
  73010. }
  73011. }, onError);
  73012. return true;
  73013. };
  73014. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  73015. var _this = this;
  73016. scene.useRightHandedSystem = true;
  73017. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  73018. // Load runtime extensios
  73019. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  73020. // Create nodes
  73021. _this._createNodes(gltfRuntime);
  73022. // Load buffers, shaders, materials, etc.
  73023. _this._loadBuffersAsync(gltfRuntime, function () {
  73024. _this._loadShadersAsync(gltfRuntime, function () {
  73025. importMaterials(gltfRuntime);
  73026. postLoad(gltfRuntime);
  73027. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  73028. onSuccess();
  73029. }
  73030. });
  73031. });
  73032. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  73033. onSuccess();
  73034. }
  73035. }, onError);
  73036. }, onError);
  73037. };
  73038. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  73039. var hasShaders = false;
  73040. var processShader = function (sha, shader) {
  73041. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  73042. gltfRuntime.loadedShaderCount++;
  73043. if (shaderString) {
  73044. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  73045. }
  73046. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  73047. onload();
  73048. }
  73049. }, function () {
  73050. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  73051. });
  73052. };
  73053. for (var sha in gltfRuntime.shaders) {
  73054. hasShaders = true;
  73055. var shader = gltfRuntime.shaders[sha];
  73056. if (shader) {
  73057. processShader.bind(this, sha, shader)();
  73058. }
  73059. else {
  73060. BABYLON.Tools.Error("No shader named: " + sha);
  73061. }
  73062. }
  73063. if (!hasShaders) {
  73064. onload();
  73065. }
  73066. };
  73067. ;
  73068. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  73069. var hasBuffers = false;
  73070. var processBuffer = function (buf, buffer) {
  73071. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  73072. gltfRuntime.loadedBufferCount++;
  73073. if (bufferView) {
  73074. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  73075. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  73076. }
  73077. gltfRuntime.loadedBufferViews[buf] = bufferView;
  73078. }
  73079. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  73080. onLoad();
  73081. }
  73082. }, function () {
  73083. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  73084. });
  73085. };
  73086. for (var buf in gltfRuntime.buffers) {
  73087. hasBuffers = true;
  73088. var buffer = gltfRuntime.buffers[buf];
  73089. if (buffer) {
  73090. processBuffer.bind(this, buf, buffer)();
  73091. }
  73092. else {
  73093. BABYLON.Tools.Error("No buffer named: " + buf);
  73094. }
  73095. }
  73096. if (!hasBuffers) {
  73097. onLoad();
  73098. }
  73099. };
  73100. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  73101. var currentScene = gltfRuntime.currentScene;
  73102. if (currentScene) {
  73103. // Only one scene even if multiple scenes are defined
  73104. for (var i = 0; i < currentScene.nodes.length; i++) {
  73105. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73106. }
  73107. }
  73108. else {
  73109. // Load all scenes
  73110. for (var thing in gltfRuntime.scenes) {
  73111. currentScene = gltfRuntime.scenes[thing];
  73112. for (var i = 0; i < currentScene.nodes.length; i++) {
  73113. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73114. }
  73115. }
  73116. }
  73117. };
  73118. GLTFLoader.Extensions = {};
  73119. return GLTFLoader;
  73120. }());
  73121. GLTF1.GLTFLoader = GLTFLoader;
  73122. ;
  73123. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  73124. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73125. })(BABYLON || (BABYLON = {}));
  73126. //# sourceMappingURL=babylon.glTFLoader.js.map
  73127. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73128. var BABYLON;
  73129. (function (BABYLON) {
  73130. var GLTF1;
  73131. (function (GLTF1) {
  73132. /**
  73133. * Utils functions for GLTF
  73134. */
  73135. var GLTFUtils = (function () {
  73136. function GLTFUtils() {
  73137. }
  73138. /**
  73139. * Sets the given "parameter" matrix
  73140. * @param scene: the {BABYLON.Scene} object
  73141. * @param source: the source node where to pick the matrix
  73142. * @param parameter: the GLTF technique parameter
  73143. * @param uniformName: the name of the shader's uniform
  73144. * @param shaderMaterial: the shader material
  73145. */
  73146. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  73147. var mat = null;
  73148. if (parameter.semantic === "MODEL") {
  73149. mat = source.getWorldMatrix();
  73150. }
  73151. else if (parameter.semantic === "PROJECTION") {
  73152. mat = scene.getProjectionMatrix();
  73153. }
  73154. else if (parameter.semantic === "VIEW") {
  73155. mat = scene.getViewMatrix();
  73156. }
  73157. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  73158. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  73159. }
  73160. else if (parameter.semantic === "MODELVIEW") {
  73161. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  73162. }
  73163. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  73164. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  73165. }
  73166. else if (parameter.semantic === "MODELINVERSE") {
  73167. mat = source.getWorldMatrix().invert();
  73168. }
  73169. else if (parameter.semantic === "VIEWINVERSE") {
  73170. mat = scene.getViewMatrix().invert();
  73171. }
  73172. else if (parameter.semantic === "PROJECTIONINVERSE") {
  73173. mat = scene.getProjectionMatrix().invert();
  73174. }
  73175. else if (parameter.semantic === "MODELVIEWINVERSE") {
  73176. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  73177. }
  73178. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  73179. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  73180. }
  73181. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  73182. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  73183. }
  73184. else {
  73185. debugger;
  73186. }
  73187. switch (parameter.type) {
  73188. case GLTF1.EParameterType.FLOAT_MAT2:
  73189. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  73190. break;
  73191. case GLTF1.EParameterType.FLOAT_MAT3:
  73192. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  73193. break;
  73194. case GLTF1.EParameterType.FLOAT_MAT4:
  73195. shaderMaterial.setMatrix(uniformName, mat);
  73196. break;
  73197. default: break;
  73198. }
  73199. };
  73200. /**
  73201. * Sets the given "parameter" matrix
  73202. * @param shaderMaterial: the shader material
  73203. * @param uniform: the name of the shader's uniform
  73204. * @param value: the value of the uniform
  73205. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  73206. */
  73207. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  73208. switch (type) {
  73209. case GLTF1.EParameterType.FLOAT:
  73210. shaderMaterial.setFloat(uniform, value);
  73211. return true;
  73212. case GLTF1.EParameterType.FLOAT_VEC2:
  73213. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  73214. return true;
  73215. case GLTF1.EParameterType.FLOAT_VEC3:
  73216. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  73217. return true;
  73218. case GLTF1.EParameterType.FLOAT_VEC4:
  73219. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  73220. return true;
  73221. default: return false;
  73222. }
  73223. };
  73224. /**
  73225. * If the uri is a base64 string
  73226. * @param uri: the uri to test
  73227. */
  73228. GLTFUtils.IsBase64 = function (uri) {
  73229. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  73230. };
  73231. /**
  73232. * Decode the base64 uri
  73233. * @param uri: the uri to decode
  73234. */
  73235. GLTFUtils.DecodeBase64 = function (uri) {
  73236. var decodedString = atob(uri.split(",")[1]);
  73237. var bufferLength = decodedString.length;
  73238. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  73239. for (var i = 0; i < bufferLength; i++) {
  73240. bufferView[i] = decodedString.charCodeAt(i);
  73241. }
  73242. return bufferView.buffer;
  73243. };
  73244. /**
  73245. * Returns the wrap mode of the texture
  73246. * @param mode: the mode value
  73247. */
  73248. GLTFUtils.GetWrapMode = function (mode) {
  73249. switch (mode) {
  73250. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  73251. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  73252. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  73253. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  73254. }
  73255. };
  73256. /**
  73257. * Returns the byte stride giving an accessor
  73258. * @param accessor: the GLTF accessor objet
  73259. */
  73260. GLTFUtils.GetByteStrideFromType = function (accessor) {
  73261. // Needs this function since "byteStride" isn't requiered in glTF format
  73262. var type = accessor.type;
  73263. switch (type) {
  73264. case "VEC2": return 2;
  73265. case "VEC3": return 3;
  73266. case "VEC4": return 4;
  73267. case "MAT2": return 4;
  73268. case "MAT3": return 9;
  73269. case "MAT4": return 16;
  73270. default: return 1;
  73271. }
  73272. };
  73273. /**
  73274. * Returns the texture filter mode giving a mode value
  73275. * @param mode: the filter mode value
  73276. */
  73277. GLTFUtils.GetTextureFilterMode = function (mode) {
  73278. switch (mode) {
  73279. case GLTF1.ETextureFilterType.LINEAR:
  73280. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  73281. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  73282. case GLTF1.ETextureFilterType.NEAREST:
  73283. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  73284. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  73285. }
  73286. };
  73287. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  73288. var byteOffset = bufferView.byteOffset + byteOffset;
  73289. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  73290. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  73291. throw new Error("Buffer access is out of range");
  73292. }
  73293. var buffer = loadedBufferView.buffer;
  73294. byteOffset += loadedBufferView.byteOffset;
  73295. switch (componentType) {
  73296. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  73297. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  73298. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  73299. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  73300. default: return new Float32Array(buffer, byteOffset, byteLength);
  73301. }
  73302. };
  73303. /**
  73304. * Returns a buffer from its accessor
  73305. * @param gltfRuntime: the GLTF runtime
  73306. * @param accessor: the GLTF accessor
  73307. */
  73308. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  73309. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  73310. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  73311. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  73312. };
  73313. /**
  73314. * Decodes a buffer view into a string
  73315. * @param view: the buffer view
  73316. */
  73317. GLTFUtils.DecodeBufferToText = function (view) {
  73318. var result = "";
  73319. var length = view.byteLength;
  73320. for (var i = 0; i < length; ++i) {
  73321. result += String.fromCharCode(view[i]);
  73322. }
  73323. return result;
  73324. };
  73325. /**
  73326. * Returns the default material of gltf. Related to
  73327. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  73328. * @param scene: the Babylon.js scene
  73329. */
  73330. GLTFUtils.GetDefaultMaterial = function (scene) {
  73331. if (!GLTFUtils._DefaultMaterial) {
  73332. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  73333. "precision highp float;",
  73334. "",
  73335. "uniform mat4 worldView;",
  73336. "uniform mat4 projection;",
  73337. "",
  73338. "attribute vec3 position;",
  73339. "",
  73340. "void main(void)",
  73341. "{",
  73342. " gl_Position = projection * worldView * vec4(position, 1.0);",
  73343. "}"
  73344. ].join("\n");
  73345. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  73346. "precision highp float;",
  73347. "",
  73348. "uniform vec4 u_emission;",
  73349. "",
  73350. "void main(void)",
  73351. "{",
  73352. " gl_FragColor = u_emission;",
  73353. "}"
  73354. ].join("\n");
  73355. var shaderPath = {
  73356. vertex: "GLTFDefaultMaterial",
  73357. fragment: "GLTFDefaultMaterial"
  73358. };
  73359. var options = {
  73360. attributes: ["position"],
  73361. uniforms: ["worldView", "projection", "u_emission"],
  73362. samplers: [],
  73363. needAlphaBlending: false
  73364. };
  73365. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  73366. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  73367. }
  73368. return GLTFUtils._DefaultMaterial;
  73369. };
  73370. // The GLTF default material
  73371. GLTFUtils._DefaultMaterial = null;
  73372. return GLTFUtils;
  73373. }());
  73374. GLTF1.GLTFUtils = GLTFUtils;
  73375. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73376. })(BABYLON || (BABYLON = {}));
  73377. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  73378. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73379. var BABYLON;
  73380. (function (BABYLON) {
  73381. var GLTF1;
  73382. (function (GLTF1) {
  73383. var GLTFLoaderExtension = (function () {
  73384. function GLTFLoaderExtension(name) {
  73385. this._name = name;
  73386. }
  73387. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  73388. get: function () {
  73389. return this._name;
  73390. },
  73391. enumerable: true,
  73392. configurable: true
  73393. });
  73394. /**
  73395. * Defines an override for loading the runtime
  73396. * Return true to stop further extensions from loading the runtime
  73397. */
  73398. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  73399. return false;
  73400. };
  73401. /**
  73402. * Defines an onverride for creating gltf runtime
  73403. * Return true to stop further extensions from creating the runtime
  73404. */
  73405. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  73406. return false;
  73407. };
  73408. /**
  73409. * Defines an override for loading buffers
  73410. * Return true to stop further extensions from loading this buffer
  73411. */
  73412. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  73413. return false;
  73414. };
  73415. /**
  73416. * Defines an override for loading texture buffers
  73417. * Return true to stop further extensions from loading this texture data
  73418. */
  73419. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  73420. return false;
  73421. };
  73422. /**
  73423. * Defines an override for creating textures
  73424. * Return true to stop further extensions from loading this texture
  73425. */
  73426. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  73427. return false;
  73428. };
  73429. /**
  73430. * Defines an override for loading shader strings
  73431. * Return true to stop further extensions from loading this shader data
  73432. */
  73433. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  73434. return false;
  73435. };
  73436. /**
  73437. * Defines an override for loading materials
  73438. * Return true to stop further extensions from loading this material
  73439. */
  73440. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  73441. return false;
  73442. };
  73443. // ---------
  73444. // Utilities
  73445. // ---------
  73446. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  73447. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73448. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  73449. }, function () {
  73450. setTimeout(function () {
  73451. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  73452. });
  73453. });
  73454. };
  73455. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  73456. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73457. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  73458. }, function () {
  73459. setTimeout(function () {
  73460. onSuccess();
  73461. });
  73462. });
  73463. };
  73464. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  73465. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73466. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  73467. }, function () {
  73468. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  73469. });
  73470. };
  73471. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  73472. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  73473. };
  73474. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  73475. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73476. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  73477. }, function () {
  73478. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  73479. });
  73480. };
  73481. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  73482. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73483. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  73484. }, function () {
  73485. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  73486. });
  73487. };
  73488. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  73489. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73490. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  73491. }, function () {
  73492. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  73493. });
  73494. };
  73495. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  73496. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  73497. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  73498. }, function () {
  73499. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  73500. });
  73501. };
  73502. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  73503. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  73504. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  73505. if (func(loaderExtension)) {
  73506. return;
  73507. }
  73508. }
  73509. defaultFunc();
  73510. };
  73511. return GLTFLoaderExtension;
  73512. }());
  73513. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  73514. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73515. })(BABYLON || (BABYLON = {}));
  73516. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  73517. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73518. var BABYLON;
  73519. (function (BABYLON) {
  73520. var GLTF1;
  73521. (function (GLTF1) {
  73522. var BinaryExtensionBufferName = "binary_glTF";
  73523. var EContentFormat;
  73524. (function (EContentFormat) {
  73525. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  73526. })(EContentFormat || (EContentFormat = {}));
  73527. ;
  73528. ;
  73529. ;
  73530. var GLTFBinaryExtension = (function (_super) {
  73531. __extends(GLTFBinaryExtension, _super);
  73532. function GLTFBinaryExtension() {
  73533. return _super.call(this, "KHR_binary_glTF") || this;
  73534. }
  73535. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  73536. var extensionsUsed = data.json.extensionsUsed;
  73537. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  73538. return false;
  73539. }
  73540. this._bin = data.bin;
  73541. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  73542. return true;
  73543. };
  73544. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  73545. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  73546. return false;
  73547. }
  73548. if (id !== BinaryExtensionBufferName) {
  73549. return false;
  73550. }
  73551. onSuccess(this._bin);
  73552. return true;
  73553. };
  73554. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  73555. var texture = gltfRuntime.textures[id];
  73556. var source = gltfRuntime.images[texture.source];
  73557. if (!source.extensions || !(this.name in source.extensions)) {
  73558. return false;
  73559. }
  73560. var sourceExt = source.extensions[this.name];
  73561. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  73562. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  73563. onSuccess(buffer);
  73564. return true;
  73565. };
  73566. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  73567. var shader = gltfRuntime.shaders[id];
  73568. if (!shader.extensions || !(this.name in shader.extensions)) {
  73569. return false;
  73570. }
  73571. var binaryExtensionShader = shader.extensions[this.name];
  73572. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  73573. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  73574. setTimeout(function () {
  73575. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  73576. onSuccess(shaderString);
  73577. });
  73578. return true;
  73579. };
  73580. return GLTFBinaryExtension;
  73581. }(GLTF1.GLTFLoaderExtension));
  73582. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  73583. var BinaryReader = (function () {
  73584. function BinaryReader(arrayBuffer) {
  73585. this._arrayBuffer = arrayBuffer;
  73586. this._dataView = new DataView(arrayBuffer);
  73587. this._byteOffset = 0;
  73588. }
  73589. BinaryReader.prototype.getUint32 = function () {
  73590. var value = this._dataView.getUint32(this._byteOffset, true);
  73591. this._byteOffset += 4;
  73592. return value;
  73593. };
  73594. BinaryReader.prototype.getUint8Array = function (length) {
  73595. if (!length) {
  73596. length = this._arrayBuffer.byteLength - this._byteOffset;
  73597. }
  73598. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  73599. this._byteOffset += length;
  73600. return value;
  73601. };
  73602. return BinaryReader;
  73603. }());
  73604. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  73605. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73606. })(BABYLON || (BABYLON = {}));
  73607. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  73608. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73609. var BABYLON;
  73610. (function (BABYLON) {
  73611. var GLTF1;
  73612. (function (GLTF1) {
  73613. ;
  73614. ;
  73615. ;
  73616. var GLTFMaterialsCommonExtension = (function (_super) {
  73617. __extends(GLTFMaterialsCommonExtension, _super);
  73618. function GLTFMaterialsCommonExtension() {
  73619. return _super.call(this, "KHR_materials_common") || this;
  73620. }
  73621. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  73622. if (!gltfRuntime.extensions)
  73623. return false;
  73624. var extension = gltfRuntime.extensions[this.name];
  73625. if (!extension)
  73626. return false;
  73627. // Create lights
  73628. var lights = extension.lights;
  73629. if (lights) {
  73630. for (var thing in lights) {
  73631. var light = lights[thing];
  73632. switch (light.type) {
  73633. case "ambient":
  73634. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  73635. var ambient = light.ambient;
  73636. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  73637. break;
  73638. case "point":
  73639. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  73640. var point = light.point;
  73641. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  73642. break;
  73643. case "directional":
  73644. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  73645. var directional = light.directional;
  73646. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  73647. break;
  73648. case "spot":
  73649. var spot = light.spot;
  73650. 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);
  73651. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  73652. break;
  73653. default:
  73654. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  73655. break;
  73656. }
  73657. }
  73658. }
  73659. return false;
  73660. };
  73661. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  73662. var material = gltfRuntime.materials[id];
  73663. if (!material || !material.extensions)
  73664. return false;
  73665. var extension = material.extensions[this.name];
  73666. if (!extension)
  73667. return false;
  73668. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  73669. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  73670. if (extension.technique === "CONSTANT") {
  73671. standardMaterial.disableLighting = true;
  73672. }
  73673. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  73674. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  73675. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  73676. // Ambient
  73677. if (typeof extension.values.ambient === "string") {
  73678. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  73679. }
  73680. else {
  73681. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  73682. }
  73683. // Diffuse
  73684. if (typeof extension.values.diffuse === "string") {
  73685. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  73686. }
  73687. else {
  73688. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  73689. }
  73690. // Emission
  73691. if (typeof extension.values.emission === "string") {
  73692. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  73693. }
  73694. else {
  73695. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  73696. }
  73697. // Specular
  73698. if (typeof extension.values.specular === "string") {
  73699. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  73700. }
  73701. else {
  73702. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  73703. }
  73704. return true;
  73705. };
  73706. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  73707. // Create buffer from texture url
  73708. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  73709. // Create texture from buffer
  73710. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  73711. }, onError);
  73712. };
  73713. return GLTFMaterialsCommonExtension;
  73714. }(GLTF1.GLTFLoaderExtension));
  73715. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  73716. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  73717. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73718. })(BABYLON || (BABYLON = {}));
  73719. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  73720. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73721. var BABYLON;
  73722. (function (BABYLON) {
  73723. var GLTF2;
  73724. (function (GLTF2) {
  73725. /**
  73726. * Enums
  73727. */
  73728. var EComponentType;
  73729. (function (EComponentType) {
  73730. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  73731. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  73732. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  73733. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  73734. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  73735. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  73736. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  73737. var EMeshPrimitiveMode;
  73738. (function (EMeshPrimitiveMode) {
  73739. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  73740. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  73741. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  73742. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  73743. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  73744. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  73745. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  73746. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  73747. var ETextureMagFilter;
  73748. (function (ETextureMagFilter) {
  73749. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  73750. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  73751. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  73752. var ETextureMinFilter;
  73753. (function (ETextureMinFilter) {
  73754. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  73755. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  73756. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  73757. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  73758. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  73759. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  73760. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  73761. var ETextureWrapMode;
  73762. (function (ETextureWrapMode) {
  73763. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  73764. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  73765. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  73766. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  73767. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  73768. })(BABYLON || (BABYLON = {}));
  73769. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  73770. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73771. var BABYLON;
  73772. (function (BABYLON) {
  73773. var GLTF2;
  73774. (function (GLTF2) {
  73775. var GLTFLoader = (function () {
  73776. function GLTFLoader(parent) {
  73777. this._renderReady = false;
  73778. this._disposed = false;
  73779. this._blockPendingTracking = false;
  73780. // Observable with boolean indicating success or error.
  73781. this._renderReadyObservable = new BABYLON.Observable();
  73782. // Count of pending work that needs to complete before the asset is rendered.
  73783. this._renderPendingCount = 0;
  73784. // Count of pending work that needs to complete before the loader is cleared.
  73785. this._loaderPendingCount = 0;
  73786. this._parent = parent;
  73787. }
  73788. GLTFLoader.RegisterExtension = function (extension) {
  73789. if (GLTFLoader.Extensions[extension.name]) {
  73790. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  73791. return;
  73792. }
  73793. GLTFLoader.Extensions[extension.name] = extension;
  73794. // Keep the order of registration so that extensions registered first are called first.
  73795. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  73796. };
  73797. Object.defineProperty(GLTFLoader.prototype, "gltf", {
  73798. get: function () {
  73799. return this._gltf;
  73800. },
  73801. enumerable: true,
  73802. configurable: true
  73803. });
  73804. Object.defineProperty(GLTFLoader.prototype, "babylonScene", {
  73805. get: function () {
  73806. return this._babylonScene;
  73807. },
  73808. enumerable: true,
  73809. configurable: true
  73810. });
  73811. GLTFLoader.prototype.executeWhenRenderReady = function (func) {
  73812. if (this._renderReady) {
  73813. func();
  73814. }
  73815. else {
  73816. this._renderReadyObservable.add(func);
  73817. }
  73818. };
  73819. GLTFLoader.prototype.dispose = function () {
  73820. if (this._disposed) {
  73821. return;
  73822. }
  73823. this._disposed = true;
  73824. // Revoke object urls created during load
  73825. if (this._gltf.textures) {
  73826. this._gltf.textures.forEach(function (texture) {
  73827. if (texture.url) {
  73828. URL.revokeObjectURL(texture.url);
  73829. }
  73830. });
  73831. }
  73832. this._gltf = undefined;
  73833. this._babylonScene = undefined;
  73834. this._rootUrl = undefined;
  73835. this._defaultMaterial = undefined;
  73836. this._successCallback = undefined;
  73837. this._errorCallback = undefined;
  73838. this._renderReady = false;
  73839. this._renderReadyObservable.clear();
  73840. this._renderPendingCount = 0;
  73841. this._loaderPendingCount = 0;
  73842. };
  73843. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  73844. var _this = this;
  73845. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  73846. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  73847. }, onProgress, onError);
  73848. };
  73849. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  73850. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  73851. };
  73852. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  73853. this._loadData(data);
  73854. this._babylonScene = scene;
  73855. this._rootUrl = rootUrl;
  73856. this._successCallback = onSuccess;
  73857. this._progressCallback = onProgress;
  73858. this._errorCallback = onError;
  73859. this.addPendingData(this);
  73860. this._loadScene(nodeNames);
  73861. this._loadAnimations();
  73862. this.removePendingData(this);
  73863. };
  73864. GLTFLoader.prototype._onError = function (message) {
  73865. this._errorCallback(message);
  73866. this.dispose();
  73867. };
  73868. GLTFLoader.prototype._onProgress = function (event) {
  73869. this._progressCallback(event);
  73870. };
  73871. GLTFLoader.prototype._onRenderReady = function () {
  73872. switch (this._parent.coordinateSystemMode) {
  73873. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  73874. if (!this._babylonScene.useRightHandedSystem) {
  73875. this._addRightHandToLeftHandRootTransform();
  73876. }
  73877. break;
  73878. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  73879. // do nothing
  73880. break;
  73881. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  73882. this._babylonScene.useRightHandedSystem = true;
  73883. break;
  73884. default:
  73885. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  73886. break;
  73887. }
  73888. this._showMeshes();
  73889. this._startAnimations();
  73890. this._successCallback();
  73891. this._renderReadyObservable.notifyObservers(this);
  73892. };
  73893. GLTFLoader.prototype._onLoaderComplete = function () {
  73894. if (this._parent.onComplete) {
  73895. this._parent.onComplete();
  73896. }
  73897. };
  73898. GLTFLoader.prototype._onLoaderFirstLODComplete = function () {
  73899. if (this._parent.onFirstLODComplete) {
  73900. this._parent.onFirstLODComplete();
  73901. }
  73902. };
  73903. GLTFLoader.prototype._loadData = function (data) {
  73904. this._gltf = data.json;
  73905. var binaryBuffer;
  73906. var buffers = this._gltf.buffers;
  73907. if (buffers && buffers[0].uri === undefined) {
  73908. binaryBuffer = buffers[0];
  73909. }
  73910. if (data.bin) {
  73911. if (binaryBuffer) {
  73912. if (binaryBuffer.byteLength != data.bin.byteLength) {
  73913. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  73914. }
  73915. }
  73916. else {
  73917. BABYLON.Tools.Warn("Unexpected BIN chunk");
  73918. }
  73919. binaryBuffer.loadedData = data.bin;
  73920. }
  73921. };
  73922. GLTFLoader.prototype._addRightHandToLeftHandRootTransform = function () {
  73923. var rootMesh = new BABYLON.Mesh("root", this._babylonScene);
  73924. rootMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  73925. rootMesh.rotation.y = Math.PI;
  73926. var nodes = this._gltf.nodes;
  73927. if (nodes) {
  73928. for (var i = 0; i < nodes.length; i++) {
  73929. var mesh = nodes[i].babylonMesh;
  73930. if (mesh && !mesh.parent) {
  73931. mesh.parent = rootMesh;
  73932. }
  73933. }
  73934. }
  73935. };
  73936. GLTFLoader.prototype._getMeshes = function () {
  73937. var meshes = [];
  73938. var nodes = this._gltf.nodes;
  73939. if (nodes) {
  73940. nodes.forEach(function (node) {
  73941. if (node.babylonMesh) {
  73942. meshes.push(node.babylonMesh);
  73943. }
  73944. });
  73945. }
  73946. return meshes;
  73947. };
  73948. GLTFLoader.prototype._getSkeletons = function () {
  73949. var skeletons = [];
  73950. var skins = this._gltf.skins;
  73951. if (skins) {
  73952. skins.forEach(function (skin) {
  73953. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  73954. skeletons.push(skin.babylonSkeleton);
  73955. }
  73956. });
  73957. }
  73958. return skeletons;
  73959. };
  73960. GLTFLoader.prototype._getAnimationTargets = function () {
  73961. var targets = [];
  73962. var animations = this._gltf.animations;
  73963. if (animations) {
  73964. animations.forEach(function (animation) {
  73965. targets.push.apply(targets, animation.targets);
  73966. });
  73967. }
  73968. return targets;
  73969. };
  73970. GLTFLoader.prototype._showMeshes = function () {
  73971. this._getMeshes().forEach(function (mesh) { return mesh.isVisible = true; });
  73972. };
  73973. GLTFLoader.prototype._startAnimations = function () {
  73974. var _this = this;
  73975. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  73976. };
  73977. GLTFLoader.prototype._loadScene = function (nodeNames) {
  73978. var _this = this;
  73979. var scene = this._gltf.scenes[this._gltf.scene || 0];
  73980. var nodeIndices = scene.nodes;
  73981. this._traverseNodes(nodeIndices, function (node, index, parentNode) {
  73982. node.index = index;
  73983. node.parent = parentNode;
  73984. return true;
  73985. });
  73986. var materials = this._gltf.materials;
  73987. if (materials) {
  73988. materials.forEach(function (material, index) { return material.index = index; });
  73989. }
  73990. if (nodeNames) {
  73991. if (!(nodeNames instanceof Array)) {
  73992. nodeNames = [nodeNames];
  73993. }
  73994. var filteredNodeIndices = new Array();
  73995. this._traverseNodes(nodeIndices, function (node) {
  73996. if (nodeNames.indexOf(node.name) === -1) {
  73997. return true;
  73998. }
  73999. filteredNodeIndices.push(node.index);
  74000. return false;
  74001. });
  74002. nodeIndices = filteredNodeIndices;
  74003. }
  74004. this._traverseNodes(nodeIndices, function (node) { return _this._loadSkin(node); });
  74005. this._traverseNodes(nodeIndices, function (node) { return _this._loadMesh(node); });
  74006. };
  74007. GLTFLoader.prototype._loadSkin = function (node) {
  74008. var _this = this;
  74009. if (node.skin !== undefined) {
  74010. var skin = this._gltf.skins[node.skin];
  74011. var skeletonId = "skeleton" + node.skin;
  74012. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  74013. skin.index = node.skin;
  74014. for (var i = 0; i < skin.joints.length; i++) {
  74015. this._createBone(this._gltf.nodes[skin.joints[i]], skin);
  74016. }
  74017. if (skin.skeleton === undefined) {
  74018. // TODO: handle when skeleton is not defined
  74019. throw new Error("Not implemented");
  74020. }
  74021. if (skin.inverseBindMatrices === undefined) {
  74022. // TODO: handle when inverse bind matrices are not defined
  74023. throw new Error("Not implemented");
  74024. }
  74025. var accessor = this._gltf.accessors[skin.inverseBindMatrices];
  74026. this._loadAccessorAsync(accessor, function (data) {
  74027. _this._traverseNode(skin.skeleton, function (node, index, parent) { return _this._updateBone(node, parent, skin, data); });
  74028. });
  74029. }
  74030. return true;
  74031. };
  74032. GLTFLoader.prototype._updateBone = function (node, parentNode, skin, inverseBindMatrixData) {
  74033. var jointIndex = skin.joints.indexOf(node.index);
  74034. if (jointIndex === -1) {
  74035. this._createBone(node, skin);
  74036. }
  74037. var babylonBone = node.babylonSkinToBones[skin.index];
  74038. // TODO: explain the math
  74039. var matrix = jointIndex === -1 ? BABYLON.Matrix.Identity() : BABYLON.Matrix.FromArray(inverseBindMatrixData, jointIndex * 16);
  74040. matrix.invertToRef(matrix);
  74041. if (parentNode) {
  74042. babylonBone.setParent(parentNode.babylonSkinToBones[skin.index], false);
  74043. matrix.multiplyToRef(babylonBone.getParent().getInvertedAbsoluteTransform(), matrix);
  74044. }
  74045. babylonBone.updateMatrix(matrix);
  74046. return true;
  74047. };
  74048. GLTFLoader.prototype._createBone = function (node, skin) {
  74049. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton);
  74050. node.babylonSkinToBones = node.babylonSkinToBones || {};
  74051. node.babylonSkinToBones[skin.index] = babylonBone;
  74052. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  74053. node.babylonAnimationTargets.push(babylonBone);
  74054. return babylonBone;
  74055. };
  74056. GLTFLoader.prototype._loadMesh = function (node) {
  74057. var babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  74058. babylonMesh.isVisible = false;
  74059. this._loadTransform(node, babylonMesh);
  74060. if (node.mesh !== undefined) {
  74061. var mesh = this._gltf.meshes[node.mesh];
  74062. this._loadMeshData(node, mesh, babylonMesh);
  74063. }
  74064. babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  74065. node.babylonMesh = babylonMesh;
  74066. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  74067. node.babylonAnimationTargets.push(node.babylonMesh);
  74068. if (node.skin !== undefined) {
  74069. var skin = this._gltf.skins[node.skin];
  74070. babylonMesh.skeleton = skin.babylonSkeleton;
  74071. }
  74072. if (node.camera !== undefined) {
  74073. // TODO: handle cameras
  74074. }
  74075. return true;
  74076. };
  74077. GLTFLoader.prototype._loadMeshData = function (node, mesh, babylonMesh) {
  74078. var _this = this;
  74079. babylonMesh.name = mesh.name || babylonMesh.name;
  74080. var babylonMultiMaterial = new BABYLON.MultiMaterial(babylonMesh.name, this._babylonScene);
  74081. babylonMesh.material = babylonMultiMaterial;
  74082. var geometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene, null, false, babylonMesh);
  74083. var vertexData = new BABYLON.VertexData();
  74084. vertexData.positions = [];
  74085. vertexData.indices = [];
  74086. var subMeshInfos = [];
  74087. var loadedPrimitives = 0;
  74088. var totalPrimitives = mesh.primitives.length;
  74089. var _loop_1 = function (i) {
  74090. var primitive = mesh.primitives[i];
  74091. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  74092. // TODO: handle other primitive modes
  74093. throw new Error("Not implemented");
  74094. }
  74095. this_1._createMorphTargets(node, mesh, primitive, babylonMesh);
  74096. this_1._loadVertexDataAsync(primitive, function (subVertexData) {
  74097. _this._loadMorphTargetsData(mesh, primitive, subVertexData, babylonMesh);
  74098. subMeshInfos.push({
  74099. materialIndex: i,
  74100. verticesStart: vertexData.positions.length,
  74101. verticesCount: subVertexData.positions.length,
  74102. indicesStart: vertexData.indices.length,
  74103. indicesCount: subVertexData.indices.length,
  74104. loadMaterial: function () {
  74105. if (primitive.material === undefined) {
  74106. babylonMultiMaterial.subMaterials[i] = _this._getDefaultMaterial();
  74107. }
  74108. else {
  74109. var material = _this._gltf.materials[primitive.material];
  74110. _this.loadMaterial(material, function (babylonMaterial, isNew) {
  74111. if (isNew && _this._parent.onMaterialLoaded) {
  74112. _this._parent.onMaterialLoaded(babylonMaterial);
  74113. }
  74114. if (_this._parent.onBeforeMaterialReadyAsync) {
  74115. _this.addLoaderPendingData(material);
  74116. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, babylonMesh, babylonMultiMaterial.subMaterials[i] != null, function () {
  74117. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  74118. _this.removeLoaderPendingData(material);
  74119. });
  74120. }
  74121. else {
  74122. babylonMultiMaterial.subMaterials[i] = babylonMaterial;
  74123. }
  74124. });
  74125. }
  74126. }
  74127. });
  74128. vertexData.merge(subVertexData);
  74129. if (++loadedPrimitives === totalPrimitives) {
  74130. geometry.setAllVerticesData(vertexData, false);
  74131. subMeshInfos.forEach(function (info) { return info.loadMaterial(); });
  74132. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  74133. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  74134. babylonMesh.subMeshes = [];
  74135. subMeshInfos.forEach(function (info) { return new BABYLON.SubMesh(info.materialIndex, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, babylonMesh); });
  74136. }
  74137. });
  74138. };
  74139. var this_1 = this;
  74140. for (var i = 0; i < totalPrimitives; i++) {
  74141. _loop_1(i);
  74142. }
  74143. };
  74144. GLTFLoader.prototype._loadVertexDataAsync = function (primitive, onSuccess) {
  74145. var _this = this;
  74146. var attributes = primitive.attributes;
  74147. if (!attributes) {
  74148. this._onError("Primitive has no attributes");
  74149. return;
  74150. }
  74151. var vertexData = new BABYLON.VertexData();
  74152. var loadedAttributes = 0;
  74153. var totalAttributes = Object.keys(attributes).length;
  74154. var _loop_2 = function (semantic) {
  74155. accessor = this_2._gltf.accessors[attributes[semantic]];
  74156. this_2._loadAccessorAsync(accessor, function (data) {
  74157. switch (semantic) {
  74158. case "NORMAL":
  74159. vertexData.normals = data;
  74160. break;
  74161. case "POSITION":
  74162. vertexData.positions = data;
  74163. break;
  74164. case "TANGENT":
  74165. vertexData.tangents = data;
  74166. break;
  74167. case "TEXCOORD_0":
  74168. vertexData.uvs = data;
  74169. break;
  74170. case "TEXCOORD_1":
  74171. vertexData.uvs2 = data;
  74172. break;
  74173. case "JOINTS_0":
  74174. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  74175. break;
  74176. case "WEIGHTS_0":
  74177. vertexData.matricesWeights = data;
  74178. break;
  74179. case "COLOR_0":
  74180. vertexData.colors = data;
  74181. break;
  74182. default:
  74183. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  74184. break;
  74185. }
  74186. if (++loadedAttributes === totalAttributes) {
  74187. var indicesAccessor = _this._gltf.accessors[primitive.indices];
  74188. if (indicesAccessor) {
  74189. _this._loadAccessorAsync(indicesAccessor, function (data) {
  74190. vertexData.indices = data;
  74191. onSuccess(vertexData);
  74192. });
  74193. }
  74194. else {
  74195. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  74196. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  74197. onSuccess(vertexData);
  74198. }
  74199. }
  74200. });
  74201. };
  74202. var this_2 = this, accessor;
  74203. for (var semantic in attributes) {
  74204. _loop_2(semantic);
  74205. }
  74206. };
  74207. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive, babylonMesh) {
  74208. var targets = primitive.targets;
  74209. if (!targets) {
  74210. return;
  74211. }
  74212. if (!babylonMesh.morphTargetManager) {
  74213. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  74214. }
  74215. for (var index = 0; index < targets.length; index++) {
  74216. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  74217. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  74218. }
  74219. };
  74220. GLTFLoader.prototype._loadMorphTargetsData = function (mesh, primitive, vertexData, babylonMesh) {
  74221. var targets = primitive.targets;
  74222. if (!targets) {
  74223. return;
  74224. }
  74225. var _loop_3 = function () {
  74226. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  74227. attributes = targets[index];
  74228. var _loop_4 = function (semantic) {
  74229. accessor = this_3._gltf.accessors[attributes[semantic]];
  74230. this_3._loadAccessorAsync(accessor, function (data) {
  74231. if (accessor.name) {
  74232. babylonMorphTarget.name = accessor.name;
  74233. }
  74234. // glTF stores morph target information as deltas while babylon.js expects the final data.
  74235. // As a result we have to add the original data to the delta to calculate the final data.
  74236. var values = data;
  74237. switch (semantic) {
  74238. case "NORMAL":
  74239. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  74240. babylonMorphTarget.setNormals(values);
  74241. break;
  74242. case "POSITION":
  74243. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  74244. babylonMorphTarget.setPositions(values);
  74245. break;
  74246. case "TANGENT":
  74247. // Tangent data for morph targets is stored as xyz delta.
  74248. // The vertexData.tangent is stored as xyzw.
  74249. // So we need to skip every fourth vertexData.tangent.
  74250. for (var i = 0, j = 0; i < values.length; i++, j++) {
  74251. values[i] += vertexData.tangents[j];
  74252. if ((i + 1) % 3 == 0) {
  74253. j++;
  74254. }
  74255. }
  74256. babylonMorphTarget.setTangents(values);
  74257. break;
  74258. default:
  74259. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  74260. break;
  74261. }
  74262. });
  74263. };
  74264. for (var semantic in attributes) {
  74265. _loop_4(semantic);
  74266. }
  74267. };
  74268. var this_3 = this, attributes, accessor;
  74269. for (var index = 0; index < targets.length; index++) {
  74270. _loop_3();
  74271. }
  74272. };
  74273. GLTFLoader.prototype._loadTransform = function (node, babylonMesh) {
  74274. var position = BABYLON.Vector3.Zero();
  74275. var rotation = BABYLON.Quaternion.Identity();
  74276. var scaling = BABYLON.Vector3.One();
  74277. if (node.matrix) {
  74278. var mat = BABYLON.Matrix.FromArray(node.matrix);
  74279. mat.decompose(scaling, rotation, position);
  74280. }
  74281. else {
  74282. if (node.translation)
  74283. position = BABYLON.Vector3.FromArray(node.translation);
  74284. if (node.rotation)
  74285. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  74286. if (node.scale)
  74287. scaling = BABYLON.Vector3.FromArray(node.scale);
  74288. }
  74289. babylonMesh.position = position;
  74290. babylonMesh.rotationQuaternion = rotation;
  74291. babylonMesh.scaling = scaling;
  74292. };
  74293. GLTFLoader.prototype._traverseNodes = function (indices, action, parentNode) {
  74294. if (parentNode === void 0) { parentNode = null; }
  74295. for (var i = 0; i < indices.length; i++) {
  74296. this._traverseNode(indices[i], action, parentNode);
  74297. }
  74298. };
  74299. GLTFLoader.prototype._traverseNode = function (index, action, parentNode) {
  74300. if (parentNode === void 0) { parentNode = null; }
  74301. var node = this._gltf.nodes[index];
  74302. if (!action(node, index, parentNode)) {
  74303. return;
  74304. }
  74305. if (node.children) {
  74306. for (var i = 0; i < node.children.length; i++) {
  74307. this._traverseNode(node.children[i], action, node);
  74308. }
  74309. }
  74310. };
  74311. GLTFLoader.prototype._loadAnimations = function () {
  74312. var animations = this._gltf.animations;
  74313. if (!animations || animations.length === 0) {
  74314. return;
  74315. }
  74316. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  74317. var animation = animations[animationIndex];
  74318. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  74319. this._loadAnimationChannel(animation, animationIndex, channelIndex);
  74320. }
  74321. }
  74322. };
  74323. GLTFLoader.prototype._loadAnimationChannel = function (animation, animationIndex, channelIndex) {
  74324. var channel = animation.channels[channelIndex];
  74325. var samplerIndex = channel.sampler;
  74326. var sampler = animation.samplers[samplerIndex];
  74327. var targetNode = this._gltf.nodes[channel.target.node];
  74328. if (!targetNode) {
  74329. BABYLON.Tools.Warn("Animation channel target node (" + channel.target.node + ") does not exist");
  74330. return;
  74331. }
  74332. var targetPath = {
  74333. "translation": "position",
  74334. "rotation": "rotationQuaternion",
  74335. "scale": "scaling",
  74336. "weights": "influence"
  74337. }[channel.target.path];
  74338. if (!targetPath) {
  74339. BABYLON.Tools.Warn("Animation channel target path '" + channel.target.path + "' is not valid");
  74340. return;
  74341. }
  74342. var animationType = {
  74343. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  74344. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  74345. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  74346. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  74347. }[targetPath];
  74348. var inputData;
  74349. var outputData;
  74350. var checkSuccess = function () {
  74351. if (!inputData || !outputData) {
  74352. return;
  74353. }
  74354. var outputBufferOffset = 0;
  74355. var getNextOutputValue = {
  74356. "position": function () {
  74357. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  74358. outputBufferOffset += 3;
  74359. return value;
  74360. },
  74361. "rotationQuaternion": function () {
  74362. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  74363. outputBufferOffset += 4;
  74364. return value;
  74365. },
  74366. "scaling": function () {
  74367. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  74368. outputBufferOffset += 3;
  74369. return value;
  74370. },
  74371. "influence": function () {
  74372. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  74373. var value = new Array(numTargets);
  74374. for (var i = 0; i < numTargets; i++) {
  74375. value[i] = outputData[outputBufferOffset++];
  74376. }
  74377. return value;
  74378. },
  74379. }[targetPath];
  74380. var getNextKey = {
  74381. "LINEAR": function (frameIndex) { return ({
  74382. frame: inputData[frameIndex],
  74383. value: getNextOutputValue()
  74384. }); },
  74385. "CUBICSPLINE": function (frameIndex) { return ({
  74386. frame: inputData[frameIndex],
  74387. inTangent: getNextOutputValue(),
  74388. value: getNextOutputValue(),
  74389. outTangent: getNextOutputValue()
  74390. }); },
  74391. }[sampler.interpolation];
  74392. var keys = new Array(inputData.length);
  74393. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  74394. keys[frameIndex] = getNextKey(frameIndex);
  74395. }
  74396. animation.targets = animation.targets || [];
  74397. if (targetPath === "influence") {
  74398. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  74399. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  74400. var morphTarget = morphTargetManager.getTarget(targetIndex);
  74401. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  74402. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  74403. babylonAnimation.setKeys(keys.map(function (key) { return ({
  74404. frame: key.frame,
  74405. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  74406. value: key.value[targetIndex],
  74407. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  74408. }); }));
  74409. morphTarget.animations.push(babylonAnimation);
  74410. animation.targets.push(morphTarget);
  74411. }
  74412. }
  74413. else {
  74414. var animationName = animation.name || "anim" + animationIndex;
  74415. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  74416. babylonAnimation.setKeys(keys);
  74417. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  74418. var target = targetNode.babylonAnimationTargets[i];
  74419. target.animations.push(babylonAnimation.clone());
  74420. animation.targets.push(target);
  74421. }
  74422. }
  74423. };
  74424. this._loadAccessorAsync(this._gltf.accessors[sampler.input], function (data) {
  74425. inputData = data;
  74426. checkSuccess();
  74427. });
  74428. this._loadAccessorAsync(this._gltf.accessors[sampler.output], function (data) {
  74429. outputData = data;
  74430. checkSuccess();
  74431. });
  74432. };
  74433. GLTFLoader.prototype._loadBufferAsync = function (index, onSuccess) {
  74434. var _this = this;
  74435. var buffer = this._gltf.buffers[index];
  74436. this.addPendingData(buffer);
  74437. if (buffer.loadedData) {
  74438. setTimeout(function () {
  74439. onSuccess(buffer.loadedData);
  74440. _this.removePendingData(buffer);
  74441. });
  74442. }
  74443. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  74444. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  74445. buffer.loadedData = new Uint8Array(data);
  74446. setTimeout(function () {
  74447. onSuccess(buffer.loadedData);
  74448. _this.removePendingData(buffer);
  74449. });
  74450. }
  74451. else if (buffer.loadedObservable) {
  74452. buffer.loadedObservable.add(function (buffer) {
  74453. onSuccess(buffer.loadedData);
  74454. _this.removePendingData(buffer);
  74455. });
  74456. }
  74457. else {
  74458. buffer.loadedObservable = new BABYLON.Observable();
  74459. buffer.loadedObservable.add(function (buffer) {
  74460. onSuccess(buffer.loadedData);
  74461. _this.removePendingData(buffer);
  74462. });
  74463. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  74464. buffer.loadedData = new Uint8Array(data);
  74465. buffer.loadedObservable.notifyObservers(buffer);
  74466. buffer.loadedObservable = null;
  74467. }, function (event) {
  74468. if (!_this._disposed) {
  74469. _this._onProgress(event);
  74470. }
  74471. }, this._babylonScene.database, true, function (request) {
  74472. if (!_this._disposed) {
  74473. _this._onError("Failed to load file '" + buffer.uri + "': " + request.status + " " + request.statusText);
  74474. _this.removePendingData(buffer);
  74475. }
  74476. });
  74477. }
  74478. };
  74479. GLTFLoader.prototype._buildInt8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  74480. if (!byteStride) {
  74481. return new Int8Array(buffer, byteOffset, byteLength);
  74482. }
  74483. var sourceBuffer = new Int8Array(buffer, byteOffset);
  74484. var targetBuffer = new Int8Array(byteLength);
  74485. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  74486. return targetBuffer;
  74487. };
  74488. GLTFLoader.prototype._buildUint8ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  74489. if (!byteStride) {
  74490. return new Uint8Array(buffer, byteOffset, byteLength);
  74491. }
  74492. var sourceBuffer = new Uint8Array(buffer, byteOffset);
  74493. var targetBuffer = new Uint8Array(byteLength);
  74494. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride, targetBuffer.length);
  74495. return targetBuffer;
  74496. };
  74497. GLTFLoader.prototype._buildInt16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  74498. if (!byteStride) {
  74499. return new Int16Array(buffer, byteOffset, byteLength);
  74500. }
  74501. var sourceBuffer = new Int16Array(buffer, byteOffset);
  74502. var targetBuffer = new Int16Array(byteLength);
  74503. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  74504. return targetBuffer;
  74505. };
  74506. GLTFLoader.prototype._buildUint16ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  74507. if (!byteStride) {
  74508. return new Uint16Array(buffer, byteOffset, byteLength);
  74509. }
  74510. var sourceBuffer = new Uint16Array(buffer, byteOffset);
  74511. var targetBuffer = new Uint16Array(byteLength);
  74512. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 2, targetBuffer.length);
  74513. return targetBuffer;
  74514. };
  74515. GLTFLoader.prototype._buildUint32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  74516. if (!byteStride) {
  74517. return new Uint32Array(buffer, byteOffset, byteLength);
  74518. }
  74519. var sourceBuffer = new Uint32Array(buffer, byteOffset);
  74520. var targetBuffer = new Uint32Array(byteLength);
  74521. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  74522. return targetBuffer;
  74523. };
  74524. GLTFLoader.prototype._buildFloat32ArrayBuffer = function (buffer, byteOffset, byteLength, byteStride, bytePerComponent) {
  74525. if (!byteStride) {
  74526. return new Float32Array(buffer, byteOffset, byteLength);
  74527. }
  74528. var sourceBuffer = new Float32Array(buffer, byteOffset);
  74529. var targetBuffer = new Float32Array(byteLength);
  74530. this._extractInterleavedData(sourceBuffer, targetBuffer, bytePerComponent, byteStride / 4, targetBuffer.length);
  74531. return targetBuffer;
  74532. };
  74533. GLTFLoader.prototype._extractInterleavedData = function (sourceBuffer, targetBuffer, bytePerComponent, stride, length) {
  74534. var tempIndex = 0;
  74535. var sourceIndex = 0;
  74536. var storageSize = bytePerComponent;
  74537. while (tempIndex < length) {
  74538. for (var cursor = 0; cursor < storageSize; cursor++) {
  74539. targetBuffer[tempIndex] = sourceBuffer[sourceIndex + cursor];
  74540. tempIndex++;
  74541. }
  74542. sourceIndex += stride;
  74543. }
  74544. };
  74545. GLTFLoader.prototype._loadBufferViewAsync = function (bufferView, byteOffset, byteLength, bytePerComponent, componentType, onSuccess) {
  74546. var _this = this;
  74547. byteOffset += (bufferView.byteOffset || 0);
  74548. this._loadBufferAsync(bufferView.buffer, function (bufferData) {
  74549. if (byteOffset + byteLength > bufferData.byteLength) {
  74550. _this._onError("Buffer access is out of range");
  74551. return;
  74552. }
  74553. var buffer = bufferData.buffer;
  74554. byteOffset += bufferData.byteOffset;
  74555. var bufferViewData;
  74556. switch (componentType) {
  74557. case GLTF2.EComponentType.BYTE:
  74558. bufferViewData = _this._buildInt8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  74559. break;
  74560. case GLTF2.EComponentType.UNSIGNED_BYTE:
  74561. bufferViewData = _this._buildUint8ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  74562. break;
  74563. case GLTF2.EComponentType.SHORT:
  74564. bufferViewData = _this._buildInt16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  74565. break;
  74566. case GLTF2.EComponentType.UNSIGNED_SHORT:
  74567. bufferViewData = _this._buildUint16ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  74568. break;
  74569. case GLTF2.EComponentType.UNSIGNED_INT:
  74570. bufferViewData = _this._buildUint32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  74571. break;
  74572. case GLTF2.EComponentType.FLOAT:
  74573. bufferViewData = _this._buildFloat32ArrayBuffer(buffer, byteOffset, byteLength, bufferView.byteStride, bytePerComponent);
  74574. break;
  74575. default:
  74576. _this._onError("Invalid component type (" + componentType + ")");
  74577. return;
  74578. }
  74579. onSuccess(bufferViewData);
  74580. });
  74581. };
  74582. GLTFLoader.prototype._loadAccessorAsync = function (accessor, onSuccess) {
  74583. var bufferView = this._gltf.bufferViews[accessor.bufferView];
  74584. var byteOffset = accessor.byteOffset || 0;
  74585. var bytePerComponent = this._getByteStrideFromType(accessor);
  74586. var byteLength = accessor.count * bytePerComponent;
  74587. this._loadBufferViewAsync(bufferView, byteOffset, byteLength, bytePerComponent, accessor.componentType, onSuccess);
  74588. };
  74589. GLTFLoader.prototype._getByteStrideFromType = function (accessor) {
  74590. switch (accessor.type) {
  74591. case "SCALAR": return 1;
  74592. case "VEC2": return 2;
  74593. case "VEC3": return 3;
  74594. case "VEC4": return 4;
  74595. case "MAT2": return 4;
  74596. case "MAT3": return 9;
  74597. case "MAT4": return 16;
  74598. default:
  74599. this._onError("Invalid accessor type (" + accessor.type + ")");
  74600. return 0;
  74601. }
  74602. };
  74603. Object.defineProperty(GLTFLoader.prototype, "blockPendingTracking", {
  74604. set: function (value) {
  74605. this._blockPendingTracking = value;
  74606. },
  74607. enumerable: true,
  74608. configurable: true
  74609. });
  74610. GLTFLoader.prototype.addPendingData = function (data) {
  74611. if (!this._renderReady) {
  74612. this._renderPendingCount++;
  74613. }
  74614. this.addLoaderPendingData(data);
  74615. };
  74616. GLTFLoader.prototype.removePendingData = function (data) {
  74617. if (!this._renderReady) {
  74618. if (--this._renderPendingCount === 0) {
  74619. this._renderReady = true;
  74620. this._onRenderReady();
  74621. }
  74622. }
  74623. this.removeLoaderPendingData(data);
  74624. };
  74625. GLTFLoader.prototype.addLoaderNonBlockingPendingData = function (data) {
  74626. if (!this._nonBlockingData) {
  74627. this._nonBlockingData = new Array();
  74628. }
  74629. this._nonBlockingData.push(data);
  74630. };
  74631. GLTFLoader.prototype.addLoaderPendingData = function (data) {
  74632. if (this._blockPendingTracking) {
  74633. this.addLoaderNonBlockingPendingData(data);
  74634. return;
  74635. }
  74636. this._loaderPendingCount++;
  74637. };
  74638. GLTFLoader.prototype.removeLoaderPendingData = function (data) {
  74639. var indexInPending = this._nonBlockingData ? this._nonBlockingData.indexOf(data) : -1;
  74640. if (indexInPending !== -1) {
  74641. this._nonBlockingData.splice(indexInPending, 1);
  74642. }
  74643. else if (--this._loaderPendingCount === 0) {
  74644. this._onLoaderFirstLODComplete();
  74645. }
  74646. if ((!this._nonBlockingData || this._nonBlockingData.length === 0) && this._loaderPendingCount === 0) {
  74647. this._onLoaderComplete();
  74648. this.dispose();
  74649. }
  74650. };
  74651. GLTFLoader.prototype._getDefaultMaterial = function () {
  74652. if (!this._defaultMaterial) {
  74653. var id = "__gltf_default";
  74654. var material = this._babylonScene.getMaterialByName(id);
  74655. if (!material) {
  74656. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  74657. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74658. material.metallic = 1;
  74659. material.roughness = 1;
  74660. }
  74661. this._defaultMaterial = material;
  74662. }
  74663. return this._defaultMaterial;
  74664. };
  74665. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (material) {
  74666. var babylonMaterial = material.babylonMaterial;
  74667. // Ensure metallic workflow
  74668. babylonMaterial.metallic = 1;
  74669. babylonMaterial.roughness = 1;
  74670. var properties = material.pbrMetallicRoughness;
  74671. if (!properties) {
  74672. return;
  74673. }
  74674. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  74675. babylonMaterial.metallic = properties.metallicFactor === undefined ? 1 : properties.metallicFactor;
  74676. babylonMaterial.roughness = properties.roughnessFactor === undefined ? 1 : properties.roughnessFactor;
  74677. if (properties.baseColorTexture) {
  74678. babylonMaterial.albedoTexture = this.loadTexture(properties.baseColorTexture);
  74679. }
  74680. if (properties.metallicRoughnessTexture) {
  74681. babylonMaterial.metallicTexture = this.loadTexture(properties.metallicRoughnessTexture);
  74682. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  74683. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  74684. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  74685. }
  74686. this.loadMaterialAlphaProperties(material, properties.baseColorFactor);
  74687. };
  74688. GLTFLoader.prototype.loadMaterial = function (material, assign) {
  74689. if (material.babylonMaterial) {
  74690. assign(material.babylonMaterial, false);
  74691. return;
  74692. }
  74693. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, material, assign)) {
  74694. return;
  74695. }
  74696. this.createPbrMaterial(material);
  74697. this.loadMaterialBaseProperties(material);
  74698. this._loadMaterialMetallicRoughnessProperties(material);
  74699. assign(material.babylonMaterial, true);
  74700. };
  74701. GLTFLoader.prototype.createPbrMaterial = function (material) {
  74702. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  74703. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74704. material.babylonMaterial = babylonMaterial;
  74705. };
  74706. GLTFLoader.prototype.loadMaterialBaseProperties = function (material) {
  74707. var babylonMaterial = material.babylonMaterial;
  74708. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  74709. if (material.doubleSided) {
  74710. babylonMaterial.backFaceCulling = false;
  74711. babylonMaterial.twoSidedLighting = true;
  74712. }
  74713. if (material.normalTexture) {
  74714. babylonMaterial.bumpTexture = this.loadTexture(material.normalTexture);
  74715. babylonMaterial.invertNormalMapX = true;
  74716. babylonMaterial.invertNormalMapY = false;
  74717. if (material.normalTexture.scale !== undefined) {
  74718. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  74719. }
  74720. }
  74721. if (material.occlusionTexture) {
  74722. babylonMaterial.ambientTexture = this.loadTexture(material.occlusionTexture);
  74723. babylonMaterial.useAmbientInGrayScale = true;
  74724. if (material.occlusionTexture.strength !== undefined) {
  74725. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  74726. }
  74727. }
  74728. if (material.emissiveTexture) {
  74729. babylonMaterial.emissiveTexture = this.loadTexture(material.emissiveTexture);
  74730. }
  74731. };
  74732. GLTFLoader.prototype.loadMaterialAlphaProperties = function (material, colorFactor) {
  74733. var babylonMaterial = material.babylonMaterial;
  74734. var alphaMode = material.alphaMode || "OPAQUE";
  74735. switch (alphaMode) {
  74736. case "OPAQUE":
  74737. // default is opaque
  74738. break;
  74739. case "MASK":
  74740. case "BLEND":
  74741. if (colorFactor) {
  74742. babylonMaterial.alpha = colorFactor[3];
  74743. }
  74744. if (babylonMaterial.albedoTexture) {
  74745. babylonMaterial.albedoTexture.hasAlpha = true;
  74746. babylonMaterial.useAlphaFromAlbedoTexture = (alphaMode === "BLEND");
  74747. }
  74748. break;
  74749. default:
  74750. BABYLON.Tools.Warn("Invalid alpha mode '" + material.alphaMode + "'");
  74751. break;
  74752. }
  74753. babylonMaterial.alphaCutOff = material.alphaCutoff === undefined ? 0.5 : material.alphaCutoff;
  74754. };
  74755. GLTFLoader.prototype.loadTexture = function (textureInfo) {
  74756. var _this = this;
  74757. var texture = this._gltf.textures[textureInfo.index];
  74758. var texCoord = textureInfo.texCoord || 0;
  74759. if (!texture || texture.source === undefined) {
  74760. return null;
  74761. }
  74762. var source = this._gltf.images[texture.source];
  74763. var sampler = (texture.sampler === undefined ? {} : this._gltf.samplers[texture.sampler]);
  74764. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  74765. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  74766. this.addPendingData(texture);
  74767. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  74768. if (!_this._disposed) {
  74769. _this.removePendingData(texture);
  74770. }
  74771. }, function () {
  74772. if (!_this._disposed) {
  74773. _this._onError("Failed to load texture '" + source.uri + "'");
  74774. _this.removePendingData(texture);
  74775. }
  74776. });
  74777. if (texture.url) {
  74778. babylonTexture.updateURL(texture.url);
  74779. }
  74780. else if (texture.dataReadyObservable) {
  74781. texture.dataReadyObservable.add(function (texture) {
  74782. babylonTexture.updateURL(texture.url);
  74783. });
  74784. }
  74785. else {
  74786. texture.dataReadyObservable = new BABYLON.Observable();
  74787. texture.dataReadyObservable.add(function (texture) {
  74788. babylonTexture.updateURL(texture.url);
  74789. });
  74790. var setTextureData = function (data) {
  74791. texture.url = URL.createObjectURL(new Blob([data], { type: source.mimeType }));
  74792. texture.dataReadyObservable.notifyObservers(texture);
  74793. };
  74794. if (!source.uri) {
  74795. var bufferView = this._gltf.bufferViews[source.bufferView];
  74796. this._loadBufferViewAsync(bufferView, 0, bufferView.byteLength, 1, GLTF2.EComponentType.UNSIGNED_BYTE, setTextureData);
  74797. }
  74798. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  74799. setTextureData(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri)));
  74800. }
  74801. else {
  74802. BABYLON.Tools.LoadFile(this._rootUrl + source.uri, setTextureData, function (event) {
  74803. if (!_this._disposed) {
  74804. _this._onProgress(event);
  74805. }
  74806. }, this._babylonScene.database, true, function (request) {
  74807. _this._onError("Failed to load file '" + source.uri + "': " + request.status + " " + request.statusText);
  74808. });
  74809. }
  74810. }
  74811. babylonTexture.coordinatesIndex = texCoord;
  74812. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  74813. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  74814. babylonTexture.name = texture.name || "texture" + textureInfo.index;
  74815. if (this._parent.onTextureLoaded) {
  74816. this._parent.onTextureLoaded(babylonTexture);
  74817. }
  74818. return babylonTexture;
  74819. };
  74820. GLTFLoader.Extensions = {};
  74821. return GLTFLoader;
  74822. }());
  74823. GLTF2.GLTFLoader = GLTFLoader;
  74824. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  74825. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  74826. })(BABYLON || (BABYLON = {}));
  74827. //# sourceMappingURL=babylon.glTFLoader.js.map
  74828. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74829. var BABYLON;
  74830. (function (BABYLON) {
  74831. var GLTF2;
  74832. (function (GLTF2) {
  74833. /**
  74834. * Utils functions for GLTF
  74835. */
  74836. var GLTFUtils = (function () {
  74837. function GLTFUtils() {
  74838. }
  74839. /**
  74840. * If the uri is a base64 string
  74841. * @param uri: the uri to test
  74842. */
  74843. GLTFUtils.IsBase64 = function (uri) {
  74844. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  74845. };
  74846. /**
  74847. * Decode the base64 uri
  74848. * @param uri: the uri to decode
  74849. */
  74850. GLTFUtils.DecodeBase64 = function (uri) {
  74851. var decodedString = atob(uri.split(",")[1]);
  74852. var bufferLength = decodedString.length;
  74853. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  74854. for (var i = 0; i < bufferLength; i++) {
  74855. bufferView[i] = decodedString.charCodeAt(i);
  74856. }
  74857. return bufferView.buffer;
  74858. };
  74859. GLTFUtils.ForEach = function (view, func) {
  74860. for (var index = 0; index < view.length; index++) {
  74861. func(view[index], index);
  74862. }
  74863. };
  74864. GLTFUtils.GetTextureWrapMode = function (mode) {
  74865. // Set defaults if undefined
  74866. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  74867. switch (mode) {
  74868. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  74869. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  74870. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74871. default:
  74872. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  74873. return BABYLON.Texture.WRAP_ADDRESSMODE;
  74874. }
  74875. };
  74876. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  74877. // Set defaults if undefined
  74878. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  74879. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST : minFilter;
  74880. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  74881. switch (minFilter) {
  74882. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  74883. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  74884. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  74885. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  74886. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  74887. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  74888. default:
  74889. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  74890. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  74891. }
  74892. }
  74893. else {
  74894. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  74895. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  74896. }
  74897. switch (minFilter) {
  74898. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  74899. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  74900. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  74901. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  74902. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  74903. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  74904. default:
  74905. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  74906. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  74907. }
  74908. }
  74909. };
  74910. /**
  74911. * Decodes a buffer view into a string
  74912. * @param view: the buffer view
  74913. */
  74914. GLTFUtils.DecodeBufferToText = function (view) {
  74915. var result = "";
  74916. var length = view.byteLength;
  74917. for (var i = 0; i < length; ++i) {
  74918. result += String.fromCharCode(view[i]);
  74919. }
  74920. return result;
  74921. };
  74922. return GLTFUtils;
  74923. }());
  74924. GLTF2.GLTFUtils = GLTFUtils;
  74925. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  74926. })(BABYLON || (BABYLON = {}));
  74927. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  74928. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74929. var BABYLON;
  74930. (function (BABYLON) {
  74931. var GLTF2;
  74932. (function (GLTF2) {
  74933. var GLTFLoaderExtension = (function () {
  74934. function GLTFLoaderExtension() {
  74935. this.enabled = true;
  74936. }
  74937. GLTFLoaderExtension.prototype.loadMaterial = function (loader, material, assign) { return false; };
  74938. GLTFLoaderExtension.LoadMaterial = function (loader, material, assign) {
  74939. return this._ApplyExtensions(function (extension) { return extension.loadMaterial(loader, material, assign); });
  74940. };
  74941. GLTFLoaderExtension._ApplyExtensions = function (action) {
  74942. var extensions = GLTFLoaderExtension._Extensions;
  74943. if (!extensions) {
  74944. return;
  74945. }
  74946. for (var i = 0; i < extensions.length; i++) {
  74947. var extension = extensions[i];
  74948. if (extension.enabled && action(extension)) {
  74949. return true;
  74950. }
  74951. }
  74952. return false;
  74953. };
  74954. //
  74955. // Utilities
  74956. //
  74957. GLTFLoaderExtension._Extensions = [];
  74958. return GLTFLoaderExtension;
  74959. }());
  74960. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  74961. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  74962. })(BABYLON || (BABYLON = {}));
  74963. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  74964. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  74965. var BABYLON;
  74966. (function (BABYLON) {
  74967. var GLTF2;
  74968. (function (GLTF2) {
  74969. var Extensions;
  74970. (function (Extensions) {
  74971. var MSFTLOD = (function (_super) {
  74972. __extends(MSFTLOD, _super);
  74973. function MSFTLOD() {
  74974. return _super !== null && _super.apply(this, arguments) || this;
  74975. }
  74976. Object.defineProperty(MSFTLOD.prototype, "name", {
  74977. get: function () {
  74978. return "MSFT_lod";
  74979. },
  74980. enumerable: true,
  74981. configurable: true
  74982. });
  74983. MSFTLOD.prototype.loadMaterial = function (loader, material, assign) {
  74984. if (!material.extensions) {
  74985. return false;
  74986. }
  74987. var properties = material.extensions[this.name];
  74988. if (!properties) {
  74989. return false;
  74990. }
  74991. // Clear out the extension so that it won't get loaded again.
  74992. material.extensions[this.name] = undefined;
  74993. // Tell the loader not to clear its state until the highest LOD is loaded.
  74994. var materialLODs = [material.index].concat(properties.ids);
  74995. loader.addLoaderPendingData(material);
  74996. for (var index = 0; index < materialLODs.length; index++) {
  74997. loader.addLoaderNonBlockingPendingData(index);
  74998. }
  74999. // Start with the lowest quality LOD.
  75000. this.loadMaterialLOD(loader, material, materialLODs, materialLODs.length - 1, assign);
  75001. return true;
  75002. };
  75003. MSFTLOD.prototype.loadMaterialLOD = function (loader, material, materialLODs, lod, assign) {
  75004. var _this = this;
  75005. var materialLOD = loader.gltf.materials[materialLODs[lod]];
  75006. if (lod !== materialLODs.length - 1) {
  75007. loader.blockPendingTracking = true;
  75008. }
  75009. loader.loadMaterial(materialLOD, function (babylonMaterial, isNew) {
  75010. assign(babylonMaterial, isNew);
  75011. loader.removeLoaderPendingData(lod);
  75012. // Loading is considered complete if this is the lowest quality LOD.
  75013. if (lod === materialLODs.length - 1) {
  75014. loader.removeLoaderPendingData(material);
  75015. }
  75016. if (lod === 0) {
  75017. loader.blockPendingTracking = false;
  75018. return;
  75019. }
  75020. // Load the next LOD when the loader is ready to render and
  75021. // all active material textures of the current LOD are loaded.
  75022. loader.executeWhenRenderReady(function () {
  75023. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  75024. setTimeout(function () {
  75025. _this.loadMaterialLOD(loader, material, materialLODs, lod - 1, assign);
  75026. }, MSFTLOD.MinimalLODDelay);
  75027. });
  75028. });
  75029. });
  75030. };
  75031. /**
  75032. * Specify the minimal delay between LODs in ms (default = 250)
  75033. */
  75034. MSFTLOD.MinimalLODDelay = 250;
  75035. return MSFTLOD;
  75036. }(GLTF2.GLTFLoaderExtension));
  75037. Extensions.MSFTLOD = MSFTLOD;
  75038. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  75039. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  75040. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75041. })(BABYLON || (BABYLON = {}));
  75042. //# sourceMappingURL=MSFT_lod.js.map
  75043. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  75044. var BABYLON;
  75045. (function (BABYLON) {
  75046. var GLTF2;
  75047. (function (GLTF2) {
  75048. var Extensions;
  75049. (function (Extensions) {
  75050. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  75051. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  75052. function KHRMaterialsPbrSpecularGlossiness() {
  75053. return _super !== null && _super.apply(this, arguments) || this;
  75054. }
  75055. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  75056. get: function () {
  75057. return "KHR_materials_pbrSpecularGlossiness";
  75058. },
  75059. enumerable: true,
  75060. configurable: true
  75061. });
  75062. KHRMaterialsPbrSpecularGlossiness.prototype.loadMaterial = function (loader, material, assign) {
  75063. if (!material.extensions) {
  75064. return false;
  75065. }
  75066. var properties = material.extensions[this.name];
  75067. if (!properties) {
  75068. return false;
  75069. }
  75070. loader.createPbrMaterial(material);
  75071. loader.loadMaterialBaseProperties(material);
  75072. this._loadSpecularGlossinessProperties(loader, material, properties);
  75073. assign(material.babylonMaterial, true);
  75074. return true;
  75075. };
  75076. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, material, properties) {
  75077. var babylonMaterial = material.babylonMaterial;
  75078. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  75079. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  75080. babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  75081. if (properties.diffuseTexture) {
  75082. babylonMaterial.albedoTexture = loader.loadTexture(properties.diffuseTexture);
  75083. }
  75084. if (properties.specularGlossinessTexture) {
  75085. babylonMaterial.reflectivityTexture = loader.loadTexture(properties.specularGlossinessTexture);
  75086. babylonMaterial.reflectivityTexture.hasAlpha = true;
  75087. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  75088. }
  75089. loader.loadMaterialAlphaProperties(material, properties.diffuseFactor);
  75090. };
  75091. return KHRMaterialsPbrSpecularGlossiness;
  75092. }(GLTF2.GLTFLoaderExtension));
  75093. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  75094. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  75095. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  75096. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75097. })(BABYLON || (BABYLON = {}));
  75098. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  75099. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  75100. module.exports = BABYLON;
  75101. };