babylon.max.js 3.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286
  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, scope) {
  5321. if (scope === void 0) { scope = null; }
  5322. this.callback = callback;
  5323. this.mask = mask;
  5324. this.scope = scope;
  5325. }
  5326. return Observer;
  5327. }());
  5328. BABYLON.Observer = Observer;
  5329. /**
  5330. * The Observable class is a simple implementation of the Observable pattern.
  5331. * 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.
  5332. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5333. * 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).
  5334. * 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.
  5335. */
  5336. var Observable = (function () {
  5337. function Observable(onObserverAdded) {
  5338. this._observers = new Array();
  5339. this._eventState = new EventState(0);
  5340. this._onObserverAdded = onObserverAdded;
  5341. }
  5342. /**
  5343. * Create a new Observer with the specified callback
  5344. * @param callback the callback that will be executed for that Observer
  5345. * @param mask the mask used to filter observers
  5346. * @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.
  5347. * @param scope optional scope for the callback to be called from
  5348. */
  5349. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5350. if (mask === void 0) { mask = -1; }
  5351. if (insertFirst === void 0) { insertFirst = false; }
  5352. if (scope === void 0) { scope = null; }
  5353. if (!callback) {
  5354. return null;
  5355. }
  5356. var observer = new Observer(callback, mask, scope);
  5357. if (insertFirst) {
  5358. this._observers.unshift(observer);
  5359. }
  5360. else {
  5361. this._observers.push(observer);
  5362. }
  5363. if (this._onObserverAdded) {
  5364. this._onObserverAdded(observer);
  5365. }
  5366. return observer;
  5367. };
  5368. /**
  5369. * Remove an Observer from the Observable object
  5370. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5371. */
  5372. Observable.prototype.remove = function (observer) {
  5373. var index = this._observers.indexOf(observer);
  5374. if (index !== -1) {
  5375. this._observers.splice(index, 1);
  5376. return true;
  5377. }
  5378. return false;
  5379. };
  5380. /**
  5381. * Remove a callback from the Observable object
  5382. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5383. */
  5384. Observable.prototype.removeCallback = function (callback) {
  5385. for (var index = 0; index < this._observers.length; index++) {
  5386. if (this._observers[index].callback === callback) {
  5387. this._observers.splice(index, 1);
  5388. return true;
  5389. }
  5390. }
  5391. return false;
  5392. };
  5393. /**
  5394. * Notify all Observers by calling their respective callback with the given data
  5395. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5396. * @param eventData
  5397. * @param mask
  5398. */
  5399. Observable.prototype.notifyObservers = function (eventData, mask) {
  5400. if (mask === void 0) { mask = -1; }
  5401. var state = this._eventState;
  5402. state.mask = mask;
  5403. state.skipNextObservers = false;
  5404. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5405. var obs = _a[_i];
  5406. if (obs.mask & mask) {
  5407. if (obs.scope) {
  5408. obs.callback.apply(obs.scope, [eventData, state]);
  5409. }
  5410. else {
  5411. obs.callback(eventData, state);
  5412. }
  5413. }
  5414. if (state.skipNextObservers) {
  5415. return false;
  5416. }
  5417. }
  5418. return true;
  5419. };
  5420. /**
  5421. * Notify a specific observer
  5422. * @param eventData
  5423. * @param mask
  5424. */
  5425. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5426. if (mask === void 0) { mask = -1; }
  5427. var state = this._eventState;
  5428. state.mask = mask;
  5429. state.skipNextObservers = false;
  5430. observer.callback(eventData, state);
  5431. };
  5432. /**
  5433. * return true is the Observable has at least one Observer registered
  5434. */
  5435. Observable.prototype.hasObservers = function () {
  5436. return this._observers.length > 0;
  5437. };
  5438. /**
  5439. * Clear the list of observers
  5440. */
  5441. Observable.prototype.clear = function () {
  5442. this._observers = new Array();
  5443. this._onObserverAdded = null;
  5444. };
  5445. /**
  5446. * Clone the current observable
  5447. */
  5448. Observable.prototype.clone = function () {
  5449. var result = new Observable();
  5450. result._observers = this._observers.slice(0);
  5451. return result;
  5452. };
  5453. /**
  5454. * Does this observable handles observer registered with a given mask
  5455. * @param {number} trigger - the mask to be tested
  5456. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5457. **/
  5458. Observable.prototype.hasSpecificMask = function (mask) {
  5459. if (mask === void 0) { mask = -1; }
  5460. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5461. var obs = _a[_i];
  5462. if (obs.mask & mask || obs.mask === mask) {
  5463. return true;
  5464. }
  5465. }
  5466. return false;
  5467. };
  5468. return Observable;
  5469. }());
  5470. BABYLON.Observable = Observable;
  5471. })(BABYLON || (BABYLON = {}));
  5472. //# sourceMappingURL=babylon.observable.js.map
  5473. var BABYLON;
  5474. (function (BABYLON) {
  5475. var SmartArray = (function () {
  5476. function SmartArray(capacity) {
  5477. this.length = 0;
  5478. this._duplicateId = 0;
  5479. this.data = new Array(capacity);
  5480. this._id = SmartArray._GlobalId++;
  5481. }
  5482. SmartArray.prototype.push = function (value) {
  5483. this.data[this.length++] = value;
  5484. if (this.length > this.data.length) {
  5485. this.data.length *= 2;
  5486. }
  5487. if (!value.__smartArrayFlags) {
  5488. value.__smartArrayFlags = {};
  5489. }
  5490. value.__smartArrayFlags[this._id] = this._duplicateId;
  5491. };
  5492. SmartArray.prototype.forEach = function (func) {
  5493. for (var index = 0; index < this.length; index++) {
  5494. func(this.data[index]);
  5495. }
  5496. };
  5497. SmartArray.prototype.pushNoDuplicate = function (value) {
  5498. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5499. return false;
  5500. }
  5501. this.push(value);
  5502. return true;
  5503. };
  5504. SmartArray.prototype.sort = function (compareFn) {
  5505. this.data.sort(compareFn);
  5506. };
  5507. SmartArray.prototype.reset = function () {
  5508. this.length = 0;
  5509. this._duplicateId++;
  5510. };
  5511. SmartArray.prototype.dispose = function () {
  5512. this.reset();
  5513. if (this.data) {
  5514. this.data.length = 0;
  5515. this.data = null;
  5516. }
  5517. };
  5518. SmartArray.prototype.concat = function (array) {
  5519. if (array.length === 0) {
  5520. return;
  5521. }
  5522. if (this.length + array.length > this.data.length) {
  5523. this.data.length = (this.length + array.length) * 2;
  5524. }
  5525. for (var index = 0; index < array.length; index++) {
  5526. this.data[this.length++] = (array.data || array)[index];
  5527. }
  5528. };
  5529. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5530. if (array.length === 0) {
  5531. return;
  5532. }
  5533. if (this.length + array.length > this.data.length) {
  5534. this.data.length = (this.length + array.length) * 2;
  5535. }
  5536. for (var index = 0; index < array.length; index++) {
  5537. var item = (array.data || array)[index];
  5538. this.pushNoDuplicate(item);
  5539. }
  5540. };
  5541. SmartArray.prototype.indexOf = function (value) {
  5542. var position = this.data.indexOf(value);
  5543. if (position >= this.length) {
  5544. return -1;
  5545. }
  5546. return position;
  5547. };
  5548. SmartArray.prototype.contains = function (value) {
  5549. return this.data.indexOf(value) !== -1;
  5550. };
  5551. // Statics
  5552. SmartArray._GlobalId = 0;
  5553. return SmartArray;
  5554. }());
  5555. BABYLON.SmartArray = SmartArray;
  5556. })(BABYLON || (BABYLON = {}));
  5557. //# sourceMappingURL=babylon.smartArray.js.map
  5558. var BABYLON;
  5559. (function (BABYLON) {
  5560. // Screenshots
  5561. var screenshotCanvas;
  5562. var cloneValue = function (source, destinationObject) {
  5563. if (!source)
  5564. return null;
  5565. if (source instanceof BABYLON.Mesh) {
  5566. return null;
  5567. }
  5568. if (source instanceof BABYLON.SubMesh) {
  5569. return source.clone(destinationObject);
  5570. }
  5571. else if (source.clone) {
  5572. return source.clone();
  5573. }
  5574. return null;
  5575. };
  5576. var Tools = (function () {
  5577. function Tools() {
  5578. }
  5579. ;
  5580. /**
  5581. * Interpolates between a and b via alpha
  5582. * @param a The lower value (returned when alpha = 0)
  5583. * @param b The upper value (returned when alpha = 1)
  5584. * @param alpha The interpolation-factor
  5585. * @return The mixed value
  5586. */
  5587. Tools.Mix = function (a, b, alpha) {
  5588. return a * (1 - alpha) + b * alpha;
  5589. };
  5590. Tools.Instantiate = function (className) {
  5591. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5592. return Tools.RegisteredExternalClasses[className];
  5593. }
  5594. var arr = className.split(".");
  5595. var fn = (window || this);
  5596. for (var i = 0, len = arr.length; i < len; i++) {
  5597. fn = fn[arr[i]];
  5598. }
  5599. if (typeof fn !== "function") {
  5600. return null;
  5601. }
  5602. return fn;
  5603. };
  5604. Tools.SetImmediate = function (action) {
  5605. if (window.setImmediate) {
  5606. window.setImmediate(action);
  5607. }
  5608. else {
  5609. setTimeout(action, 1);
  5610. }
  5611. };
  5612. Tools.IsExponentOfTwo = function (value) {
  5613. var count = 1;
  5614. do {
  5615. count *= 2;
  5616. } while (count < value);
  5617. return count === value;
  5618. };
  5619. /**
  5620. * Find the next highest power of two.
  5621. * @param x Number to start search from.
  5622. * @return Next highest power of two.
  5623. */
  5624. Tools.CeilingPOT = function (x) {
  5625. x--;
  5626. x |= x >> 1;
  5627. x |= x >> 2;
  5628. x |= x >> 4;
  5629. x |= x >> 8;
  5630. x |= x >> 16;
  5631. x++;
  5632. return x;
  5633. };
  5634. /**
  5635. * Find the next lowest power of two.
  5636. * @param x Number to start search from.
  5637. * @return Next lowest power of two.
  5638. */
  5639. Tools.FloorPOT = function (x) {
  5640. x = x | (x >> 1);
  5641. x = x | (x >> 2);
  5642. x = x | (x >> 4);
  5643. x = x | (x >> 8);
  5644. x = x | (x >> 16);
  5645. return x - (x >> 1);
  5646. };
  5647. /**
  5648. * Find the nearest power of two.
  5649. * @param x Number to start search from.
  5650. * @return Next nearest power of two.
  5651. */
  5652. Tools.NearestPOT = function (x) {
  5653. var c = Tools.CeilingPOT(x);
  5654. var f = Tools.FloorPOT(x);
  5655. return (c - x) > (x - f) ? f : c;
  5656. };
  5657. Tools.GetExponentOfTwo = function (value, max, mode) {
  5658. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5659. var pot;
  5660. switch (mode) {
  5661. case BABYLON.Engine.SCALEMODE_FLOOR:
  5662. pot = Tools.FloorPOT(value);
  5663. break;
  5664. case BABYLON.Engine.SCALEMODE_NEAREST:
  5665. pot = Tools.NearestPOT(value);
  5666. break;
  5667. case BABYLON.Engine.SCALEMODE_CEILING:
  5668. pot = Tools.CeilingPOT(value);
  5669. break;
  5670. }
  5671. return Math.min(pot, max);
  5672. };
  5673. Tools.GetFilename = function (path) {
  5674. var index = path.lastIndexOf("/");
  5675. if (index < 0)
  5676. return path;
  5677. return path.substring(index + 1);
  5678. };
  5679. Tools.GetDOMTextContent = function (element) {
  5680. var result = "";
  5681. var child = element.firstChild;
  5682. while (child) {
  5683. if (child.nodeType === 3) {
  5684. result += child.textContent;
  5685. }
  5686. child = child.nextSibling;
  5687. }
  5688. return result;
  5689. };
  5690. Tools.ToDegrees = function (angle) {
  5691. return angle * 180 / Math.PI;
  5692. };
  5693. Tools.ToRadians = function (angle) {
  5694. return angle * Math.PI / 180;
  5695. };
  5696. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5697. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5698. var output = "";
  5699. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5700. var i = 0;
  5701. var bytes = new Uint8Array(buffer);
  5702. while (i < bytes.length) {
  5703. chr1 = bytes[i++];
  5704. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5705. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5706. enc1 = chr1 >> 2;
  5707. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5708. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5709. enc4 = chr3 & 63;
  5710. if (isNaN(chr2)) {
  5711. enc3 = enc4 = 64;
  5712. }
  5713. else if (isNaN(chr3)) {
  5714. enc4 = 64;
  5715. }
  5716. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5717. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5718. }
  5719. return "data:image/png;base64," + output;
  5720. };
  5721. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5722. if (bias === void 0) { bias = null; }
  5723. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5724. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5725. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5726. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5727. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5728. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5729. }
  5730. if (bias) {
  5731. minimum.x -= minimum.x * bias.x + bias.y;
  5732. minimum.y -= minimum.y * bias.x + bias.y;
  5733. minimum.z -= minimum.z * bias.x + bias.y;
  5734. maximum.x += maximum.x * bias.x + bias.y;
  5735. maximum.y += maximum.y * bias.x + bias.y;
  5736. maximum.z += maximum.z * bias.x + bias.y;
  5737. }
  5738. return {
  5739. minimum: minimum,
  5740. maximum: maximum
  5741. };
  5742. };
  5743. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5744. if (bias === void 0) { bias = null; }
  5745. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5746. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5747. if (!stride) {
  5748. stride = 3;
  5749. }
  5750. for (var index = start; index < start + count; index++) {
  5751. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5752. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5753. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5754. }
  5755. if (bias) {
  5756. minimum.x -= minimum.x * bias.x + bias.y;
  5757. minimum.y -= minimum.y * bias.x + bias.y;
  5758. minimum.z -= minimum.z * bias.x + bias.y;
  5759. maximum.x += maximum.x * bias.x + bias.y;
  5760. maximum.y += maximum.y * bias.x + bias.y;
  5761. maximum.z += maximum.z * bias.x + bias.y;
  5762. }
  5763. return {
  5764. minimum: minimum,
  5765. maximum: maximum
  5766. };
  5767. };
  5768. Tools.Vector2ArrayFeeder = function (array) {
  5769. return function (index) {
  5770. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5771. var length = isFloatArray ? array.length / 2 : array.length;
  5772. if (index >= length) {
  5773. return null;
  5774. }
  5775. if (isFloatArray) {
  5776. var fa = array;
  5777. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5778. }
  5779. var a = array;
  5780. return a[index];
  5781. };
  5782. };
  5783. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5784. if (bias === void 0) { bias = null; }
  5785. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5786. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5787. var i = 0;
  5788. var cur = feeder(i++);
  5789. while (cur) {
  5790. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5791. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5792. cur = feeder(i++);
  5793. }
  5794. if (bias) {
  5795. minimum.x -= minimum.x * bias.x + bias.y;
  5796. minimum.y -= minimum.y * bias.x + bias.y;
  5797. maximum.x += maximum.x * bias.x + bias.y;
  5798. maximum.y += maximum.y * bias.x + bias.y;
  5799. }
  5800. return {
  5801. minimum: minimum,
  5802. maximum: maximum
  5803. };
  5804. };
  5805. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5806. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5807. return undefined;
  5808. return Array.isArray(obj) ? obj : [obj];
  5809. };
  5810. // Misc.
  5811. Tools.GetPointerPrefix = function () {
  5812. var eventPrefix = "pointer";
  5813. // Check if pointer events are supported
  5814. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5815. eventPrefix = "mouse";
  5816. }
  5817. return eventPrefix;
  5818. };
  5819. /**
  5820. * @param func - the function to be called
  5821. * @param requester - the object that will request the next frame. Falls back to window.
  5822. */
  5823. Tools.QueueNewFrame = function (func, requester) {
  5824. if (requester === void 0) { requester = window; }
  5825. if (requester.requestAnimationFrame) {
  5826. return requester.requestAnimationFrame(func);
  5827. }
  5828. else if (requester.msRequestAnimationFrame) {
  5829. return requester.msRequestAnimationFrame(func);
  5830. }
  5831. else if (requester.webkitRequestAnimationFrame) {
  5832. return requester.webkitRequestAnimationFrame(func);
  5833. }
  5834. else if (requester.mozRequestAnimationFrame) {
  5835. return requester.mozRequestAnimationFrame(func);
  5836. }
  5837. else if (requester.oRequestAnimationFrame) {
  5838. return requester.oRequestAnimationFrame(func);
  5839. }
  5840. else {
  5841. return window.setTimeout(func, 16);
  5842. }
  5843. };
  5844. Tools.RequestFullscreen = function (element) {
  5845. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5846. if (!requestFunction)
  5847. return;
  5848. requestFunction.call(element);
  5849. };
  5850. Tools.ExitFullscreen = function () {
  5851. if (document.exitFullscreen) {
  5852. document.exitFullscreen();
  5853. }
  5854. else if (document.mozCancelFullScreen) {
  5855. document.mozCancelFullScreen();
  5856. }
  5857. else if (document.webkitCancelFullScreen) {
  5858. document.webkitCancelFullScreen();
  5859. }
  5860. else if (document.msCancelFullScreen) {
  5861. document.msCancelFullScreen();
  5862. }
  5863. };
  5864. Tools.SetCorsBehavior = function (url, img) {
  5865. if (Tools.CorsBehavior) {
  5866. switch (typeof (Tools.CorsBehavior)) {
  5867. case "function":
  5868. var result = Tools.CorsBehavior(url);
  5869. if (result) {
  5870. img.crossOrigin = result;
  5871. }
  5872. break;
  5873. case "string":
  5874. default:
  5875. img.crossOrigin = Tools.CorsBehavior;
  5876. break;
  5877. }
  5878. }
  5879. };
  5880. // External files
  5881. Tools.CleanUrl = function (url) {
  5882. url = url.replace(/#/mg, "%23");
  5883. return url;
  5884. };
  5885. Tools.LoadImage = function (url, onLoad, onError, database) {
  5886. if (url instanceof ArrayBuffer) {
  5887. url = Tools.EncodeArrayBufferTobase64(url);
  5888. }
  5889. url = Tools.CleanUrl(url);
  5890. url = Tools.PreprocessUrl(url);
  5891. var img = new Image();
  5892. if (url.substr(0, 5) !== "data:") {
  5893. Tools.SetCorsBehavior(url, img);
  5894. }
  5895. img.onload = function () {
  5896. onLoad(img);
  5897. };
  5898. img.onerror = function (err) {
  5899. Tools.Error("Error while trying to load image: " + url);
  5900. if (Tools.UseFallbackTexture) {
  5901. img.src = Tools.fallbackTexture;
  5902. onLoad(img);
  5903. }
  5904. else {
  5905. onError("Error while trying to load image: " + url, err);
  5906. }
  5907. };
  5908. var noIndexedDB = function () {
  5909. img.src = url;
  5910. };
  5911. var loadFromIndexedDB = function () {
  5912. database.loadImageFromDB(url, img);
  5913. };
  5914. //ANY database to do!
  5915. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5916. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5917. }
  5918. else {
  5919. if (url.indexOf("file:") !== 0) {
  5920. noIndexedDB();
  5921. }
  5922. else {
  5923. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5924. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5925. try {
  5926. var blobURL;
  5927. try {
  5928. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5929. }
  5930. catch (ex) {
  5931. // Chrome doesn't support oneTimeOnly parameter
  5932. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5933. }
  5934. img.src = blobURL;
  5935. }
  5936. catch (e) {
  5937. img.src = null;
  5938. }
  5939. }
  5940. else {
  5941. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5942. img.src = Tools.fallbackTexture;
  5943. }
  5944. }
  5945. }
  5946. return img;
  5947. };
  5948. //ANY
  5949. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5950. url = Tools.CleanUrl(url);
  5951. url = Tools.PreprocessUrl(url);
  5952. var noIndexedDB = function () {
  5953. var request = new XMLHttpRequest();
  5954. var loadUrl = Tools.BaseUrl + url;
  5955. request.open('GET', loadUrl, true);
  5956. if (useArrayBuffer) {
  5957. request.responseType = "arraybuffer";
  5958. }
  5959. request.onprogress = progressCallBack;
  5960. request.onreadystatechange = function () {
  5961. // In case of undefined state in some browsers.
  5962. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5963. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5964. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5965. callback(!useArrayBuffer ? request.responseText : request.response);
  5966. }
  5967. else {
  5968. var e = new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5969. if (onError) {
  5970. onError(request, e);
  5971. }
  5972. else {
  5973. throw e;
  5974. }
  5975. }
  5976. }
  5977. };
  5978. request.send(null);
  5979. };
  5980. var loadFromIndexedDB = function () {
  5981. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5982. };
  5983. if (url.indexOf("file:") !== -1) {
  5984. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5985. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5986. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5987. }
  5988. else {
  5989. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  5990. if (onError) {
  5991. var e = new Error(errorMessage);
  5992. onError(undefined, e);
  5993. }
  5994. else {
  5995. Tools.Error(errorMessage);
  5996. }
  5997. }
  5998. }
  5999. else {
  6000. // Caching all files
  6001. if (database && database.enableSceneOffline) {
  6002. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6003. }
  6004. else {
  6005. noIndexedDB();
  6006. }
  6007. }
  6008. };
  6009. /**
  6010. * Load a script (identified by an url). When the url returns, the
  6011. * content of this file is added into a new script element, attached to the DOM (body element)
  6012. */
  6013. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6014. var head = document.getElementsByTagName('head')[0];
  6015. var script = document.createElement('script');
  6016. script.type = 'text/javascript';
  6017. script.src = scriptUrl;
  6018. var self = this;
  6019. script.onload = function () {
  6020. if (onSuccess) {
  6021. onSuccess();
  6022. }
  6023. };
  6024. script.onerror = function (e) {
  6025. if (onError) {
  6026. onError("Unable to load script", e);
  6027. }
  6028. };
  6029. head.appendChild(script);
  6030. };
  6031. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6032. var reader = new FileReader();
  6033. reader.onload = function (e) {
  6034. //target doesn't have result from ts 1.3
  6035. callback(e.target['result']);
  6036. };
  6037. reader.onprogress = progressCallback;
  6038. reader.readAsDataURL(fileToLoad);
  6039. };
  6040. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6041. var reader = new FileReader();
  6042. reader.onerror = function (e) {
  6043. Tools.Log("Error while reading file: " + fileToLoad.name);
  6044. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6045. };
  6046. reader.onload = function (e) {
  6047. //target doesn't have result from ts 1.3
  6048. callback(e.target['result']);
  6049. };
  6050. reader.onprogress = progressCallBack;
  6051. if (!useArrayBuffer) {
  6052. // Asynchronous read
  6053. reader.readAsText(fileToLoad);
  6054. }
  6055. else {
  6056. reader.readAsArrayBuffer(fileToLoad);
  6057. }
  6058. };
  6059. //returns a downloadable url to a file content.
  6060. Tools.FileAsURL = function (content) {
  6061. var fileBlob = new Blob([content]);
  6062. var url = window.URL || window.webkitURL;
  6063. var link = url.createObjectURL(fileBlob);
  6064. return link;
  6065. };
  6066. // Misc.
  6067. Tools.Format = function (value, decimals) {
  6068. if (decimals === void 0) { decimals = 2; }
  6069. return value.toFixed(decimals);
  6070. };
  6071. Tools.CheckExtends = function (v, min, max) {
  6072. if (v.x < min.x)
  6073. min.x = v.x;
  6074. if (v.y < min.y)
  6075. min.y = v.y;
  6076. if (v.z < min.z)
  6077. min.z = v.z;
  6078. if (v.x > max.x)
  6079. max.x = v.x;
  6080. if (v.y > max.y)
  6081. max.y = v.y;
  6082. if (v.z > max.z)
  6083. max.z = v.z;
  6084. };
  6085. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6086. for (var prop in source) {
  6087. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6088. continue;
  6089. }
  6090. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6091. continue;
  6092. }
  6093. var sourceValue = source[prop];
  6094. var typeOfSourceValue = typeof sourceValue;
  6095. if (typeOfSourceValue === "function") {
  6096. continue;
  6097. }
  6098. if (typeOfSourceValue === "object") {
  6099. if (sourceValue instanceof Array) {
  6100. destination[prop] = [];
  6101. if (sourceValue.length > 0) {
  6102. if (typeof sourceValue[0] == "object") {
  6103. for (var index = 0; index < sourceValue.length; index++) {
  6104. var clonedValue = cloneValue(sourceValue[index], destination);
  6105. if (destination[prop].indexOf(clonedValue) === -1) {
  6106. destination[prop].push(clonedValue);
  6107. }
  6108. }
  6109. }
  6110. else {
  6111. destination[prop] = sourceValue.slice(0);
  6112. }
  6113. }
  6114. }
  6115. else {
  6116. destination[prop] = cloneValue(sourceValue, destination);
  6117. }
  6118. }
  6119. else {
  6120. destination[prop] = sourceValue;
  6121. }
  6122. }
  6123. };
  6124. Tools.IsEmpty = function (obj) {
  6125. for (var i in obj) {
  6126. return false;
  6127. }
  6128. return true;
  6129. };
  6130. Tools.RegisterTopRootEvents = function (events) {
  6131. for (var index = 0; index < events.length; index++) {
  6132. var event = events[index];
  6133. window.addEventListener(event.name, event.handler, false);
  6134. try {
  6135. if (window.parent) {
  6136. window.parent.addEventListener(event.name, event.handler, false);
  6137. }
  6138. }
  6139. catch (e) {
  6140. // Silently fails...
  6141. }
  6142. }
  6143. };
  6144. Tools.UnregisterTopRootEvents = function (events) {
  6145. for (var index = 0; index < events.length; index++) {
  6146. var event = events[index];
  6147. window.removeEventListener(event.name, event.handler);
  6148. try {
  6149. if (window.parent) {
  6150. window.parent.removeEventListener(event.name, event.handler);
  6151. }
  6152. }
  6153. catch (e) {
  6154. // Silently fails...
  6155. }
  6156. }
  6157. };
  6158. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6159. if (mimeType === void 0) { mimeType = "image/png"; }
  6160. // Read the contents of the framebuffer
  6161. var numberOfChannelsByLine = width * 4;
  6162. var halfHeight = height / 2;
  6163. //Reading datas from WebGL
  6164. var data = engine.readPixels(0, 0, width, height);
  6165. //To flip image on Y axis.
  6166. for (var i = 0; i < halfHeight; i++) {
  6167. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6168. var currentCell = j + i * numberOfChannelsByLine;
  6169. var targetLine = height - i - 1;
  6170. var targetCell = j + targetLine * numberOfChannelsByLine;
  6171. var temp = data[currentCell];
  6172. data[currentCell] = data[targetCell];
  6173. data[targetCell] = temp;
  6174. }
  6175. }
  6176. // Create a 2D canvas to store the result
  6177. if (!screenshotCanvas) {
  6178. screenshotCanvas = document.createElement('canvas');
  6179. }
  6180. screenshotCanvas.width = width;
  6181. screenshotCanvas.height = height;
  6182. var context = screenshotCanvas.getContext('2d');
  6183. // Copy the pixels to a 2D canvas
  6184. var imageData = context.createImageData(width, height);
  6185. var castData = (imageData.data);
  6186. castData.set(data);
  6187. context.putImageData(imageData, 0, 0);
  6188. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6189. };
  6190. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6191. if (mimeType === void 0) { mimeType = "image/png"; }
  6192. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6193. if (successCallback) {
  6194. successCallback(base64Image);
  6195. }
  6196. else {
  6197. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6198. if (("download" in document.createElement("a"))) {
  6199. var a = window.document.createElement("a");
  6200. a.href = base64Image;
  6201. var date = new Date();
  6202. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6203. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6204. window.document.body.appendChild(a);
  6205. a.addEventListener("click", function () {
  6206. a.parentElement.removeChild(a);
  6207. });
  6208. a.click();
  6209. //Or opening a new tab with the image if it is not possible to automatically start download.
  6210. }
  6211. else {
  6212. var newWindow = window.open("");
  6213. var img = newWindow.document.createElement("img");
  6214. img.src = base64Image;
  6215. newWindow.document.body.appendChild(img);
  6216. }
  6217. }
  6218. };
  6219. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6220. if (mimeType === void 0) { mimeType = "image/png"; }
  6221. var width;
  6222. var height;
  6223. // If a precision value is specified
  6224. if (size.precision) {
  6225. width = Math.round(engine.getRenderWidth() * size.precision);
  6226. height = Math.round(width / engine.getAspectRatio(camera));
  6227. }
  6228. else if (size.width && size.height) {
  6229. width = size.width;
  6230. height = size.height;
  6231. }
  6232. else if (size.width && !size.height) {
  6233. width = size.width;
  6234. height = Math.round(width / engine.getAspectRatio(camera));
  6235. }
  6236. else if (size.height && !size.width) {
  6237. height = size.height;
  6238. width = Math.round(height * engine.getAspectRatio(camera));
  6239. }
  6240. else if (!isNaN(size)) {
  6241. height = size;
  6242. width = size;
  6243. }
  6244. else {
  6245. Tools.Error("Invalid 'size' parameter !");
  6246. return;
  6247. }
  6248. if (!screenshotCanvas) {
  6249. screenshotCanvas = document.createElement('canvas');
  6250. }
  6251. screenshotCanvas.width = width;
  6252. screenshotCanvas.height = height;
  6253. var renderContext = screenshotCanvas.getContext("2d");
  6254. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6255. var newWidth = width;
  6256. var newHeight = newWidth / ratio;
  6257. if (newHeight > height) {
  6258. newHeight = height;
  6259. newWidth = newHeight * ratio;
  6260. }
  6261. var offsetX = Math.max(0, width - newWidth) / 2;
  6262. var offsetY = Math.max(0, height - newHeight) / 2;
  6263. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6264. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6265. };
  6266. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6267. if (mimeType === void 0) { mimeType = "image/png"; }
  6268. if (samples === void 0) { samples = 1; }
  6269. var width;
  6270. var height;
  6271. //If a precision value is specified
  6272. if (size.precision) {
  6273. width = Math.round(engine.getRenderWidth() * size.precision);
  6274. height = Math.round(width / engine.getAspectRatio(camera));
  6275. size = { width: width, height: height };
  6276. }
  6277. else if (size.width && size.height) {
  6278. width = size.width;
  6279. height = size.height;
  6280. }
  6281. else if (size.width && !size.height) {
  6282. width = size.width;
  6283. height = Math.round(width / engine.getAspectRatio(camera));
  6284. size = { width: width, height: height };
  6285. }
  6286. else if (size.height && !size.width) {
  6287. height = size.height;
  6288. width = Math.round(height * engine.getAspectRatio(camera));
  6289. size = { width: width, height: height };
  6290. }
  6291. else if (!isNaN(size)) {
  6292. height = size;
  6293. width = size;
  6294. }
  6295. else {
  6296. Tools.Error("Invalid 'size' parameter !");
  6297. return;
  6298. }
  6299. var scene = camera.getScene();
  6300. var previousCamera = null;
  6301. if (scene.activeCamera !== camera) {
  6302. previousCamera = scene.activeCamera;
  6303. scene.activeCamera = camera;
  6304. }
  6305. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6306. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6307. texture.renderList = null;
  6308. texture.samples = samples;
  6309. texture.onAfterRenderObservable.add(function () {
  6310. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6311. });
  6312. scene.incrementRenderId();
  6313. scene.resetCachedMaterial();
  6314. texture.render(true);
  6315. texture.dispose();
  6316. if (previousCamera) {
  6317. scene.activeCamera = previousCamera;
  6318. }
  6319. camera.getProjectionMatrix(true); // Force cache refresh;
  6320. };
  6321. // XHR response validator for local file scenario
  6322. Tools.ValidateXHRData = function (xhr, dataType) {
  6323. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6324. if (dataType === void 0) { dataType = 7; }
  6325. try {
  6326. if (dataType & 1) {
  6327. if (xhr.responseText && xhr.responseText.length > 0) {
  6328. return true;
  6329. }
  6330. else if (dataType === 1) {
  6331. return false;
  6332. }
  6333. }
  6334. if (dataType & 2) {
  6335. // Check header width and height since there is no "TGA" magic number
  6336. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6337. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6338. return true;
  6339. }
  6340. else if (dataType === 2) {
  6341. return false;
  6342. }
  6343. }
  6344. if (dataType & 4) {
  6345. // Check for the "DDS" magic number
  6346. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6347. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6348. return true;
  6349. }
  6350. else {
  6351. return false;
  6352. }
  6353. }
  6354. }
  6355. catch (e) {
  6356. // Global protection
  6357. }
  6358. return false;
  6359. };
  6360. /**
  6361. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6362. * Be aware Math.random() could cause collisions, but:
  6363. * "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"
  6364. */
  6365. Tools.RandomId = function () {
  6366. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6367. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6368. return v.toString(16);
  6369. });
  6370. };
  6371. Object.defineProperty(Tools, "NoneLogLevel", {
  6372. get: function () {
  6373. return Tools._NoneLogLevel;
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. Object.defineProperty(Tools, "MessageLogLevel", {
  6379. get: function () {
  6380. return Tools._MessageLogLevel;
  6381. },
  6382. enumerable: true,
  6383. configurable: true
  6384. });
  6385. Object.defineProperty(Tools, "WarningLogLevel", {
  6386. get: function () {
  6387. return Tools._WarningLogLevel;
  6388. },
  6389. enumerable: true,
  6390. configurable: true
  6391. });
  6392. Object.defineProperty(Tools, "ErrorLogLevel", {
  6393. get: function () {
  6394. return Tools._ErrorLogLevel;
  6395. },
  6396. enumerable: true,
  6397. configurable: true
  6398. });
  6399. Object.defineProperty(Tools, "AllLogLevel", {
  6400. get: function () {
  6401. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6402. },
  6403. enumerable: true,
  6404. configurable: true
  6405. });
  6406. Tools._AddLogEntry = function (entry) {
  6407. Tools._LogCache = entry + Tools._LogCache;
  6408. if (Tools.OnNewCacheEntry) {
  6409. Tools.OnNewCacheEntry(entry);
  6410. }
  6411. };
  6412. Tools._FormatMessage = function (message) {
  6413. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6414. var date = new Date();
  6415. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6416. };
  6417. Tools._LogDisabled = function (message) {
  6418. // nothing to do
  6419. };
  6420. Tools._LogEnabled = function (message) {
  6421. var formattedMessage = Tools._FormatMessage(message);
  6422. console.log("BJS - " + formattedMessage);
  6423. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6424. Tools._AddLogEntry(entry);
  6425. };
  6426. Tools._WarnDisabled = function (message) {
  6427. // nothing to do
  6428. };
  6429. Tools._WarnEnabled = function (message) {
  6430. var formattedMessage = Tools._FormatMessage(message);
  6431. console.warn("BJS - " + formattedMessage);
  6432. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6433. Tools._AddLogEntry(entry);
  6434. };
  6435. Tools._ErrorDisabled = function (message) {
  6436. // nothing to do
  6437. };
  6438. Tools._ErrorEnabled = function (message) {
  6439. Tools.errorsCount++;
  6440. var formattedMessage = Tools._FormatMessage(message);
  6441. console.error("BJS - " + formattedMessage);
  6442. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6443. Tools._AddLogEntry(entry);
  6444. };
  6445. Object.defineProperty(Tools, "LogCache", {
  6446. get: function () {
  6447. return Tools._LogCache;
  6448. },
  6449. enumerable: true,
  6450. configurable: true
  6451. });
  6452. Tools.ClearLogCache = function () {
  6453. Tools._LogCache = "";
  6454. Tools.errorsCount = 0;
  6455. };
  6456. Object.defineProperty(Tools, "LogLevels", {
  6457. set: function (level) {
  6458. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6459. Tools.Log = Tools._LogEnabled;
  6460. }
  6461. else {
  6462. Tools.Log = Tools._LogDisabled;
  6463. }
  6464. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6465. Tools.Warn = Tools._WarnEnabled;
  6466. }
  6467. else {
  6468. Tools.Warn = Tools._WarnDisabled;
  6469. }
  6470. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6471. Tools.Error = Tools._ErrorEnabled;
  6472. }
  6473. else {
  6474. Tools.Error = Tools._ErrorDisabled;
  6475. }
  6476. },
  6477. enumerable: true,
  6478. configurable: true
  6479. });
  6480. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6481. get: function () {
  6482. return Tools._PerformanceNoneLogLevel;
  6483. },
  6484. enumerable: true,
  6485. configurable: true
  6486. });
  6487. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6488. get: function () {
  6489. return Tools._PerformanceUserMarkLogLevel;
  6490. },
  6491. enumerable: true,
  6492. configurable: true
  6493. });
  6494. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6495. get: function () {
  6496. return Tools._PerformanceConsoleLogLevel;
  6497. },
  6498. enumerable: true,
  6499. configurable: true
  6500. });
  6501. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6502. set: function (level) {
  6503. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6504. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6505. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6506. return;
  6507. }
  6508. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6509. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6510. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6511. return;
  6512. }
  6513. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6514. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6515. },
  6516. enumerable: true,
  6517. configurable: true
  6518. });
  6519. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6520. };
  6521. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6522. };
  6523. Tools._StartUserMark = function (counterName, condition) {
  6524. if (condition === void 0) { condition = true; }
  6525. if (!condition || !Tools._performance.mark) {
  6526. return;
  6527. }
  6528. Tools._performance.mark(counterName + "-Begin");
  6529. };
  6530. Tools._EndUserMark = function (counterName, condition) {
  6531. if (condition === void 0) { condition = true; }
  6532. if (!condition || !Tools._performance.mark) {
  6533. return;
  6534. }
  6535. Tools._performance.mark(counterName + "-End");
  6536. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6537. };
  6538. Tools._StartPerformanceConsole = function (counterName, condition) {
  6539. if (condition === void 0) { condition = true; }
  6540. if (!condition) {
  6541. return;
  6542. }
  6543. Tools._StartUserMark(counterName, condition);
  6544. if (console.time) {
  6545. console.time(counterName);
  6546. }
  6547. };
  6548. Tools._EndPerformanceConsole = function (counterName, condition) {
  6549. if (condition === void 0) { condition = true; }
  6550. if (!condition) {
  6551. return;
  6552. }
  6553. Tools._EndUserMark(counterName, condition);
  6554. if (console.time) {
  6555. console.timeEnd(counterName);
  6556. }
  6557. };
  6558. Object.defineProperty(Tools, "Now", {
  6559. get: function () {
  6560. if (window.performance && window.performance.now) {
  6561. return window.performance.now();
  6562. }
  6563. return new Date().getTime();
  6564. },
  6565. enumerable: true,
  6566. configurable: true
  6567. });
  6568. /**
  6569. * This method will return the name of the class used to create the instance of the given object.
  6570. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6571. * @param object the object to get the class name from
  6572. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6573. */
  6574. Tools.GetClassName = function (object, isType) {
  6575. if (isType === void 0) { isType = false; }
  6576. var name = null;
  6577. if (!isType && object.getClassName) {
  6578. name = object.getClassName();
  6579. }
  6580. else {
  6581. if (object instanceof Object) {
  6582. var classObj = isType ? object : Object.getPrototypeOf(object);
  6583. name = classObj.constructor["__bjsclassName__"];
  6584. }
  6585. if (!name) {
  6586. name = typeof object;
  6587. }
  6588. }
  6589. return name;
  6590. };
  6591. Tools.first = function (array, predicate) {
  6592. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6593. var el = array_1[_i];
  6594. if (predicate(el)) {
  6595. return el;
  6596. }
  6597. }
  6598. };
  6599. /**
  6600. * This method will return the name of the full name of the class, including its owning module (if any).
  6601. * 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).
  6602. * @param object the object to get the class name from
  6603. * @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.
  6604. */
  6605. Tools.getFullClassName = function (object, isType) {
  6606. if (isType === void 0) { isType = false; }
  6607. var className = null;
  6608. var moduleName = null;
  6609. if (!isType && object.getClassName) {
  6610. className = object.getClassName();
  6611. }
  6612. else {
  6613. if (object instanceof Object) {
  6614. var classObj = isType ? object : Object.getPrototypeOf(object);
  6615. className = classObj.constructor["__bjsclassName__"];
  6616. moduleName = classObj.constructor["__bjsmoduleName__"];
  6617. }
  6618. if (!className) {
  6619. className = typeof object;
  6620. }
  6621. }
  6622. if (!className) {
  6623. return null;
  6624. }
  6625. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6626. };
  6627. /**
  6628. * 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.
  6629. * @param array
  6630. */
  6631. Tools.arrayOrStringFeeder = function (array) {
  6632. return function (index) {
  6633. if (index >= array.length) {
  6634. return null;
  6635. }
  6636. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6637. if (val && val.getHashCode) {
  6638. val = val.getHashCode();
  6639. }
  6640. if (typeof val === "string") {
  6641. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6642. }
  6643. return val;
  6644. };
  6645. };
  6646. /**
  6647. * Compute the hashCode of a stream of number
  6648. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6649. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6650. * @return the hash code computed
  6651. */
  6652. Tools.hashCodeFromStream = function (feeder) {
  6653. // Based from here: http://stackoverflow.com/a/7616484/802124
  6654. var hash = 0;
  6655. var index = 0;
  6656. var chr = feeder(index++);
  6657. while (chr != null) {
  6658. hash = ((hash << 5) - hash) + chr;
  6659. hash |= 0; // Convert to 32bit integer
  6660. chr = feeder(index++);
  6661. }
  6662. return hash;
  6663. };
  6664. Tools.BaseUrl = "";
  6665. Tools.CorsBehavior = "anonymous";
  6666. Tools.UseFallbackTexture = true;
  6667. /**
  6668. * Use this object to register external classes like custom textures or material
  6669. * to allow the laoders to instantiate them
  6670. */
  6671. Tools.RegisteredExternalClasses = {};
  6672. // Used in case of a texture loading problem
  6673. 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";
  6674. Tools.PreprocessUrl = function (url) {
  6675. return url;
  6676. };
  6677. // Logs
  6678. Tools._NoneLogLevel = 0;
  6679. Tools._MessageLogLevel = 1;
  6680. Tools._WarningLogLevel = 2;
  6681. Tools._ErrorLogLevel = 4;
  6682. Tools._LogCache = "";
  6683. Tools.errorsCount = 0;
  6684. Tools.Log = Tools._LogEnabled;
  6685. Tools.Warn = Tools._WarnEnabled;
  6686. Tools.Error = Tools._ErrorEnabled;
  6687. // Performances
  6688. Tools._PerformanceNoneLogLevel = 0;
  6689. Tools._PerformanceUserMarkLogLevel = 1;
  6690. Tools._PerformanceConsoleLogLevel = 2;
  6691. Tools._performance = window.performance;
  6692. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6693. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6694. return Tools;
  6695. }());
  6696. BABYLON.Tools = Tools;
  6697. /**
  6698. * This class is used to track a performance counter which is number based.
  6699. * The user has access to many properties which give statistics of different nature
  6700. *
  6701. * The implementer can track two kinds of Performance Counter: time and count
  6702. * 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.
  6703. * 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.
  6704. */
  6705. var PerfCounter = (function () {
  6706. function PerfCounter() {
  6707. this._startMonitoringTime = 0;
  6708. this._min = 0;
  6709. this._max = 0;
  6710. this._average = 0;
  6711. this._lastSecAverage = 0;
  6712. this._current = 0;
  6713. this._totalValueCount = 0;
  6714. this._totalAccumulated = 0;
  6715. this._lastSecAccumulated = 0;
  6716. this._lastSecTime = 0;
  6717. this._lastSecValueCount = 0;
  6718. }
  6719. Object.defineProperty(PerfCounter.prototype, "min", {
  6720. /**
  6721. * Returns the smallest value ever
  6722. */
  6723. get: function () {
  6724. return this._min;
  6725. },
  6726. enumerable: true,
  6727. configurable: true
  6728. });
  6729. Object.defineProperty(PerfCounter.prototype, "max", {
  6730. /**
  6731. * Returns the biggest value ever
  6732. */
  6733. get: function () {
  6734. return this._max;
  6735. },
  6736. enumerable: true,
  6737. configurable: true
  6738. });
  6739. Object.defineProperty(PerfCounter.prototype, "average", {
  6740. /**
  6741. * Returns the average value since the performance counter is running
  6742. */
  6743. get: function () {
  6744. return this._average;
  6745. },
  6746. enumerable: true,
  6747. configurable: true
  6748. });
  6749. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6750. /**
  6751. * Returns the average value of the last second the counter was monitored
  6752. */
  6753. get: function () {
  6754. return this._lastSecAverage;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(PerfCounter.prototype, "current", {
  6760. /**
  6761. * Returns the current value
  6762. */
  6763. get: function () {
  6764. return this._current;
  6765. },
  6766. enumerable: true,
  6767. configurable: true
  6768. });
  6769. Object.defineProperty(PerfCounter.prototype, "total", {
  6770. get: function () {
  6771. return this._totalAccumulated;
  6772. },
  6773. enumerable: true,
  6774. configurable: true
  6775. });
  6776. /**
  6777. * Call this method to start monitoring a new frame.
  6778. * 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.
  6779. */
  6780. PerfCounter.prototype.fetchNewFrame = function () {
  6781. this._totalValueCount++;
  6782. this._current = 0;
  6783. this._lastSecValueCount++;
  6784. };
  6785. /**
  6786. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6787. * @param newCount the count value to add to the monitored count
  6788. * @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.
  6789. */
  6790. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6791. if (!PerfCounter.Enabled) {
  6792. return;
  6793. }
  6794. this._current += newCount;
  6795. if (fetchResult) {
  6796. this._fetchResult();
  6797. }
  6798. };
  6799. /**
  6800. * Start monitoring this performance counter
  6801. */
  6802. PerfCounter.prototype.beginMonitoring = function () {
  6803. if (!PerfCounter.Enabled) {
  6804. return;
  6805. }
  6806. this._startMonitoringTime = Tools.Now;
  6807. };
  6808. /**
  6809. * Compute the time lapsed since the previous beginMonitoring() call.
  6810. * @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
  6811. */
  6812. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6813. if (newFrame === void 0) { newFrame = true; }
  6814. if (!PerfCounter.Enabled) {
  6815. return;
  6816. }
  6817. if (newFrame) {
  6818. this.fetchNewFrame();
  6819. }
  6820. var currentTime = Tools.Now;
  6821. this._current = currentTime - this._startMonitoringTime;
  6822. if (newFrame) {
  6823. this._fetchResult();
  6824. }
  6825. };
  6826. PerfCounter.prototype._fetchResult = function () {
  6827. this._totalAccumulated += this._current;
  6828. this._lastSecAccumulated += this._current;
  6829. // Min/Max update
  6830. this._min = Math.min(this._min, this._current);
  6831. this._max = Math.max(this._max, this._current);
  6832. this._average = this._totalAccumulated / this._totalValueCount;
  6833. // Reset last sec?
  6834. var now = Tools.Now;
  6835. if ((now - this._lastSecTime) > 1000) {
  6836. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6837. this._lastSecTime = now;
  6838. this._lastSecAccumulated = 0;
  6839. this._lastSecValueCount = 0;
  6840. }
  6841. };
  6842. PerfCounter.Enabled = true;
  6843. return PerfCounter;
  6844. }());
  6845. BABYLON.PerfCounter = PerfCounter;
  6846. /**
  6847. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6848. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6849. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6850. * @param name The name of the class, case should be preserved
  6851. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6852. */
  6853. function className(name, module) {
  6854. return function (target) {
  6855. target["__bjsclassName__"] = name;
  6856. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6857. };
  6858. }
  6859. BABYLON.className = className;
  6860. /**
  6861. * An implementation of a loop for asynchronous functions.
  6862. */
  6863. var AsyncLoop = (function () {
  6864. /**
  6865. * Constroctor.
  6866. * @param iterations the number of iterations.
  6867. * @param _fn the function to run each iteration
  6868. * @param _successCallback the callback that will be called upon succesful execution
  6869. * @param offset starting offset.
  6870. */
  6871. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6872. if (offset === void 0) { offset = 0; }
  6873. this.iterations = iterations;
  6874. this._fn = _fn;
  6875. this._successCallback = _successCallback;
  6876. this.index = offset - 1;
  6877. this._done = false;
  6878. }
  6879. /**
  6880. * Execute the next iteration. Must be called after the last iteration was finished.
  6881. */
  6882. AsyncLoop.prototype.executeNext = function () {
  6883. if (!this._done) {
  6884. if (this.index + 1 < this.iterations) {
  6885. ++this.index;
  6886. this._fn(this);
  6887. }
  6888. else {
  6889. this.breakLoop();
  6890. }
  6891. }
  6892. };
  6893. /**
  6894. * Break the loop and run the success callback.
  6895. */
  6896. AsyncLoop.prototype.breakLoop = function () {
  6897. this._done = true;
  6898. this._successCallback();
  6899. };
  6900. /**
  6901. * Helper function
  6902. */
  6903. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6904. if (offset === void 0) { offset = 0; }
  6905. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6906. loop.executeNext();
  6907. return loop;
  6908. };
  6909. /**
  6910. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6911. * @param iterations total number of iterations
  6912. * @param syncedIterations number of synchronous iterations in each async iteration.
  6913. * @param fn the function to call each iteration.
  6914. * @param callback a success call back that will be called when iterating stops.
  6915. * @param breakFunction a break condition (optional)
  6916. * @param timeout timeout settings for the setTimeout function. default - 0.
  6917. * @constructor
  6918. */
  6919. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6920. if (timeout === void 0) { timeout = 0; }
  6921. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6922. if (breakFunction && breakFunction())
  6923. loop.breakLoop();
  6924. else {
  6925. setTimeout(function () {
  6926. for (var i = 0; i < syncedIterations; ++i) {
  6927. var iteration = (loop.index * syncedIterations) + i;
  6928. if (iteration >= iterations)
  6929. break;
  6930. fn(iteration);
  6931. if (breakFunction && breakFunction()) {
  6932. loop.breakLoop();
  6933. break;
  6934. }
  6935. }
  6936. loop.executeNext();
  6937. }, timeout);
  6938. }
  6939. }, callback);
  6940. };
  6941. return AsyncLoop;
  6942. }());
  6943. BABYLON.AsyncLoop = AsyncLoop;
  6944. })(BABYLON || (BABYLON = {}));
  6945. //# sourceMappingURL=babylon.tools.js.map
  6946. var BABYLON;
  6947. (function (BABYLON) {
  6948. var Internals;
  6949. (function (Internals) {
  6950. var _AlphaState = (function () {
  6951. /**
  6952. * Initializes the state.
  6953. */
  6954. function _AlphaState() {
  6955. this._isAlphaBlendDirty = false;
  6956. this._isBlendFunctionParametersDirty = false;
  6957. this._isBlendEquationParametersDirty = false;
  6958. this._isBlendConstantsDirty = false;
  6959. this._alphaBlend = false;
  6960. this._blendFunctionParameters = new Array(4);
  6961. this._blendEquationParameters = new Array(2);
  6962. this._blendConstants = new Array(4);
  6963. this.reset();
  6964. }
  6965. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6966. get: function () {
  6967. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6968. },
  6969. enumerable: true,
  6970. configurable: true
  6971. });
  6972. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6973. get: function () {
  6974. return this._alphaBlend;
  6975. },
  6976. set: function (value) {
  6977. if (this._alphaBlend === value) {
  6978. return;
  6979. }
  6980. this._alphaBlend = value;
  6981. this._isAlphaBlendDirty = true;
  6982. },
  6983. enumerable: true,
  6984. configurable: true
  6985. });
  6986. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6987. if (this._blendConstants[0] === r &&
  6988. this._blendConstants[1] === g &&
  6989. this._blendConstants[2] === b &&
  6990. this._blendConstants[3] === a) {
  6991. return;
  6992. }
  6993. this._blendConstants[0] = r;
  6994. this._blendConstants[1] = g;
  6995. this._blendConstants[2] = b;
  6996. this._blendConstants[3] = a;
  6997. this._isBlendConstantsDirty = true;
  6998. };
  6999. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7000. if (this._blendFunctionParameters[0] === value0 &&
  7001. this._blendFunctionParameters[1] === value1 &&
  7002. this._blendFunctionParameters[2] === value2 &&
  7003. this._blendFunctionParameters[3] === value3) {
  7004. return;
  7005. }
  7006. this._blendFunctionParameters[0] = value0;
  7007. this._blendFunctionParameters[1] = value1;
  7008. this._blendFunctionParameters[2] = value2;
  7009. this._blendFunctionParameters[3] = value3;
  7010. this._isBlendFunctionParametersDirty = true;
  7011. };
  7012. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7013. if (this._blendEquationParameters[0] === rgb &&
  7014. this._blendEquationParameters[1] === alpha) {
  7015. return;
  7016. }
  7017. this._blendEquationParameters[0] = rgb;
  7018. this._blendEquationParameters[1] = alpha;
  7019. this._isBlendEquationParametersDirty = true;
  7020. };
  7021. _AlphaState.prototype.reset = function () {
  7022. this._alphaBlend = false;
  7023. this._blendFunctionParameters[0] = null;
  7024. this._blendFunctionParameters[1] = null;
  7025. this._blendFunctionParameters[2] = null;
  7026. this._blendFunctionParameters[3] = null;
  7027. this._blendEquationParameters[0] = null;
  7028. this._blendEquationParameters[1] = null;
  7029. this._blendConstants[0] = null;
  7030. this._blendConstants[1] = null;
  7031. this._blendConstants[2] = null;
  7032. this._blendConstants[3] = null;
  7033. this._isAlphaBlendDirty = true;
  7034. this._isBlendFunctionParametersDirty = false;
  7035. this._isBlendEquationParametersDirty = false;
  7036. this._isBlendConstantsDirty = false;
  7037. };
  7038. _AlphaState.prototype.apply = function (gl) {
  7039. if (!this.isDirty) {
  7040. return;
  7041. }
  7042. // Alpha blend
  7043. if (this._isAlphaBlendDirty) {
  7044. if (this._alphaBlend) {
  7045. gl.enable(gl.BLEND);
  7046. }
  7047. else {
  7048. gl.disable(gl.BLEND);
  7049. }
  7050. this._isAlphaBlendDirty = false;
  7051. }
  7052. // Alpha function
  7053. if (this._isBlendFunctionParametersDirty) {
  7054. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7055. this._isBlendFunctionParametersDirty = false;
  7056. }
  7057. // Alpha equation
  7058. if (this._isBlendEquationParametersDirty) {
  7059. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7060. this._isBlendEquationParametersDirty = false;
  7061. }
  7062. // Constants
  7063. if (this._isBlendConstantsDirty) {
  7064. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7065. this._isBlendConstantsDirty = false;
  7066. }
  7067. };
  7068. return _AlphaState;
  7069. }());
  7070. Internals._AlphaState = _AlphaState;
  7071. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7072. })(BABYLON || (BABYLON = {}));
  7073. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7074. var BABYLON;
  7075. (function (BABYLON) {
  7076. var Internals;
  7077. (function (Internals) {
  7078. var _DepthCullingState = (function () {
  7079. /**
  7080. * Initializes the state.
  7081. */
  7082. function _DepthCullingState() {
  7083. this._isDepthTestDirty = false;
  7084. this._isDepthMaskDirty = false;
  7085. this._isDepthFuncDirty = false;
  7086. this._isCullFaceDirty = false;
  7087. this._isCullDirty = false;
  7088. this._isZOffsetDirty = false;
  7089. this.reset();
  7090. }
  7091. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7092. get: function () {
  7093. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7094. },
  7095. enumerable: true,
  7096. configurable: true
  7097. });
  7098. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7099. get: function () {
  7100. return this._zOffset;
  7101. },
  7102. set: function (value) {
  7103. if (this._zOffset === value) {
  7104. return;
  7105. }
  7106. this._zOffset = value;
  7107. this._isZOffsetDirty = true;
  7108. },
  7109. enumerable: true,
  7110. configurable: true
  7111. });
  7112. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7113. get: function () {
  7114. return this._cullFace;
  7115. },
  7116. set: function (value) {
  7117. if (this._cullFace === value) {
  7118. return;
  7119. }
  7120. this._cullFace = value;
  7121. this._isCullFaceDirty = true;
  7122. },
  7123. enumerable: true,
  7124. configurable: true
  7125. });
  7126. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7127. get: function () {
  7128. return this._cull;
  7129. },
  7130. set: function (value) {
  7131. if (this._cull === value) {
  7132. return;
  7133. }
  7134. this._cull = value;
  7135. this._isCullDirty = true;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7141. get: function () {
  7142. return this._depthFunc;
  7143. },
  7144. set: function (value) {
  7145. if (this._depthFunc === value) {
  7146. return;
  7147. }
  7148. this._depthFunc = value;
  7149. this._isDepthFuncDirty = true;
  7150. },
  7151. enumerable: true,
  7152. configurable: true
  7153. });
  7154. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7155. get: function () {
  7156. return this._depthMask;
  7157. },
  7158. set: function (value) {
  7159. if (this._depthMask === value) {
  7160. return;
  7161. }
  7162. this._depthMask = value;
  7163. this._isDepthMaskDirty = true;
  7164. },
  7165. enumerable: true,
  7166. configurable: true
  7167. });
  7168. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7169. get: function () {
  7170. return this._depthTest;
  7171. },
  7172. set: function (value) {
  7173. if (this._depthTest === value) {
  7174. return;
  7175. }
  7176. this._depthTest = value;
  7177. this._isDepthTestDirty = true;
  7178. },
  7179. enumerable: true,
  7180. configurable: true
  7181. });
  7182. _DepthCullingState.prototype.reset = function () {
  7183. this._depthMask = true;
  7184. this._depthTest = true;
  7185. this._depthFunc = null;
  7186. this._cullFace = null;
  7187. this._cull = null;
  7188. this._zOffset = 0;
  7189. this._isDepthTestDirty = true;
  7190. this._isDepthMaskDirty = true;
  7191. this._isDepthFuncDirty = false;
  7192. this._isCullFaceDirty = false;
  7193. this._isCullDirty = false;
  7194. this._isZOffsetDirty = false;
  7195. };
  7196. _DepthCullingState.prototype.apply = function (gl) {
  7197. if (!this.isDirty) {
  7198. return;
  7199. }
  7200. // Cull
  7201. if (this._isCullDirty) {
  7202. if (this.cull) {
  7203. gl.enable(gl.CULL_FACE);
  7204. }
  7205. else {
  7206. gl.disable(gl.CULL_FACE);
  7207. }
  7208. this._isCullDirty = false;
  7209. }
  7210. // Cull face
  7211. if (this._isCullFaceDirty) {
  7212. gl.cullFace(this.cullFace);
  7213. this._isCullFaceDirty = false;
  7214. }
  7215. // Depth mask
  7216. if (this._isDepthMaskDirty) {
  7217. gl.depthMask(this.depthMask);
  7218. this._isDepthMaskDirty = false;
  7219. }
  7220. // Depth test
  7221. if (this._isDepthTestDirty) {
  7222. if (this.depthTest) {
  7223. gl.enable(gl.DEPTH_TEST);
  7224. }
  7225. else {
  7226. gl.disable(gl.DEPTH_TEST);
  7227. }
  7228. this._isDepthTestDirty = false;
  7229. }
  7230. // Depth func
  7231. if (this._isDepthFuncDirty) {
  7232. gl.depthFunc(this.depthFunc);
  7233. this._isDepthFuncDirty = false;
  7234. }
  7235. // zOffset
  7236. if (this._isZOffsetDirty) {
  7237. if (this.zOffset) {
  7238. gl.enable(gl.POLYGON_OFFSET_FILL);
  7239. gl.polygonOffset(this.zOffset, 0);
  7240. }
  7241. else {
  7242. gl.disable(gl.POLYGON_OFFSET_FILL);
  7243. }
  7244. this._isZOffsetDirty = false;
  7245. }
  7246. };
  7247. return _DepthCullingState;
  7248. }());
  7249. Internals._DepthCullingState = _DepthCullingState;
  7250. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7251. })(BABYLON || (BABYLON = {}));
  7252. //# sourceMappingURL=babylon.depthCullingState.js.map
  7253. var BABYLON;
  7254. (function (BABYLON) {
  7255. var Internals;
  7256. (function (Internals) {
  7257. var _StencilState = (function () {
  7258. function _StencilState() {
  7259. this._isStencilTestDirty = false;
  7260. this._isStencilMaskDirty = false;
  7261. this._isStencilFuncDirty = false;
  7262. this._isStencilOpDirty = false;
  7263. this.reset();
  7264. }
  7265. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7266. get: function () {
  7267. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7268. },
  7269. enumerable: true,
  7270. configurable: true
  7271. });
  7272. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7273. get: function () {
  7274. return this._stencilFunc;
  7275. },
  7276. set: function (value) {
  7277. if (this._stencilFunc === value) {
  7278. return;
  7279. }
  7280. this._stencilFunc = value;
  7281. this._isStencilFuncDirty = true;
  7282. },
  7283. enumerable: true,
  7284. configurable: true
  7285. });
  7286. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7287. get: function () {
  7288. return this._stencilFuncRef;
  7289. },
  7290. set: function (value) {
  7291. if (this._stencilFuncRef === value) {
  7292. return;
  7293. }
  7294. this._stencilFuncRef = value;
  7295. this._isStencilFuncDirty = true;
  7296. },
  7297. enumerable: true,
  7298. configurable: true
  7299. });
  7300. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7301. get: function () {
  7302. return this._stencilFuncMask;
  7303. },
  7304. set: function (value) {
  7305. if (this._stencilFuncMask === value) {
  7306. return;
  7307. }
  7308. this._stencilFuncMask = value;
  7309. this._isStencilFuncDirty = true;
  7310. },
  7311. enumerable: true,
  7312. configurable: true
  7313. });
  7314. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7315. get: function () {
  7316. return this._stencilOpStencilFail;
  7317. },
  7318. set: function (value) {
  7319. if (this._stencilOpStencilFail === value) {
  7320. return;
  7321. }
  7322. this._stencilOpStencilFail = value;
  7323. this._isStencilOpDirty = true;
  7324. },
  7325. enumerable: true,
  7326. configurable: true
  7327. });
  7328. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7329. get: function () {
  7330. return this._stencilOpDepthFail;
  7331. },
  7332. set: function (value) {
  7333. if (this._stencilOpDepthFail === value) {
  7334. return;
  7335. }
  7336. this._stencilOpDepthFail = value;
  7337. this._isStencilOpDirty = true;
  7338. },
  7339. enumerable: true,
  7340. configurable: true
  7341. });
  7342. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7343. get: function () {
  7344. return this._stencilOpStencilDepthPass;
  7345. },
  7346. set: function (value) {
  7347. if (this._stencilOpStencilDepthPass === value) {
  7348. return;
  7349. }
  7350. this._stencilOpStencilDepthPass = value;
  7351. this._isStencilOpDirty = true;
  7352. },
  7353. enumerable: true,
  7354. configurable: true
  7355. });
  7356. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7357. get: function () {
  7358. return this._stencilMask;
  7359. },
  7360. set: function (value) {
  7361. if (this._stencilMask === value) {
  7362. return;
  7363. }
  7364. this._stencilMask = value;
  7365. this._isStencilMaskDirty = true;
  7366. },
  7367. enumerable: true,
  7368. configurable: true
  7369. });
  7370. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7371. get: function () {
  7372. return this._stencilTest;
  7373. },
  7374. set: function (value) {
  7375. if (this._stencilTest === value) {
  7376. return;
  7377. }
  7378. this._stencilTest = value;
  7379. this._isStencilTestDirty = true;
  7380. },
  7381. enumerable: true,
  7382. configurable: true
  7383. });
  7384. _StencilState.prototype.reset = function () {
  7385. this._stencilTest = false;
  7386. this._stencilMask = 0xFF;
  7387. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7388. this._stencilFuncRef = 1;
  7389. this._stencilFuncMask = 0xFF;
  7390. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7391. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7392. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7393. this._isStencilTestDirty = true;
  7394. this._isStencilMaskDirty = true;
  7395. this._isStencilFuncDirty = true;
  7396. this._isStencilOpDirty = true;
  7397. };
  7398. _StencilState.prototype.apply = function (gl) {
  7399. if (!this.isDirty) {
  7400. return;
  7401. }
  7402. // Stencil test
  7403. if (this._isStencilTestDirty) {
  7404. if (this.stencilTest) {
  7405. gl.enable(gl.STENCIL_TEST);
  7406. }
  7407. else {
  7408. gl.disable(gl.STENCIL_TEST);
  7409. }
  7410. this._isStencilTestDirty = false;
  7411. }
  7412. // Stencil mask
  7413. if (this._isStencilMaskDirty) {
  7414. gl.stencilMask(this.stencilMask);
  7415. this._isStencilMaskDirty = false;
  7416. }
  7417. // Stencil func
  7418. if (this._isStencilFuncDirty) {
  7419. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7420. this._isStencilFuncDirty = false;
  7421. }
  7422. // Stencil op
  7423. if (this._isStencilOpDirty) {
  7424. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7425. this._isStencilOpDirty = false;
  7426. }
  7427. };
  7428. return _StencilState;
  7429. }());
  7430. Internals._StencilState = _StencilState;
  7431. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7432. })(BABYLON || (BABYLON = {}));
  7433. //# sourceMappingURL=babylon.stencilState.js.map
  7434. var BABYLON;
  7435. (function (BABYLON) {
  7436. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7437. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7438. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7439. gl.compileShader(shader);
  7440. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7441. throw new Error(gl.getShaderInfoLog(shader));
  7442. }
  7443. return shader;
  7444. };
  7445. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7446. var magFilter = gl.NEAREST;
  7447. var minFilter = gl.NEAREST;
  7448. switch (samplingMode) {
  7449. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7450. magFilter = gl.LINEAR;
  7451. if (generateMipMaps) {
  7452. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7453. }
  7454. else {
  7455. minFilter = gl.LINEAR;
  7456. }
  7457. break;
  7458. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7459. magFilter = gl.LINEAR;
  7460. if (generateMipMaps) {
  7461. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7462. }
  7463. else {
  7464. minFilter = gl.LINEAR;
  7465. }
  7466. break;
  7467. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7468. magFilter = gl.NEAREST;
  7469. if (generateMipMaps) {
  7470. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7471. }
  7472. else {
  7473. minFilter = gl.NEAREST;
  7474. }
  7475. break;
  7476. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7477. magFilter = gl.NEAREST;
  7478. if (generateMipMaps) {
  7479. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7480. }
  7481. else {
  7482. minFilter = gl.NEAREST;
  7483. }
  7484. break;
  7485. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7486. magFilter = gl.NEAREST;
  7487. if (generateMipMaps) {
  7488. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7489. }
  7490. else {
  7491. minFilter = gl.LINEAR;
  7492. }
  7493. break;
  7494. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7495. magFilter = gl.NEAREST;
  7496. if (generateMipMaps) {
  7497. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7498. }
  7499. else {
  7500. minFilter = gl.LINEAR;
  7501. }
  7502. break;
  7503. case BABYLON.Texture.NEAREST_LINEAR:
  7504. magFilter = gl.NEAREST;
  7505. minFilter = gl.LINEAR;
  7506. break;
  7507. case BABYLON.Texture.NEAREST_NEAREST:
  7508. magFilter = gl.NEAREST;
  7509. minFilter = gl.NEAREST;
  7510. break;
  7511. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7512. magFilter = gl.LINEAR;
  7513. if (generateMipMaps) {
  7514. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7515. }
  7516. else {
  7517. minFilter = gl.NEAREST;
  7518. }
  7519. break;
  7520. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7521. magFilter = gl.LINEAR;
  7522. if (generateMipMaps) {
  7523. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7524. }
  7525. else {
  7526. minFilter = gl.NEAREST;
  7527. }
  7528. break;
  7529. case BABYLON.Texture.LINEAR_LINEAR:
  7530. magFilter = gl.LINEAR;
  7531. minFilter = gl.LINEAR;
  7532. break;
  7533. case BABYLON.Texture.LINEAR_NEAREST:
  7534. magFilter = gl.LINEAR;
  7535. minFilter = gl.NEAREST;
  7536. break;
  7537. }
  7538. return {
  7539. min: minFilter,
  7540. mag: magFilter
  7541. };
  7542. };
  7543. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7544. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7545. var img;
  7546. var onload = function () {
  7547. loadedImages[index] = img;
  7548. loadedImages._internalCount++;
  7549. if (scene) {
  7550. scene._removePendingData(img);
  7551. }
  7552. if (loadedImages._internalCount === 6) {
  7553. onfinish(loadedImages);
  7554. }
  7555. };
  7556. var onerror = function (message, exception) {
  7557. if (scene) {
  7558. scene._removePendingData(img);
  7559. }
  7560. if (onErrorCallBack) {
  7561. onErrorCallBack(message, exception);
  7562. }
  7563. };
  7564. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7565. if (scene) {
  7566. scene._addPendingData(img);
  7567. }
  7568. };
  7569. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7570. if (onError === void 0) { onError = null; }
  7571. var loadedImages = [];
  7572. loadedImages._internalCount = 0;
  7573. for (var index = 0; index < 6; index++) {
  7574. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7575. }
  7576. };
  7577. var BufferPointer = (function () {
  7578. function BufferPointer() {
  7579. }
  7580. return BufferPointer;
  7581. }());
  7582. var InstancingAttributeInfo = (function () {
  7583. function InstancingAttributeInfo() {
  7584. }
  7585. return InstancingAttributeInfo;
  7586. }());
  7587. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7588. /**
  7589. * Define options used to create a render target texture
  7590. */
  7591. var RenderTargetCreationOptions = (function () {
  7592. function RenderTargetCreationOptions() {
  7593. }
  7594. return RenderTargetCreationOptions;
  7595. }());
  7596. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7597. /**
  7598. * Regroup several parameters relative to the browser in use
  7599. */
  7600. var EngineCapabilities = (function () {
  7601. function EngineCapabilities() {
  7602. }
  7603. return EngineCapabilities;
  7604. }());
  7605. BABYLON.EngineCapabilities = EngineCapabilities;
  7606. /**
  7607. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7608. */
  7609. var Engine = (function () {
  7610. /**
  7611. * @constructor
  7612. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7613. * @param {boolean} [antialias] - enable antialias
  7614. * @param options - further options to be sent to the getContext function
  7615. */
  7616. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7617. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7618. var _this = this;
  7619. // Public members
  7620. this.forcePOTTextures = false;
  7621. this.isFullscreen = false;
  7622. this.isPointerLock = false;
  7623. this.cullBackFaces = true;
  7624. this.renderEvenInBackground = true;
  7625. this.preventCacheWipeBetweenFrames = false;
  7626. // To enable/disable IDB support and avoid XHR on .manifest
  7627. this.enableOfflineSupport = false;
  7628. this.scenes = new Array();
  7629. this.postProcesses = new Array();
  7630. // Observables
  7631. /**
  7632. * Observable event triggered each time the rendering canvas is resized
  7633. */
  7634. this.onResizeObservable = new BABYLON.Observable();
  7635. /**
  7636. * Observable event triggered each time the canvas loses focus
  7637. */
  7638. this.onCanvasBlurObservable = new BABYLON.Observable();
  7639. /**
  7640. * Observable event triggered each time the canvas gains focus
  7641. */
  7642. this.onCanvasFocusObservable = new BABYLON.Observable();
  7643. /**
  7644. * Observable event triggered each time the canvas receives pointerout event
  7645. */
  7646. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7647. /**
  7648. * Observable event triggered before each texture is initialized
  7649. */
  7650. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7651. //WebVR
  7652. this._vrDisplay = undefined;
  7653. this._vrSupported = false;
  7654. this._vrExclusivePointerMode = false;
  7655. // Uniform buffers list
  7656. this.disableUniformBuffers = false;
  7657. this._uniformBuffers = new Array();
  7658. this._windowIsBackground = false;
  7659. this._webGLVersion = 1.0;
  7660. this._badOS = false;
  7661. this._badDesktopOS = false;
  7662. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7663. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7664. this.onVRRequestPresentStart = new BABYLON.Observable();
  7665. this._colorWrite = true;
  7666. this._drawCalls = new BABYLON.PerfCounter();
  7667. this._renderingQueueLaunched = false;
  7668. this._activeRenderLoops = [];
  7669. // Deterministic lockstepMaxSteps
  7670. this._deterministicLockstep = false;
  7671. this._lockstepMaxSteps = 4;
  7672. // Lost context
  7673. this.onContextLostObservable = new BABYLON.Observable();
  7674. this.onContextRestoredObservable = new BABYLON.Observable();
  7675. this._contextWasLost = false;
  7676. this._doNotHandleContextLost = false;
  7677. // FPS
  7678. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7679. this._fps = 60;
  7680. this._deltaTime = 0;
  7681. /**
  7682. * Turn this value on if you want to pause FPS computation when in background
  7683. */
  7684. this.disablePerformanceMonitorInBackground = false;
  7685. // States
  7686. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7687. this._stencilState = new BABYLON.Internals._StencilState();
  7688. this._alphaState = new BABYLON.Internals._AlphaState();
  7689. this._alphaMode = Engine.ALPHA_DISABLE;
  7690. // Cache
  7691. this._internalTexturesCache = new Array();
  7692. this._maxTextureChannels = 16;
  7693. this._activeTexturesCache = {};
  7694. this._compiledEffects = {};
  7695. this._vertexAttribArraysEnabled = [];
  7696. this._uintIndicesCurrentlySet = false;
  7697. this._currentBoundBuffer = new Array();
  7698. this._currentBufferPointers = new Array();
  7699. this._currentInstanceLocations = new Array();
  7700. this._currentInstanceBuffers = new Array();
  7701. this._vaoRecordInProgress = false;
  7702. this._mustWipeVertexAttributes = false;
  7703. // Hardware supported Compressed Textures
  7704. this._texturesSupported = new Array();
  7705. this._onVRFullScreenTriggered = function () {
  7706. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7707. //get the old size before we change
  7708. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7709. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7710. //get the width and height, change the render size
  7711. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7712. var width, height;
  7713. _this.setHardwareScalingLevel(1);
  7714. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7715. }
  7716. else {
  7717. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7718. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7719. }
  7720. };
  7721. var canvas;
  7722. Engine.Instances.push(this);
  7723. options = options || {};
  7724. if (canvasOrContext.getContext) {
  7725. canvas = canvasOrContext;
  7726. this._renderingCanvas = canvas;
  7727. if (antialias != null) {
  7728. options.antialias = antialias;
  7729. }
  7730. if (options.deterministicLockstep === undefined) {
  7731. options.deterministicLockstep = false;
  7732. }
  7733. if (options.lockstepMaxSteps === undefined) {
  7734. options.lockstepMaxSteps = 4;
  7735. }
  7736. if (options.preserveDrawingBuffer === undefined) {
  7737. options.preserveDrawingBuffer = false;
  7738. }
  7739. if (options.audioEngine === undefined) {
  7740. options.audioEngine = true;
  7741. }
  7742. if (options.stencil === undefined) {
  7743. options.stencil = true;
  7744. }
  7745. this._deterministicLockstep = options.deterministicLockstep;
  7746. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7747. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7748. // GL
  7749. if (!options.disableWebGL2Support) {
  7750. try {
  7751. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7752. if (this._gl) {
  7753. this._webGLVersion = 2.0;
  7754. }
  7755. }
  7756. catch (e) {
  7757. // Do nothing
  7758. }
  7759. }
  7760. if (!this._gl) {
  7761. if (!canvas) {
  7762. throw new Error("The provided canvas is null or undefined.");
  7763. }
  7764. try {
  7765. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7766. }
  7767. catch (e) {
  7768. throw new Error("WebGL not supported");
  7769. }
  7770. }
  7771. if (!this._gl) {
  7772. throw new Error("WebGL not supported");
  7773. }
  7774. this._onCanvasFocus = function () {
  7775. _this.onCanvasFocusObservable.notifyObservers(_this);
  7776. };
  7777. this._onCanvasBlur = function () {
  7778. _this.onCanvasBlurObservable.notifyObservers(_this);
  7779. };
  7780. canvas.addEventListener("focus", this._onCanvasFocus);
  7781. canvas.addEventListener("blur", this._onCanvasBlur);
  7782. this._onBlur = function () {
  7783. if (_this.disablePerformanceMonitorInBackground) {
  7784. _this._performanceMonitor.disable();
  7785. }
  7786. _this._windowIsBackground = true;
  7787. };
  7788. this._onFocus = function () {
  7789. if (_this.disablePerformanceMonitorInBackground) {
  7790. _this._performanceMonitor.enable();
  7791. }
  7792. _this._windowIsBackground = false;
  7793. };
  7794. this._onCanvasPointerOut = function () {
  7795. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7796. };
  7797. window.addEventListener("blur", this._onBlur);
  7798. window.addEventListener("focus", this._onFocus);
  7799. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7800. // Context lost
  7801. if (!this._doNotHandleContextLost) {
  7802. this._onContextLost = function (evt) {
  7803. evt.preventDefault();
  7804. _this._contextWasLost = true;
  7805. BABYLON.Tools.Warn("WebGL context lost.");
  7806. _this.onContextLostObservable.notifyObservers(_this);
  7807. };
  7808. this._onContextRestored = function (evt) {
  7809. // Adding a timeout to avoid race condition at browser level
  7810. setTimeout(function () {
  7811. // Rebuild gl context
  7812. _this._initGLContext();
  7813. // Rebuild effects
  7814. _this._rebuildEffects();
  7815. // Rebuild textures
  7816. _this._rebuildInternalTextures();
  7817. // Rebuild buffers
  7818. _this._rebuildBuffers();
  7819. // Cache
  7820. _this.wipeCaches(true);
  7821. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7822. _this.onContextRestoredObservable.notifyObservers(_this);
  7823. _this._contextWasLost = false;
  7824. }, 0);
  7825. };
  7826. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7827. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7828. }
  7829. }
  7830. else {
  7831. this._gl = canvasOrContext;
  7832. this._renderingCanvas = this._gl.canvas;
  7833. if (this._gl.renderbufferStorageMultisample) {
  7834. this._webGLVersion = 2.0;
  7835. }
  7836. options.stencil = this._gl.getContextAttributes().stencil;
  7837. }
  7838. // Viewport
  7839. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7840. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7841. this.resize();
  7842. this._isStencilEnable = options.stencil;
  7843. this._initGLContext();
  7844. if (canvas) {
  7845. // Fullscreen
  7846. this._onFullscreenChange = function () {
  7847. if (document.fullscreen !== undefined) {
  7848. _this.isFullscreen = document.fullscreen;
  7849. }
  7850. else if (document.mozFullScreen !== undefined) {
  7851. _this.isFullscreen = document.mozFullScreen;
  7852. }
  7853. else if (document.webkitIsFullScreen !== undefined) {
  7854. _this.isFullscreen = document.webkitIsFullScreen;
  7855. }
  7856. else if (document.msIsFullScreen !== undefined) {
  7857. _this.isFullscreen = document.msIsFullScreen;
  7858. }
  7859. // Pointer lock
  7860. if (_this.isFullscreen && _this._pointerLockRequested) {
  7861. canvas.requestPointerLock = canvas.requestPointerLock ||
  7862. canvas.msRequestPointerLock ||
  7863. canvas.mozRequestPointerLock ||
  7864. canvas.webkitRequestPointerLock;
  7865. if (canvas.requestPointerLock) {
  7866. canvas.requestPointerLock();
  7867. }
  7868. }
  7869. };
  7870. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7871. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7872. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7873. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7874. // Pointer lock
  7875. this._onPointerLockChange = function () {
  7876. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7877. document.webkitPointerLockElement === canvas ||
  7878. document.msPointerLockElement === canvas ||
  7879. document.pointerLockElement === canvas);
  7880. };
  7881. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7882. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7883. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7884. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7885. this._onVRDisplayPointerRestricted = function () {
  7886. canvas.requestPointerLock();
  7887. };
  7888. this._onVRDisplayPointerUnrestricted = function () {
  7889. document.exitPointerLock();
  7890. };
  7891. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7892. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7893. }
  7894. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7895. Engine.audioEngine = new BABYLON.AudioEngine();
  7896. }
  7897. // Prepare buffer pointers
  7898. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7899. this._currentBufferPointers[i] = new BufferPointer();
  7900. }
  7901. // Load WebVR Devices
  7902. if (options.autoEnableWebVR) {
  7903. this.initWebVR();
  7904. }
  7905. // Detect if we are running on a faulty buggy OS.
  7906. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7907. // Detect if we are running on a faulty buggy desktop OS.
  7908. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7909. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7910. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7911. }
  7912. Object.defineProperty(Engine, "LastCreatedEngine", {
  7913. get: function () {
  7914. if (Engine.Instances.length === 0) {
  7915. return null;
  7916. }
  7917. return Engine.Instances[Engine.Instances.length - 1];
  7918. },
  7919. enumerable: true,
  7920. configurable: true
  7921. });
  7922. Object.defineProperty(Engine, "LastCreatedScene", {
  7923. get: function () {
  7924. var lastCreatedEngine = Engine.LastCreatedEngine;
  7925. if (!lastCreatedEngine) {
  7926. return null;
  7927. }
  7928. if (lastCreatedEngine.scenes.length === 0) {
  7929. return null;
  7930. }
  7931. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7932. },
  7933. enumerable: true,
  7934. configurable: true
  7935. });
  7936. /**
  7937. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7938. */
  7939. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7940. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7941. var engine = Engine.Instances[engineIndex];
  7942. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7943. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7944. }
  7945. }
  7946. };
  7947. Object.defineProperty(Engine, "NEVER", {
  7948. get: function () {
  7949. return Engine._NEVER;
  7950. },
  7951. enumerable: true,
  7952. configurable: true
  7953. });
  7954. Object.defineProperty(Engine, "ALWAYS", {
  7955. get: function () {
  7956. return Engine._ALWAYS;
  7957. },
  7958. enumerable: true,
  7959. configurable: true
  7960. });
  7961. Object.defineProperty(Engine, "LESS", {
  7962. get: function () {
  7963. return Engine._LESS;
  7964. },
  7965. enumerable: true,
  7966. configurable: true
  7967. });
  7968. Object.defineProperty(Engine, "EQUAL", {
  7969. get: function () {
  7970. return Engine._EQUAL;
  7971. },
  7972. enumerable: true,
  7973. configurable: true
  7974. });
  7975. Object.defineProperty(Engine, "LEQUAL", {
  7976. get: function () {
  7977. return Engine._LEQUAL;
  7978. },
  7979. enumerable: true,
  7980. configurable: true
  7981. });
  7982. Object.defineProperty(Engine, "GREATER", {
  7983. get: function () {
  7984. return Engine._GREATER;
  7985. },
  7986. enumerable: true,
  7987. configurable: true
  7988. });
  7989. Object.defineProperty(Engine, "GEQUAL", {
  7990. get: function () {
  7991. return Engine._GEQUAL;
  7992. },
  7993. enumerable: true,
  7994. configurable: true
  7995. });
  7996. Object.defineProperty(Engine, "NOTEQUAL", {
  7997. get: function () {
  7998. return Engine._NOTEQUAL;
  7999. },
  8000. enumerable: true,
  8001. configurable: true
  8002. });
  8003. Object.defineProperty(Engine, "KEEP", {
  8004. get: function () {
  8005. return Engine._KEEP;
  8006. },
  8007. enumerable: true,
  8008. configurable: true
  8009. });
  8010. Object.defineProperty(Engine, "REPLACE", {
  8011. get: function () {
  8012. return Engine._REPLACE;
  8013. },
  8014. enumerable: true,
  8015. configurable: true
  8016. });
  8017. Object.defineProperty(Engine, "INCR", {
  8018. get: function () {
  8019. return Engine._INCR;
  8020. },
  8021. enumerable: true,
  8022. configurable: true
  8023. });
  8024. Object.defineProperty(Engine, "DECR", {
  8025. get: function () {
  8026. return Engine._DECR;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(Engine, "INVERT", {
  8032. get: function () {
  8033. return Engine._INVERT;
  8034. },
  8035. enumerable: true,
  8036. configurable: true
  8037. });
  8038. Object.defineProperty(Engine, "INCR_WRAP", {
  8039. get: function () {
  8040. return Engine._INCR_WRAP;
  8041. },
  8042. enumerable: true,
  8043. configurable: true
  8044. });
  8045. Object.defineProperty(Engine, "DECR_WRAP", {
  8046. get: function () {
  8047. return Engine._DECR_WRAP;
  8048. },
  8049. enumerable: true,
  8050. configurable: true
  8051. });
  8052. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8053. get: function () {
  8054. return Engine._ALPHA_DISABLE;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8060. get: function () {
  8061. return Engine._ALPHA_ONEONE;
  8062. },
  8063. enumerable: true,
  8064. configurable: true
  8065. });
  8066. Object.defineProperty(Engine, "ALPHA_ADD", {
  8067. get: function () {
  8068. return Engine._ALPHA_ADD;
  8069. },
  8070. enumerable: true,
  8071. configurable: true
  8072. });
  8073. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8074. get: function () {
  8075. return Engine._ALPHA_COMBINE;
  8076. },
  8077. enumerable: true,
  8078. configurable: true
  8079. });
  8080. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8081. get: function () {
  8082. return Engine._ALPHA_SUBTRACT;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8088. get: function () {
  8089. return Engine._ALPHA_MULTIPLY;
  8090. },
  8091. enumerable: true,
  8092. configurable: true
  8093. });
  8094. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8095. get: function () {
  8096. return Engine._ALPHA_MAXIMIZED;
  8097. },
  8098. enumerable: true,
  8099. configurable: true
  8100. });
  8101. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8102. get: function () {
  8103. return Engine._ALPHA_PREMULTIPLIED;
  8104. },
  8105. enumerable: true,
  8106. configurable: true
  8107. });
  8108. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8109. get: function () {
  8110. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8111. },
  8112. enumerable: true,
  8113. configurable: true
  8114. });
  8115. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8116. get: function () {
  8117. return Engine._ALPHA_INTERPOLATE;
  8118. },
  8119. enumerable: true,
  8120. configurable: true
  8121. });
  8122. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8123. get: function () {
  8124. return Engine._ALPHA_SCREENMODE;
  8125. },
  8126. enumerable: true,
  8127. configurable: true
  8128. });
  8129. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8130. get: function () {
  8131. return Engine._DELAYLOADSTATE_NONE;
  8132. },
  8133. enumerable: true,
  8134. configurable: true
  8135. });
  8136. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8137. get: function () {
  8138. return Engine._DELAYLOADSTATE_LOADED;
  8139. },
  8140. enumerable: true,
  8141. configurable: true
  8142. });
  8143. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8144. get: function () {
  8145. return Engine._DELAYLOADSTATE_LOADING;
  8146. },
  8147. enumerable: true,
  8148. configurable: true
  8149. });
  8150. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8151. get: function () {
  8152. return Engine._DELAYLOADSTATE_NOTLOADED;
  8153. },
  8154. enumerable: true,
  8155. configurable: true
  8156. });
  8157. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8158. get: function () {
  8159. return Engine._TEXTUREFORMAT_ALPHA;
  8160. },
  8161. enumerable: true,
  8162. configurable: true
  8163. });
  8164. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8165. get: function () {
  8166. return Engine._TEXTUREFORMAT_LUMINANCE;
  8167. },
  8168. enumerable: true,
  8169. configurable: true
  8170. });
  8171. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8172. get: function () {
  8173. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8174. },
  8175. enumerable: true,
  8176. configurable: true
  8177. });
  8178. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8179. get: function () {
  8180. return Engine._TEXTUREFORMAT_RGB;
  8181. },
  8182. enumerable: true,
  8183. configurable: true
  8184. });
  8185. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8186. get: function () {
  8187. return Engine._TEXTUREFORMAT_RGBA;
  8188. },
  8189. enumerable: true,
  8190. configurable: true
  8191. });
  8192. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8193. get: function () {
  8194. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8195. },
  8196. enumerable: true,
  8197. configurable: true
  8198. });
  8199. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8200. get: function () {
  8201. return Engine._TEXTURETYPE_FLOAT;
  8202. },
  8203. enumerable: true,
  8204. configurable: true
  8205. });
  8206. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8207. get: function () {
  8208. return Engine._TEXTURETYPE_HALF_FLOAT;
  8209. },
  8210. enumerable: true,
  8211. configurable: true
  8212. });
  8213. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8214. get: function () {
  8215. return Engine._SCALEMODE_FLOOR;
  8216. },
  8217. enumerable: true,
  8218. configurable: true
  8219. });
  8220. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8221. get: function () {
  8222. return Engine._SCALEMODE_NEAREST;
  8223. },
  8224. enumerable: true,
  8225. configurable: true
  8226. });
  8227. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8228. get: function () {
  8229. return Engine._SCALEMODE_CEILING;
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Object.defineProperty(Engine, "Version", {
  8235. get: function () {
  8236. return "3.1-alpha";
  8237. },
  8238. enumerable: true,
  8239. configurable: true
  8240. });
  8241. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8242. get: function () {
  8243. return this._vrExclusivePointerMode;
  8244. },
  8245. enumerable: true,
  8246. configurable: true
  8247. });
  8248. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8249. get: function () {
  8250. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8251. },
  8252. enumerable: true,
  8253. configurable: true
  8254. });
  8255. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8256. get: function () {
  8257. return this._webGLVersion < 2 || this.forcePOTTextures;
  8258. },
  8259. enumerable: true,
  8260. configurable: true
  8261. });
  8262. Object.defineProperty(Engine.prototype, "badOS", {
  8263. get: function () {
  8264. return this._badOS;
  8265. },
  8266. enumerable: true,
  8267. configurable: true
  8268. });
  8269. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8270. get: function () {
  8271. return this._badDesktopOS;
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8277. get: function () {
  8278. return this._performanceMonitor;
  8279. },
  8280. enumerable: true,
  8281. configurable: true
  8282. });
  8283. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8284. get: function () {
  8285. return this._texturesSupported;
  8286. },
  8287. enumerable: true,
  8288. configurable: true
  8289. });
  8290. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8291. get: function () {
  8292. return this._textureFormatInUse;
  8293. },
  8294. enumerable: true,
  8295. configurable: true
  8296. });
  8297. Object.defineProperty(Engine.prototype, "currentViewport", {
  8298. get: function () {
  8299. return this._cachedViewport;
  8300. },
  8301. enumerable: true,
  8302. configurable: true
  8303. });
  8304. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8305. // Empty texture
  8306. get: function () {
  8307. if (!this._emptyTexture) {
  8308. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8309. }
  8310. return this._emptyTexture;
  8311. },
  8312. enumerable: true,
  8313. configurable: true
  8314. });
  8315. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8316. get: function () {
  8317. if (!this._emptyCubeTexture) {
  8318. var faceData = new Uint8Array(4);
  8319. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8320. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8321. }
  8322. return this._emptyCubeTexture;
  8323. },
  8324. enumerable: true,
  8325. configurable: true
  8326. });
  8327. Engine.prototype._rebuildInternalTextures = function () {
  8328. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8329. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8330. var internalTexture = currentState_1[_i];
  8331. internalTexture._rebuild();
  8332. }
  8333. };
  8334. Engine.prototype._rebuildEffects = function () {
  8335. for (var key in this._compiledEffects) {
  8336. var effect = this._compiledEffects[key];
  8337. effect._prepareEffect();
  8338. }
  8339. BABYLON.Effect.ResetCache();
  8340. };
  8341. Engine.prototype._rebuildBuffers = function () {
  8342. // Index / Vertex
  8343. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8344. var scene = _a[_i];
  8345. scene.resetCachedMaterial();
  8346. scene._rebuildGeometries();
  8347. scene._rebuildTextures();
  8348. }
  8349. // Uniforms
  8350. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8351. var uniformBuffer = _c[_b];
  8352. uniformBuffer._rebuild();
  8353. }
  8354. };
  8355. Engine.prototype._initGLContext = function () {
  8356. // Caps
  8357. this._caps = new EngineCapabilities();
  8358. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8359. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8360. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8361. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8362. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8363. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8364. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8365. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8366. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8367. // Infos
  8368. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8369. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8370. if (rendererInfo != null) {
  8371. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8372. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8373. }
  8374. if (!this._glVendor) {
  8375. this._glVendor = "Unknown vendor";
  8376. }
  8377. if (!this._glRenderer) {
  8378. this._glRenderer = "Unknown renderer";
  8379. }
  8380. // Constants
  8381. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8382. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8383. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8384. this._gl.DEPTH24_STENCIL8 = 35056;
  8385. // Extensions
  8386. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8387. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8388. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8389. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8390. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8391. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8392. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8393. 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');
  8394. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8395. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8396. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8397. this._caps.highPrecisionShaderSupported = true;
  8398. // Checks if some of the format renders first to allow the use of webgl inspector.
  8399. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8400. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8401. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8402. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8403. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8404. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8405. if (this._webGLVersion > 1) {
  8406. this._gl.HALF_FLOAT_OES = 0x140B;
  8407. }
  8408. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8409. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8410. // Draw buffers
  8411. if (this._webGLVersion > 1) {
  8412. this._caps.drawBuffersExtension = true;
  8413. }
  8414. else {
  8415. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8416. if (drawBuffersExtension !== null) {
  8417. this._caps.drawBuffersExtension = true;
  8418. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8419. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8420. for (var i = 0; i < 16; i++) {
  8421. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8422. }
  8423. }
  8424. else {
  8425. this._caps.drawBuffersExtension = false;
  8426. }
  8427. }
  8428. // Depth Texture
  8429. if (this._webGLVersion > 1) {
  8430. this._caps.depthTextureExtension = true;
  8431. }
  8432. else {
  8433. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8434. if (depthTextureExtension != null) {
  8435. this._caps.depthTextureExtension = true;
  8436. }
  8437. }
  8438. // Vertex array object
  8439. if (this._webGLVersion > 1) {
  8440. this._caps.vertexArrayObject = true;
  8441. }
  8442. else {
  8443. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8444. if (vertexArrayObjectExtension != null) {
  8445. this._caps.vertexArrayObject = true;
  8446. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8447. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8448. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8449. }
  8450. else {
  8451. this._caps.vertexArrayObject = false;
  8452. }
  8453. }
  8454. // Instances count
  8455. if (this._webGLVersion > 1) {
  8456. this._caps.instancedArrays = true;
  8457. }
  8458. else {
  8459. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8460. if (instanceExtension != null) {
  8461. this._caps.instancedArrays = true;
  8462. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8463. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8464. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8465. }
  8466. else {
  8467. this._caps.instancedArrays = false;
  8468. }
  8469. }
  8470. // Intelligently add supported compressed formats in order to check for.
  8471. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8472. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8473. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8474. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8475. if (this._caps.astc)
  8476. this.texturesSupported.push('-astc.ktx');
  8477. if (this._caps.s3tc)
  8478. this.texturesSupported.push('-dxt.ktx');
  8479. if (this._caps.pvrtc)
  8480. this.texturesSupported.push('-pvrtc.ktx');
  8481. if (this._caps.etc2)
  8482. this.texturesSupported.push('-etc2.ktx');
  8483. if (this._caps.etc1)
  8484. this.texturesSupported.push('-etc1.ktx');
  8485. if (this._gl.getShaderPrecisionFormat) {
  8486. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8487. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8488. }
  8489. // Depth buffer
  8490. this.setDepthBuffer(true);
  8491. this.setDepthFunctionToLessOrEqual();
  8492. this.setDepthWrite(true);
  8493. };
  8494. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8495. get: function () {
  8496. return this._webGLVersion;
  8497. },
  8498. enumerable: true,
  8499. configurable: true
  8500. });
  8501. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8502. /**
  8503. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8504. */
  8505. get: function () {
  8506. return this._isStencilEnable;
  8507. },
  8508. enumerable: true,
  8509. configurable: true
  8510. });
  8511. Engine.prototype._prepareWorkingCanvas = function () {
  8512. if (this._workingCanvas) {
  8513. return;
  8514. }
  8515. this._workingCanvas = document.createElement("canvas");
  8516. this._workingContext = this._workingCanvas.getContext("2d");
  8517. };
  8518. Engine.prototype.resetTextureCache = function () {
  8519. for (var key in this._activeTexturesCache) {
  8520. this._activeTexturesCache[key] = null;
  8521. }
  8522. };
  8523. Engine.prototype.isDeterministicLockStep = function () {
  8524. return this._deterministicLockstep;
  8525. };
  8526. Engine.prototype.getLockstepMaxSteps = function () {
  8527. return this._lockstepMaxSteps;
  8528. };
  8529. Engine.prototype.getGlInfo = function () {
  8530. return {
  8531. vendor: this._glVendor,
  8532. renderer: this._glRenderer,
  8533. version: this._glVersion
  8534. };
  8535. };
  8536. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8537. if (useScreen === void 0) { useScreen = false; }
  8538. var viewport = camera.viewport;
  8539. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8540. };
  8541. Engine.prototype.getRenderWidth = function (useScreen) {
  8542. if (useScreen === void 0) { useScreen = false; }
  8543. if (!useScreen && this._currentRenderTarget) {
  8544. return this._currentRenderTarget.width;
  8545. }
  8546. return this._gl.drawingBufferWidth;
  8547. };
  8548. Engine.prototype.getRenderHeight = function (useScreen) {
  8549. if (useScreen === void 0) { useScreen = false; }
  8550. if (!useScreen && this._currentRenderTarget) {
  8551. return this._currentRenderTarget.height;
  8552. }
  8553. return this._gl.drawingBufferHeight;
  8554. };
  8555. Engine.prototype.getRenderingCanvas = function () {
  8556. return this._renderingCanvas;
  8557. };
  8558. Engine.prototype.getRenderingCanvasClientRect = function () {
  8559. return this._renderingCanvas.getBoundingClientRect();
  8560. };
  8561. Engine.prototype.setHardwareScalingLevel = function (level) {
  8562. this._hardwareScalingLevel = level;
  8563. this.resize();
  8564. };
  8565. Engine.prototype.getHardwareScalingLevel = function () {
  8566. return this._hardwareScalingLevel;
  8567. };
  8568. Engine.prototype.getLoadedTexturesCache = function () {
  8569. return this._internalTexturesCache;
  8570. };
  8571. Engine.prototype.getCaps = function () {
  8572. return this._caps;
  8573. };
  8574. Object.defineProperty(Engine.prototype, "drawCalls", {
  8575. /** The number of draw calls submitted last frame */
  8576. get: function () {
  8577. return this._drawCalls.current;
  8578. },
  8579. enumerable: true,
  8580. configurable: true
  8581. });
  8582. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8583. get: function () {
  8584. return this._drawCalls;
  8585. },
  8586. enumerable: true,
  8587. configurable: true
  8588. });
  8589. Engine.prototype.getDepthFunction = function () {
  8590. return this._depthCullingState.depthFunc;
  8591. };
  8592. Engine.prototype.setDepthFunction = function (depthFunc) {
  8593. this._depthCullingState.depthFunc = depthFunc;
  8594. };
  8595. Engine.prototype.setDepthFunctionToGreater = function () {
  8596. this._depthCullingState.depthFunc = this._gl.GREATER;
  8597. };
  8598. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8599. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8600. };
  8601. Engine.prototype.setDepthFunctionToLess = function () {
  8602. this._depthCullingState.depthFunc = this._gl.LESS;
  8603. };
  8604. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8605. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8606. };
  8607. Engine.prototype.getStencilBuffer = function () {
  8608. return this._stencilState.stencilTest;
  8609. };
  8610. Engine.prototype.setStencilBuffer = function (enable) {
  8611. this._stencilState.stencilTest = enable;
  8612. };
  8613. Engine.prototype.getStencilMask = function () {
  8614. return this._stencilState.stencilMask;
  8615. };
  8616. Engine.prototype.setStencilMask = function (mask) {
  8617. this._stencilState.stencilMask = mask;
  8618. };
  8619. Engine.prototype.getStencilFunction = function () {
  8620. return this._stencilState.stencilFunc;
  8621. };
  8622. Engine.prototype.getStencilFunctionReference = function () {
  8623. return this._stencilState.stencilFuncRef;
  8624. };
  8625. Engine.prototype.getStencilFunctionMask = function () {
  8626. return this._stencilState.stencilFuncMask;
  8627. };
  8628. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8629. this._stencilState.stencilFunc = stencilFunc;
  8630. };
  8631. Engine.prototype.setStencilFunctionReference = function (reference) {
  8632. this._stencilState.stencilFuncRef = reference;
  8633. };
  8634. Engine.prototype.setStencilFunctionMask = function (mask) {
  8635. this._stencilState.stencilFuncMask = mask;
  8636. };
  8637. Engine.prototype.getStencilOperationFail = function () {
  8638. return this._stencilState.stencilOpStencilFail;
  8639. };
  8640. Engine.prototype.getStencilOperationDepthFail = function () {
  8641. return this._stencilState.stencilOpDepthFail;
  8642. };
  8643. Engine.prototype.getStencilOperationPass = function () {
  8644. return this._stencilState.stencilOpStencilDepthPass;
  8645. };
  8646. Engine.prototype.setStencilOperationFail = function (operation) {
  8647. this._stencilState.stencilOpStencilFail = operation;
  8648. };
  8649. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8650. this._stencilState.stencilOpDepthFail = operation;
  8651. };
  8652. Engine.prototype.setStencilOperationPass = function (operation) {
  8653. this._stencilState.stencilOpStencilDepthPass = operation;
  8654. };
  8655. Engine.prototype.setDitheringState = function (value) {
  8656. if (value) {
  8657. this._gl.enable(this._gl.DITHER);
  8658. }
  8659. else {
  8660. this._gl.disable(this._gl.DITHER);
  8661. }
  8662. };
  8663. /**
  8664. * stop executing a render loop function and remove it from the execution array
  8665. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8666. */
  8667. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8668. if (!renderFunction) {
  8669. this._activeRenderLoops = [];
  8670. return;
  8671. }
  8672. var index = this._activeRenderLoops.indexOf(renderFunction);
  8673. if (index >= 0) {
  8674. this._activeRenderLoops.splice(index, 1);
  8675. }
  8676. };
  8677. Engine.prototype._renderLoop = function () {
  8678. if (!this._contextWasLost) {
  8679. var shouldRender = true;
  8680. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8681. shouldRender = false;
  8682. }
  8683. if (shouldRender) {
  8684. // Start new frame
  8685. this.beginFrame();
  8686. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8687. var renderFunction = this._activeRenderLoops[index];
  8688. renderFunction();
  8689. }
  8690. // Present
  8691. this.endFrame();
  8692. }
  8693. }
  8694. if (this._activeRenderLoops.length > 0) {
  8695. // Register new frame
  8696. var requester = window;
  8697. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8698. requester = this._vrDisplay;
  8699. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8700. }
  8701. else {
  8702. this._renderingQueueLaunched = false;
  8703. }
  8704. };
  8705. /**
  8706. * Register and execute a render loop. The engine can have more than one render function.
  8707. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8708. * @example
  8709. * engine.runRenderLoop(function () {
  8710. * scene.render()
  8711. * })
  8712. */
  8713. Engine.prototype.runRenderLoop = function (renderFunction) {
  8714. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8715. return;
  8716. }
  8717. this._activeRenderLoops.push(renderFunction);
  8718. if (!this._renderingQueueLaunched) {
  8719. this._renderingQueueLaunched = true;
  8720. this._bindedRenderFunction = this._renderLoop.bind(this);
  8721. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8722. }
  8723. };
  8724. /**
  8725. * Toggle full screen mode.
  8726. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8727. * @param {any} options - an options object to be sent to the requestFullscreen function
  8728. */
  8729. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8730. if (this.isFullscreen) {
  8731. BABYLON.Tools.ExitFullscreen();
  8732. }
  8733. else {
  8734. this._pointerLockRequested = requestPointerLock;
  8735. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8736. }
  8737. };
  8738. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8739. if (stencil === void 0) { stencil = false; }
  8740. this.applyStates();
  8741. var mode = 0;
  8742. if (backBuffer && color) {
  8743. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8744. mode |= this._gl.COLOR_BUFFER_BIT;
  8745. }
  8746. if (depth) {
  8747. this._gl.clearDepth(1.0);
  8748. mode |= this._gl.DEPTH_BUFFER_BIT;
  8749. }
  8750. if (stencil) {
  8751. this._gl.clearStencil(0);
  8752. mode |= this._gl.STENCIL_BUFFER_BIT;
  8753. }
  8754. this._gl.clear(mode);
  8755. };
  8756. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8757. var gl = this._gl;
  8758. // Save state
  8759. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8760. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8761. // Change state
  8762. gl.enable(gl.SCISSOR_TEST);
  8763. gl.scissor(x, y, width, height);
  8764. // Clear
  8765. this.clear(clearColor, true, true, true);
  8766. // Restore state
  8767. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8768. if (curScissor === true) {
  8769. gl.enable(gl.SCISSOR_TEST);
  8770. }
  8771. else {
  8772. gl.disable(gl.SCISSOR_TEST);
  8773. }
  8774. };
  8775. /**
  8776. * Set the WebGL's viewport
  8777. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8778. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8779. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8780. */
  8781. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8782. var width = requiredWidth || this.getRenderWidth();
  8783. var height = requiredHeight || this.getRenderHeight();
  8784. var x = viewport.x || 0;
  8785. var y = viewport.y || 0;
  8786. this._cachedViewport = viewport;
  8787. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8788. };
  8789. /**
  8790. * Directly set the WebGL Viewport
  8791. * The x, y, width & height are directly passed to the WebGL call
  8792. * @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.
  8793. */
  8794. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8795. var currentViewport = this._cachedViewport;
  8796. this._cachedViewport = null;
  8797. this._gl.viewport(x, y, width, height);
  8798. return currentViewport;
  8799. };
  8800. Engine.prototype.beginFrame = function () {
  8801. this._measureFps();
  8802. };
  8803. Engine.prototype.endFrame = function () {
  8804. //force a flush in case we are using a bad OS.
  8805. if (this._badOS) {
  8806. this.flushFramebuffer();
  8807. }
  8808. //submit frame to the vr device, if enabled
  8809. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8810. // TODO: We should only submit the frame if we read frameData successfully.
  8811. this._vrDisplay.submitFrame();
  8812. }
  8813. };
  8814. /**
  8815. * resize the view according to the canvas' size.
  8816. * @example
  8817. * window.addEventListener("resize", function () {
  8818. * engine.resize();
  8819. * });
  8820. */
  8821. Engine.prototype.resize = function () {
  8822. // We're not resizing the size of the canvas while in VR mode & presenting
  8823. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  8824. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8825. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8826. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8827. }
  8828. };
  8829. /**
  8830. * force a specific size of the canvas
  8831. * @param {number} width - the new canvas' width
  8832. * @param {number} height - the new canvas' height
  8833. */
  8834. Engine.prototype.setSize = function (width, height) {
  8835. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8836. return;
  8837. }
  8838. this._renderingCanvas.width = width;
  8839. this._renderingCanvas.height = height;
  8840. for (var index = 0; index < this.scenes.length; index++) {
  8841. var scene = this.scenes[index];
  8842. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8843. var cam = scene.cameras[camIndex];
  8844. cam._currentRenderId = 0;
  8845. }
  8846. }
  8847. if (this.onResizeObservable.hasObservers) {
  8848. this.onResizeObservable.notifyObservers(this);
  8849. }
  8850. };
  8851. // WebVR functions
  8852. Engine.prototype.isVRDevicePresent = function () {
  8853. return !!this._vrDisplay;
  8854. };
  8855. Engine.prototype.getVRDevice = function () {
  8856. return this._vrDisplay;
  8857. };
  8858. Engine.prototype.initWebVR = function () {
  8859. var _this = this;
  8860. var notifyObservers = function () {
  8861. var eventArgs = {
  8862. vrDisplay: _this._vrDisplay,
  8863. vrSupported: _this._vrSupported
  8864. };
  8865. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  8866. };
  8867. if (!this._onVrDisplayConnect) {
  8868. this._onVrDisplayConnect = function (event) {
  8869. _this._vrDisplay = event.display;
  8870. notifyObservers();
  8871. };
  8872. this._onVrDisplayDisconnect = function () {
  8873. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  8874. _this._vrDisplay = undefined;
  8875. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  8876. notifyObservers();
  8877. };
  8878. this._onVrDisplayPresentChange = function () {
  8879. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  8880. };
  8881. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  8882. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  8883. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  8884. }
  8885. this._getVRDisplays(notifyObservers);
  8886. return this.onVRDisplayChangedObservable;
  8887. };
  8888. Engine.prototype.enableVR = function () {
  8889. var _this = this;
  8890. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  8891. var onResolved = function () {
  8892. _this.onVRRequestPresentComplete.notifyObservers(true);
  8893. _this._onVRFullScreenTriggered();
  8894. };
  8895. var onRejected = function () {
  8896. _this.onVRRequestPresentComplete.notifyObservers(false);
  8897. };
  8898. this.onVRRequestPresentStart.notifyObservers(this);
  8899. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  8900. }
  8901. };
  8902. Engine.prototype.disableVR = function () {
  8903. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8904. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  8905. }
  8906. };
  8907. Engine.prototype._getVRDisplays = function (callback) {
  8908. var _this = this;
  8909. var getWebVRDevices = function (devices) {
  8910. _this._vrSupported = true;
  8911. // note that devices may actually be an empty array. This is fine;
  8912. // we expect this._vrDisplay to be undefined in this case.
  8913. return _this._vrDisplay = devices[0];
  8914. };
  8915. if (navigator.getVRDisplays) {
  8916. // TODO: Backwards compatible for 1.0?
  8917. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  8918. // TODO: System CANNOT support WebVR, despite API presence.
  8919. _this._vrSupported = false;
  8920. callback();
  8921. });
  8922. }
  8923. else {
  8924. // TODO: Browser does not support WebVR
  8925. this._vrDisplay = undefined;
  8926. this._vrSupported = false;
  8927. callback();
  8928. }
  8929. };
  8930. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8931. if (this._currentRenderTarget) {
  8932. this.unBindFramebuffer(this._currentRenderTarget);
  8933. }
  8934. this._currentRenderTarget = texture;
  8935. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8936. var gl = this._gl;
  8937. if (texture.isCube) {
  8938. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8939. }
  8940. if (this._cachedViewport && !forceFullscreenViewport) {
  8941. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8942. }
  8943. else {
  8944. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8945. }
  8946. this.wipeCaches();
  8947. };
  8948. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8949. if (this._currentFramebuffer !== framebuffer) {
  8950. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8951. this._currentFramebuffer = framebuffer;
  8952. }
  8953. };
  8954. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8955. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8956. this._currentRenderTarget = null;
  8957. // If MSAA, we need to bitblt back to main texture
  8958. var gl = this._gl;
  8959. if (texture._MSAAFramebuffer) {
  8960. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8961. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8962. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8963. }
  8964. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8965. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8966. gl.generateMipmap(gl.TEXTURE_2D);
  8967. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8968. }
  8969. if (onBeforeUnbind) {
  8970. if (texture._MSAAFramebuffer) {
  8971. // Bind the correct framebuffer
  8972. this.bindUnboundFramebuffer(texture._framebuffer);
  8973. }
  8974. onBeforeUnbind();
  8975. }
  8976. this.bindUnboundFramebuffer(null);
  8977. };
  8978. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8979. if (texture.generateMipMaps) {
  8980. var gl = this._gl;
  8981. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8982. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8983. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8984. }
  8985. };
  8986. Engine.prototype.flushFramebuffer = function () {
  8987. this._gl.flush();
  8988. };
  8989. Engine.prototype.restoreDefaultFramebuffer = function () {
  8990. if (this._currentRenderTarget) {
  8991. this.unBindFramebuffer(this._currentRenderTarget);
  8992. }
  8993. else {
  8994. this.bindUnboundFramebuffer(null);
  8995. }
  8996. if (this._cachedViewport) {
  8997. this.setViewport(this._cachedViewport);
  8998. }
  8999. this.wipeCaches();
  9000. };
  9001. // UBOs
  9002. Engine.prototype.createUniformBuffer = function (elements) {
  9003. var ubo = this._gl.createBuffer();
  9004. this.bindUniformBuffer(ubo);
  9005. if (elements instanceof Float32Array) {
  9006. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9007. }
  9008. else {
  9009. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9010. }
  9011. this.bindUniformBuffer(null);
  9012. ubo.references = 1;
  9013. return ubo;
  9014. };
  9015. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9016. var ubo = this._gl.createBuffer();
  9017. this.bindUniformBuffer(ubo);
  9018. if (elements instanceof Float32Array) {
  9019. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9020. }
  9021. else {
  9022. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9023. }
  9024. this.bindUniformBuffer(null);
  9025. ubo.references = 1;
  9026. return ubo;
  9027. };
  9028. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9029. this.bindUniformBuffer(uniformBuffer);
  9030. if (offset === undefined) {
  9031. offset = 0;
  9032. }
  9033. if (count === undefined) {
  9034. if (elements instanceof Float32Array) {
  9035. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9036. }
  9037. else {
  9038. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9039. }
  9040. }
  9041. else {
  9042. if (elements instanceof Float32Array) {
  9043. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9044. }
  9045. else {
  9046. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9047. }
  9048. }
  9049. this.bindUniformBuffer(null);
  9050. };
  9051. // VBOs
  9052. Engine.prototype._resetVertexBufferBinding = function () {
  9053. this.bindArrayBuffer(null);
  9054. this._cachedVertexBuffers = null;
  9055. };
  9056. Engine.prototype.createVertexBuffer = function (vertices) {
  9057. var vbo = this._gl.createBuffer();
  9058. this.bindArrayBuffer(vbo);
  9059. if (vertices instanceof Float32Array) {
  9060. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9061. }
  9062. else {
  9063. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9064. }
  9065. this._resetVertexBufferBinding();
  9066. vbo.references = 1;
  9067. return vbo;
  9068. };
  9069. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9070. var vbo = this._gl.createBuffer();
  9071. this.bindArrayBuffer(vbo);
  9072. if (vertices instanceof Float32Array) {
  9073. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9074. }
  9075. else {
  9076. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9077. }
  9078. this._resetVertexBufferBinding();
  9079. vbo.references = 1;
  9080. return vbo;
  9081. };
  9082. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9083. this.bindArrayBuffer(vertexBuffer);
  9084. if (offset === undefined) {
  9085. offset = 0;
  9086. }
  9087. if (count === undefined) {
  9088. if (vertices instanceof Float32Array) {
  9089. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9090. }
  9091. else {
  9092. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9093. }
  9094. }
  9095. else {
  9096. if (vertices instanceof Float32Array) {
  9097. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9098. }
  9099. else {
  9100. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9101. }
  9102. }
  9103. this._resetVertexBufferBinding();
  9104. };
  9105. Engine.prototype._resetIndexBufferBinding = function () {
  9106. this.bindIndexBuffer(null);
  9107. this._cachedIndexBuffer = null;
  9108. };
  9109. Engine.prototype.createIndexBuffer = function (indices) {
  9110. var vbo = this._gl.createBuffer();
  9111. this.bindIndexBuffer(vbo);
  9112. // Check for 32 bits indices
  9113. var arrayBuffer;
  9114. var need32Bits = false;
  9115. if (indices instanceof Uint16Array) {
  9116. arrayBuffer = indices;
  9117. }
  9118. else {
  9119. //check 32 bit support
  9120. if (this._caps.uintIndices) {
  9121. if (indices instanceof Uint32Array) {
  9122. arrayBuffer = indices;
  9123. need32Bits = true;
  9124. }
  9125. else {
  9126. //number[] or Int32Array, check if 32 bit is necessary
  9127. for (var index = 0; index < indices.length; index++) {
  9128. if (indices[index] > 65535) {
  9129. need32Bits = true;
  9130. break;
  9131. }
  9132. }
  9133. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9134. }
  9135. }
  9136. else {
  9137. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9138. arrayBuffer = new Uint16Array(indices);
  9139. }
  9140. }
  9141. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9142. this._resetIndexBufferBinding();
  9143. vbo.references = 1;
  9144. vbo.is32Bits = need32Bits;
  9145. return vbo;
  9146. };
  9147. Engine.prototype.bindArrayBuffer = function (buffer) {
  9148. if (!this._vaoRecordInProgress) {
  9149. this._unbindVertexArrayObject();
  9150. }
  9151. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9152. };
  9153. Engine.prototype.bindUniformBuffer = function (buffer) {
  9154. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9155. };
  9156. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9157. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9158. };
  9159. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9160. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9161. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9162. };
  9163. ;
  9164. Engine.prototype.bindIndexBuffer = function (buffer) {
  9165. if (!this._vaoRecordInProgress) {
  9166. this._unbindVertexArrayObject();
  9167. }
  9168. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9169. };
  9170. Engine.prototype.bindBuffer = function (buffer, target) {
  9171. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9172. this._gl.bindBuffer(target, buffer);
  9173. this._currentBoundBuffer[target] = buffer;
  9174. }
  9175. };
  9176. Engine.prototype.updateArrayBuffer = function (data) {
  9177. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9178. };
  9179. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9180. var pointer = this._currentBufferPointers[indx];
  9181. var changed = false;
  9182. if (!pointer.active) {
  9183. changed = true;
  9184. pointer.active = true;
  9185. pointer.index = indx;
  9186. pointer.size = size;
  9187. pointer.type = type;
  9188. pointer.normalized = normalized;
  9189. pointer.stride = stride;
  9190. pointer.offset = offset;
  9191. pointer.buffer = buffer;
  9192. }
  9193. else {
  9194. if (pointer.buffer !== buffer) {
  9195. pointer.buffer = buffer;
  9196. changed = true;
  9197. }
  9198. if (pointer.size !== size) {
  9199. pointer.size = size;
  9200. changed = true;
  9201. }
  9202. if (pointer.type !== type) {
  9203. pointer.type = type;
  9204. changed = true;
  9205. }
  9206. if (pointer.normalized !== normalized) {
  9207. pointer.normalized = normalized;
  9208. changed = true;
  9209. }
  9210. if (pointer.stride !== stride) {
  9211. pointer.stride = stride;
  9212. changed = true;
  9213. }
  9214. if (pointer.offset !== offset) {
  9215. pointer.offset = offset;
  9216. changed = true;
  9217. }
  9218. }
  9219. if (changed || this._vaoRecordInProgress) {
  9220. this.bindArrayBuffer(buffer);
  9221. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9222. }
  9223. };
  9224. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9225. if (indexBuffer == null) {
  9226. return;
  9227. }
  9228. if (this._cachedIndexBuffer !== indexBuffer) {
  9229. this._cachedIndexBuffer = indexBuffer;
  9230. this.bindIndexBuffer(indexBuffer);
  9231. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9232. }
  9233. };
  9234. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9235. var attributes = effect.getAttributesNames();
  9236. if (!this._vaoRecordInProgress) {
  9237. this._unbindVertexArrayObject();
  9238. }
  9239. this.unbindAllAttributes();
  9240. for (var index = 0; index < attributes.length; index++) {
  9241. var order = effect.getAttributeLocation(index);
  9242. if (order >= 0) {
  9243. var vertexBuffer = vertexBuffers[attributes[index]];
  9244. if (!vertexBuffer) {
  9245. continue;
  9246. }
  9247. this._gl.enableVertexAttribArray(order);
  9248. if (!this._vaoRecordInProgress) {
  9249. this._vertexAttribArraysEnabled[order] = true;
  9250. }
  9251. var buffer = vertexBuffer.getBuffer();
  9252. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9253. if (vertexBuffer.getIsInstanced()) {
  9254. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9255. if (!this._vaoRecordInProgress) {
  9256. this._currentInstanceLocations.push(order);
  9257. this._currentInstanceBuffers.push(buffer);
  9258. }
  9259. }
  9260. }
  9261. }
  9262. };
  9263. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9264. var vao = this._gl.createVertexArray();
  9265. this._vaoRecordInProgress = true;
  9266. this._gl.bindVertexArray(vao);
  9267. this._mustWipeVertexAttributes = true;
  9268. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9269. this.bindIndexBuffer(indexBuffer);
  9270. this._vaoRecordInProgress = false;
  9271. this._gl.bindVertexArray(null);
  9272. return vao;
  9273. };
  9274. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9275. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9276. this._cachedVertexArrayObject = vertexArrayObject;
  9277. this._gl.bindVertexArray(vertexArrayObject);
  9278. this._cachedVertexBuffers = null;
  9279. this._cachedIndexBuffer = null;
  9280. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9281. this._mustWipeVertexAttributes = true;
  9282. }
  9283. };
  9284. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9285. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9286. this._cachedVertexBuffers = vertexBuffer;
  9287. this._cachedEffectForVertexBuffers = effect;
  9288. var attributesCount = effect.getAttributesCount();
  9289. this._unbindVertexArrayObject();
  9290. this.unbindAllAttributes();
  9291. var offset = 0;
  9292. for (var index = 0; index < attributesCount; index++) {
  9293. if (index < vertexDeclaration.length) {
  9294. var order = effect.getAttributeLocation(index);
  9295. if (order >= 0) {
  9296. this._gl.enableVertexAttribArray(order);
  9297. this._vertexAttribArraysEnabled[order] = true;
  9298. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9299. }
  9300. offset += vertexDeclaration[index] * 4;
  9301. }
  9302. }
  9303. }
  9304. this._bindIndexBufferWithCache(indexBuffer);
  9305. };
  9306. Engine.prototype._unbindVertexArrayObject = function () {
  9307. if (!this._cachedVertexArrayObject) {
  9308. return;
  9309. }
  9310. this._cachedVertexArrayObject = null;
  9311. this._gl.bindVertexArray(null);
  9312. };
  9313. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9314. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9315. this._cachedVertexBuffers = vertexBuffers;
  9316. this._cachedEffectForVertexBuffers = effect;
  9317. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9318. }
  9319. this._bindIndexBufferWithCache(indexBuffer);
  9320. };
  9321. Engine.prototype.unbindInstanceAttributes = function () {
  9322. var boundBuffer;
  9323. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9324. var instancesBuffer = this._currentInstanceBuffers[i];
  9325. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9326. boundBuffer = instancesBuffer;
  9327. this.bindArrayBuffer(instancesBuffer);
  9328. }
  9329. var offsetLocation = this._currentInstanceLocations[i];
  9330. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9331. }
  9332. this._currentInstanceBuffers.length = 0;
  9333. this._currentInstanceLocations.length = 0;
  9334. };
  9335. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9336. this._gl.deleteVertexArray(vao);
  9337. };
  9338. Engine.prototype._releaseBuffer = function (buffer) {
  9339. buffer.references--;
  9340. if (buffer.references === 0) {
  9341. this._gl.deleteBuffer(buffer);
  9342. return true;
  9343. }
  9344. return false;
  9345. };
  9346. Engine.prototype.createInstancesBuffer = function (capacity) {
  9347. var buffer = this._gl.createBuffer();
  9348. buffer.capacity = capacity;
  9349. this.bindArrayBuffer(buffer);
  9350. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9351. return buffer;
  9352. };
  9353. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9354. this._gl.deleteBuffer(buffer);
  9355. };
  9356. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9357. this.bindArrayBuffer(instancesBuffer);
  9358. if (data) {
  9359. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9360. }
  9361. if (offsetLocations[0].index !== undefined) {
  9362. var stride = 0;
  9363. for (var i = 0; i < offsetLocations.length; i++) {
  9364. var ai = offsetLocations[i];
  9365. stride += ai.attributeSize * 4;
  9366. }
  9367. for (var i = 0; i < offsetLocations.length; i++) {
  9368. var ai = offsetLocations[i];
  9369. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9370. this._gl.enableVertexAttribArray(ai.index);
  9371. this._vertexAttribArraysEnabled[ai.index] = true;
  9372. }
  9373. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9374. this._gl.vertexAttribDivisor(ai.index, 1);
  9375. this._currentInstanceLocations.push(ai.index);
  9376. this._currentInstanceBuffers.push(instancesBuffer);
  9377. }
  9378. }
  9379. else {
  9380. for (var index = 0; index < 4; index++) {
  9381. var offsetLocation = offsetLocations[index];
  9382. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9383. this._gl.enableVertexAttribArray(offsetLocation);
  9384. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9385. }
  9386. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9387. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9388. this._currentInstanceLocations.push(offsetLocation);
  9389. this._currentInstanceBuffers.push(instancesBuffer);
  9390. }
  9391. }
  9392. };
  9393. Engine.prototype.applyStates = function () {
  9394. this._depthCullingState.apply(this._gl);
  9395. this._stencilState.apply(this._gl);
  9396. this._alphaState.apply(this._gl);
  9397. };
  9398. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9399. // Apply states
  9400. this.applyStates();
  9401. this._drawCalls.addCount(1, false);
  9402. // Render
  9403. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9404. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9405. if (instancesCount) {
  9406. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9407. return;
  9408. }
  9409. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9410. };
  9411. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9412. // Apply states
  9413. this.applyStates();
  9414. this._drawCalls.addCount(1, false);
  9415. if (instancesCount) {
  9416. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9417. return;
  9418. }
  9419. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9420. };
  9421. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9422. // Apply states
  9423. this.applyStates();
  9424. this._drawCalls.addCount(1, false);
  9425. if (instancesCount) {
  9426. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9427. return;
  9428. }
  9429. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9430. };
  9431. // Shaders
  9432. Engine.prototype._releaseEffect = function (effect) {
  9433. if (this._compiledEffects[effect._key]) {
  9434. delete this._compiledEffects[effect._key];
  9435. if (effect.getProgram()) {
  9436. this._gl.deleteProgram(effect.getProgram());
  9437. }
  9438. }
  9439. };
  9440. /**
  9441. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9442. * @param samplers An array of string used to represent textures
  9443. */
  9444. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9445. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9446. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9447. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9448. if (this._compiledEffects[name]) {
  9449. var compiledEffect = this._compiledEffects[name];
  9450. if (onCompiled && compiledEffect.isReady()) {
  9451. onCompiled(compiledEffect);
  9452. }
  9453. return compiledEffect;
  9454. }
  9455. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9456. effect._key = name;
  9457. this._compiledEffects[name] = effect;
  9458. return effect;
  9459. };
  9460. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9461. if (uniformsNames === void 0) { uniformsNames = []; }
  9462. if (samplers === void 0) { samplers = []; }
  9463. if (defines === void 0) { defines = ""; }
  9464. return this.createEffect({
  9465. vertex: "particles",
  9466. fragmentElement: fragmentName
  9467. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9468. };
  9469. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9470. context = context || this._gl;
  9471. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9472. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9473. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9474. var shaderProgram = context.createProgram();
  9475. context.attachShader(shaderProgram, vertexShader);
  9476. context.attachShader(shaderProgram, fragmentShader);
  9477. context.linkProgram(shaderProgram);
  9478. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9479. if (!linked) {
  9480. context.validateProgram(shaderProgram);
  9481. var error = context.getProgramInfoLog(shaderProgram);
  9482. if (error) {
  9483. throw new Error(error);
  9484. }
  9485. }
  9486. context.deleteShader(vertexShader);
  9487. context.deleteShader(fragmentShader);
  9488. return shaderProgram;
  9489. };
  9490. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9491. var results = [];
  9492. for (var index = 0; index < uniformsNames.length; index++) {
  9493. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9494. }
  9495. return results;
  9496. };
  9497. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9498. var results = [];
  9499. for (var index = 0; index < attributesNames.length; index++) {
  9500. try {
  9501. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9502. }
  9503. catch (e) {
  9504. results.push(-1);
  9505. }
  9506. }
  9507. return results;
  9508. };
  9509. Engine.prototype.enableEffect = function (effect) {
  9510. // Use program
  9511. this.setProgram(effect.getProgram());
  9512. this._currentEffect = effect;
  9513. if (effect.onBind) {
  9514. effect.onBind(effect);
  9515. }
  9516. effect.onBindObservable.notifyObservers(effect);
  9517. };
  9518. Engine.prototype.setIntArray = function (uniform, array) {
  9519. if (!uniform)
  9520. return;
  9521. this._gl.uniform1iv(uniform, array);
  9522. };
  9523. Engine.prototype.setIntArray2 = function (uniform, array) {
  9524. if (!uniform || array.length % 2 !== 0)
  9525. return;
  9526. this._gl.uniform2iv(uniform, array);
  9527. };
  9528. Engine.prototype.setIntArray3 = function (uniform, array) {
  9529. if (!uniform || array.length % 3 !== 0)
  9530. return;
  9531. this._gl.uniform3iv(uniform, array);
  9532. };
  9533. Engine.prototype.setIntArray4 = function (uniform, array) {
  9534. if (!uniform || array.length % 4 !== 0)
  9535. return;
  9536. this._gl.uniform4iv(uniform, array);
  9537. };
  9538. Engine.prototype.setFloatArray = function (uniform, array) {
  9539. if (!uniform)
  9540. return;
  9541. this._gl.uniform1fv(uniform, array);
  9542. };
  9543. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9544. if (!uniform || array.length % 2 !== 0)
  9545. return;
  9546. this._gl.uniform2fv(uniform, array);
  9547. };
  9548. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9549. if (!uniform || array.length % 3 !== 0)
  9550. return;
  9551. this._gl.uniform3fv(uniform, array);
  9552. };
  9553. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9554. if (!uniform || array.length % 4 !== 0)
  9555. return;
  9556. this._gl.uniform4fv(uniform, array);
  9557. };
  9558. Engine.prototype.setArray = function (uniform, array) {
  9559. if (!uniform)
  9560. return;
  9561. this._gl.uniform1fv(uniform, array);
  9562. };
  9563. Engine.prototype.setArray2 = function (uniform, array) {
  9564. if (!uniform || array.length % 2 !== 0)
  9565. return;
  9566. this._gl.uniform2fv(uniform, array);
  9567. };
  9568. Engine.prototype.setArray3 = function (uniform, array) {
  9569. if (!uniform || array.length % 3 !== 0)
  9570. return;
  9571. this._gl.uniform3fv(uniform, array);
  9572. };
  9573. Engine.prototype.setArray4 = function (uniform, array) {
  9574. if (!uniform || array.length % 4 !== 0)
  9575. return;
  9576. this._gl.uniform4fv(uniform, array);
  9577. };
  9578. Engine.prototype.setMatrices = function (uniform, matrices) {
  9579. if (!uniform)
  9580. return;
  9581. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9582. };
  9583. Engine.prototype.setMatrix = function (uniform, matrix) {
  9584. if (!uniform)
  9585. return;
  9586. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9587. };
  9588. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9589. if (!uniform)
  9590. return;
  9591. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9592. };
  9593. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9594. if (!uniform)
  9595. return;
  9596. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9597. };
  9598. Engine.prototype.setFloat = function (uniform, value) {
  9599. if (!uniform)
  9600. return;
  9601. this._gl.uniform1f(uniform, value);
  9602. };
  9603. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9604. if (!uniform)
  9605. return;
  9606. this._gl.uniform2f(uniform, x, y);
  9607. };
  9608. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9609. if (!uniform)
  9610. return;
  9611. this._gl.uniform3f(uniform, x, y, z);
  9612. };
  9613. Engine.prototype.setBool = function (uniform, bool) {
  9614. if (!uniform)
  9615. return;
  9616. this._gl.uniform1i(uniform, bool);
  9617. };
  9618. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9619. if (!uniform)
  9620. return;
  9621. this._gl.uniform4f(uniform, x, y, z, w);
  9622. };
  9623. Engine.prototype.setColor3 = function (uniform, color3) {
  9624. if (!uniform)
  9625. return;
  9626. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9627. };
  9628. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9629. if (!uniform)
  9630. return;
  9631. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9632. };
  9633. // States
  9634. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9635. if (zOffset === void 0) { zOffset = 0; }
  9636. if (reverseSide === void 0) { reverseSide = false; }
  9637. // Culling
  9638. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9639. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9640. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9641. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9642. if (culling) {
  9643. this._depthCullingState.cullFace = cullFace;
  9644. this._depthCullingState.cull = true;
  9645. }
  9646. else {
  9647. this._depthCullingState.cull = false;
  9648. }
  9649. }
  9650. // Z offset
  9651. this.setZOffset(zOffset);
  9652. };
  9653. Engine.prototype.setZOffset = function (value) {
  9654. this._depthCullingState.zOffset = value;
  9655. };
  9656. Engine.prototype.getZOffset = function () {
  9657. return this._depthCullingState.zOffset;
  9658. };
  9659. Engine.prototype.setDepthBuffer = function (enable) {
  9660. this._depthCullingState.depthTest = enable;
  9661. };
  9662. Engine.prototype.getDepthWrite = function () {
  9663. return this._depthCullingState.depthMask;
  9664. };
  9665. Engine.prototype.setDepthWrite = function (enable) {
  9666. this._depthCullingState.depthMask = enable;
  9667. };
  9668. Engine.prototype.setColorWrite = function (enable) {
  9669. this._gl.colorMask(enable, enable, enable, enable);
  9670. this._colorWrite = enable;
  9671. };
  9672. Engine.prototype.getColorWrite = function () {
  9673. return this._colorWrite;
  9674. };
  9675. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9676. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9677. };
  9678. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9679. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9680. if (this._alphaMode === mode) {
  9681. return;
  9682. }
  9683. switch (mode) {
  9684. case Engine.ALPHA_DISABLE:
  9685. this._alphaState.alphaBlend = false;
  9686. break;
  9687. case Engine.ALPHA_PREMULTIPLIED:
  9688. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9689. this._alphaState.alphaBlend = true;
  9690. break;
  9691. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9692. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9693. this._alphaState.alphaBlend = true;
  9694. break;
  9695. case Engine.ALPHA_COMBINE:
  9696. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9697. this._alphaState.alphaBlend = true;
  9698. break;
  9699. case Engine.ALPHA_ONEONE:
  9700. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9701. this._alphaState.alphaBlend = true;
  9702. break;
  9703. case Engine.ALPHA_ADD:
  9704. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9705. this._alphaState.alphaBlend = true;
  9706. break;
  9707. case Engine.ALPHA_SUBTRACT:
  9708. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9709. this._alphaState.alphaBlend = true;
  9710. break;
  9711. case Engine.ALPHA_MULTIPLY:
  9712. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9713. this._alphaState.alphaBlend = true;
  9714. break;
  9715. case Engine.ALPHA_MAXIMIZED:
  9716. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9717. this._alphaState.alphaBlend = true;
  9718. break;
  9719. case Engine.ALPHA_INTERPOLATE:
  9720. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9721. this._alphaState.alphaBlend = true;
  9722. break;
  9723. case Engine.ALPHA_SCREENMODE:
  9724. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9725. this._alphaState.alphaBlend = true;
  9726. break;
  9727. }
  9728. if (!noDepthWriteChange) {
  9729. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9730. }
  9731. this._alphaMode = mode;
  9732. };
  9733. Engine.prototype.getAlphaMode = function () {
  9734. return this._alphaMode;
  9735. };
  9736. Engine.prototype.setAlphaTesting = function (enable) {
  9737. this._alphaTest = enable;
  9738. };
  9739. Engine.prototype.getAlphaTesting = function () {
  9740. return !!this._alphaTest;
  9741. };
  9742. // Textures
  9743. Engine.prototype.wipeCaches = function (bruteForce) {
  9744. if (this.preventCacheWipeBetweenFrames) {
  9745. return;
  9746. }
  9747. this.resetTextureCache();
  9748. this._currentEffect = null;
  9749. // 6/8/2017: deltakosh: Should not be required anymore.
  9750. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9751. if (bruteForce) {
  9752. this._currentProgram = null;
  9753. this._stencilState.reset();
  9754. this._depthCullingState.reset();
  9755. this.setDepthFunctionToLessOrEqual();
  9756. this._alphaState.reset();
  9757. }
  9758. this._cachedVertexBuffers = null;
  9759. this._cachedIndexBuffer = null;
  9760. this._cachedEffectForVertexBuffers = null;
  9761. this._unbindVertexArrayObject();
  9762. this.bindIndexBuffer(null);
  9763. this.bindArrayBuffer(null);
  9764. };
  9765. /**
  9766. * Set the compressed texture format to use, based on the formats you have, and the formats
  9767. * supported by the hardware / browser.
  9768. *
  9769. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9770. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9771. * to API arguments needed to compressed textures. This puts the burden on the container
  9772. * generator to house the arcane code for determining these for current & future formats.
  9773. *
  9774. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9775. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9776. *
  9777. * Note: The result of this call is not taken into account when a texture is base64.
  9778. *
  9779. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9780. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9781. *
  9782. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9783. * @returns The extension selected.
  9784. */
  9785. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9786. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9787. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9788. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9789. return this._textureFormatInUse = this._texturesSupported[i];
  9790. }
  9791. }
  9792. }
  9793. // actively set format to nothing, to allow this to be called more than once
  9794. // and possibly fail the 2nd time
  9795. return this._textureFormatInUse = null;
  9796. };
  9797. Engine.prototype._createTexture = function () {
  9798. return this._gl.createTexture();
  9799. };
  9800. /**
  9801. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9802. * @param {string} urlArg- This contains one of the following:
  9803. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9804. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9805. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9806. *
  9807. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9808. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9809. * @param {Scene} scene- Needed for loading to the correct scene.
  9810. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9811. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9812. * @param {callback} onError- Optional callback to be called upon failure.
  9813. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9814. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9815. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9816. *
  9817. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9818. */
  9819. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9820. var _this = this;
  9821. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9822. if (onLoad === void 0) { onLoad = null; }
  9823. if (onError === void 0) { onError = null; }
  9824. if (buffer === void 0) { buffer = null; }
  9825. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9826. var fromData = url.substr(0, 5) === "data:";
  9827. var fromBlob = url.substr(0, 5) === "blob:";
  9828. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9829. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9830. // establish the file extension, if possible
  9831. var lastDot = url.lastIndexOf('.');
  9832. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9833. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9834. var isTGA = (extension === ".tga");
  9835. // determine if a ktx file should be substituted
  9836. var isKTX = false;
  9837. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9838. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9839. isKTX = true;
  9840. }
  9841. if (scene) {
  9842. scene._addPendingData(texture);
  9843. }
  9844. texture.url = url;
  9845. texture.generateMipMaps = !noMipmap;
  9846. texture.samplingMode = samplingMode;
  9847. texture.invertY = invertY;
  9848. if (!this._doNotHandleContextLost) {
  9849. // Keep a link to the buffer only if we plan to handle context lost
  9850. texture._buffer = buffer;
  9851. }
  9852. if (onLoad) {
  9853. texture.onLoadedObservable.add(onLoad);
  9854. }
  9855. if (!fallBack)
  9856. this._internalTexturesCache.push(texture);
  9857. var onerror = function () {
  9858. if (scene) {
  9859. scene._removePendingData(texture);
  9860. }
  9861. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9862. if (isKTX) {
  9863. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9864. }
  9865. else if (onError) {
  9866. onError();
  9867. }
  9868. };
  9869. var callback;
  9870. // processing for non-image formats
  9871. if (isKTX || isTGA || isDDS) {
  9872. if (isKTX) {
  9873. callback = function (data) {
  9874. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9875. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9876. ktx.uploadLevels(_this._gl, !noMipmap);
  9877. return false;
  9878. }, samplingMode);
  9879. };
  9880. }
  9881. else if (isTGA) {
  9882. callback = function (arrayBuffer) {
  9883. var data = new Uint8Array(arrayBuffer);
  9884. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9885. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9886. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9887. return false;
  9888. }, samplingMode);
  9889. };
  9890. }
  9891. else if (isDDS) {
  9892. callback = function (data) {
  9893. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9894. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9895. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9896. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9897. return false;
  9898. }, samplingMode);
  9899. };
  9900. }
  9901. if (!buffer) {
  9902. BABYLON.Tools.LoadFile(url, function (data) {
  9903. callback(data);
  9904. }, null, scene ? scene.database : null, true, onerror);
  9905. }
  9906. else {
  9907. callback(buffer);
  9908. }
  9909. // image format processing
  9910. }
  9911. else {
  9912. var onload = function (img) {
  9913. if (fromBlob && !_this._doNotHandleContextLost) {
  9914. // We need to store the image if we need to rebuild the texture
  9915. // in case of a webgl context lost
  9916. texture._buffer = img;
  9917. }
  9918. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9919. var gl = _this._gl;
  9920. var isPot = (img.width === potWidth && img.height === potHeight);
  9921. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9922. if (isPot) {
  9923. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9924. return false;
  9925. }
  9926. // Using shaders to rescale because canvas.drawImage is lossy
  9927. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9928. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9929. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9930. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9931. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9932. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9933. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9934. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9935. _this._releaseTexture(source);
  9936. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9937. continuationCallback();
  9938. });
  9939. return true;
  9940. }, samplingMode);
  9941. };
  9942. if (!fromData || isBase64)
  9943. if (buffer instanceof HTMLImageElement) {
  9944. onload(buffer);
  9945. }
  9946. else {
  9947. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9948. }
  9949. else if (buffer instanceof Array || typeof buffer === "string")
  9950. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9951. else
  9952. onload(buffer);
  9953. }
  9954. return texture;
  9955. };
  9956. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9957. var _this = this;
  9958. var rtt = this.createRenderTargetTexture({
  9959. width: destination.width,
  9960. height: destination.height,
  9961. }, {
  9962. generateMipMaps: false,
  9963. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9964. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9965. generateDepthBuffer: false,
  9966. generateStencilBuffer: false
  9967. });
  9968. if (!this._rescalePostProcess) {
  9969. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9970. }
  9971. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9972. _this._rescalePostProcess.onApply = function (effect) {
  9973. effect._bindTexture("textureSampler", source);
  9974. };
  9975. var hostingScene = scene;
  9976. if (!hostingScene) {
  9977. hostingScene = _this.scenes[_this.scenes.length - 1];
  9978. }
  9979. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9980. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9981. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9982. _this.unBindFramebuffer(rtt);
  9983. _this._releaseTexture(rtt);
  9984. if (onComplete) {
  9985. onComplete();
  9986. }
  9987. });
  9988. };
  9989. Engine.prototype._getInternalFormat = function (format) {
  9990. var internalFormat = this._gl.RGBA;
  9991. switch (format) {
  9992. case Engine.TEXTUREFORMAT_ALPHA:
  9993. internalFormat = this._gl.ALPHA;
  9994. break;
  9995. case Engine.TEXTUREFORMAT_LUMINANCE:
  9996. internalFormat = this._gl.LUMINANCE;
  9997. break;
  9998. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9999. internalFormat = this._gl.LUMINANCE_ALPHA;
  10000. break;
  10001. case Engine.TEXTUREFORMAT_RGB:
  10002. internalFormat = this._gl.RGB;
  10003. break;
  10004. case Engine.TEXTUREFORMAT_RGBA:
  10005. internalFormat = this._gl.RGBA;
  10006. break;
  10007. }
  10008. return internalFormat;
  10009. };
  10010. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10011. if (compression === void 0) { compression = null; }
  10012. var internalFormat = this._getInternalFormat(format);
  10013. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10014. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10015. if (!this._doNotHandleContextLost) {
  10016. texture._bufferView = data;
  10017. texture.format = format;
  10018. texture.invertY = invertY;
  10019. texture._compression = compression;
  10020. }
  10021. if (texture.width % 4 !== 0) {
  10022. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10023. }
  10024. if (compression) {
  10025. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10026. }
  10027. else {
  10028. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10029. }
  10030. if (texture.generateMipMaps) {
  10031. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10032. }
  10033. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10034. this.resetTextureCache();
  10035. texture.isReady = true;
  10036. };
  10037. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10038. if (compression === void 0) { compression = null; }
  10039. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10040. texture.baseWidth = width;
  10041. texture.baseHeight = height;
  10042. texture.width = width;
  10043. texture.height = height;
  10044. texture.format = format;
  10045. texture.generateMipMaps = generateMipMaps;
  10046. texture.samplingMode = samplingMode;
  10047. texture.invertY = invertY;
  10048. texture._compression = compression;
  10049. if (!this._doNotHandleContextLost) {
  10050. texture._bufferView = data;
  10051. }
  10052. this.updateRawTexture(texture, data, format, invertY, compression);
  10053. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10054. // Filters
  10055. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10056. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10057. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10058. if (generateMipMaps) {
  10059. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10060. }
  10061. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10062. this._internalTexturesCache.push(texture);
  10063. return texture;
  10064. };
  10065. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10066. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10067. texture.baseWidth = width;
  10068. texture.baseHeight = height;
  10069. if (generateMipMaps) {
  10070. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10071. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10072. }
  10073. this.resetTextureCache();
  10074. texture.width = width;
  10075. texture.height = height;
  10076. texture.isReady = false;
  10077. texture.generateMipMaps = generateMipMaps;
  10078. texture.samplingMode = samplingMode;
  10079. this.updateTextureSamplingMode(samplingMode, texture);
  10080. this._internalTexturesCache.push(texture);
  10081. return texture;
  10082. };
  10083. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10084. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10085. if (texture.isCube) {
  10086. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10087. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10088. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10089. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10090. }
  10091. else {
  10092. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10093. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10094. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10095. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10096. }
  10097. texture.samplingMode = samplingMode;
  10098. };
  10099. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10100. if (premulAlpha === void 0) { premulAlpha = false; }
  10101. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10102. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10103. if (premulAlpha) {
  10104. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10105. }
  10106. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10107. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10108. if (texture.generateMipMaps) {
  10109. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10110. }
  10111. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10112. if (premulAlpha) {
  10113. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10114. }
  10115. this.resetTextureCache();
  10116. texture.isReady = true;
  10117. };
  10118. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10119. if (texture._isDisabled) {
  10120. return;
  10121. }
  10122. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10123. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10124. try {
  10125. // Testing video texture support
  10126. if (this._videoTextureSupported === undefined) {
  10127. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10128. if (this._gl.getError() !== 0) {
  10129. this._videoTextureSupported = false;
  10130. }
  10131. else {
  10132. this._videoTextureSupported = true;
  10133. }
  10134. }
  10135. // Copy video through the current working canvas if video texture is not supported
  10136. if (!this._videoTextureSupported) {
  10137. if (!texture._workingCanvas) {
  10138. texture._workingCanvas = document.createElement("canvas");
  10139. texture._workingContext = texture._workingCanvas.getContext("2d");
  10140. texture._workingCanvas.width = texture.width;
  10141. texture._workingCanvas.height = texture.height;
  10142. }
  10143. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10144. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10145. }
  10146. else {
  10147. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10148. }
  10149. if (texture.generateMipMaps) {
  10150. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10151. }
  10152. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10153. this.resetTextureCache();
  10154. texture.isReady = true;
  10155. }
  10156. catch (ex) {
  10157. // Something unexpected
  10158. // Let's disable the texture
  10159. texture._isDisabled = true;
  10160. }
  10161. };
  10162. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10163. var fullOptions = new RenderTargetCreationOptions();
  10164. if (options !== undefined && typeof options === "object") {
  10165. fullOptions.generateMipMaps = options.generateMipMaps;
  10166. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10167. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10168. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10169. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10170. }
  10171. else {
  10172. fullOptions.generateMipMaps = options;
  10173. fullOptions.generateDepthBuffer = true;
  10174. fullOptions.generateStencilBuffer = false;
  10175. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10176. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10177. }
  10178. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10179. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10180. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10181. }
  10182. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10183. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10184. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10185. }
  10186. var gl = this._gl;
  10187. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10188. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10189. var width = size.width || size;
  10190. var height = size.height || size;
  10191. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10192. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10193. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10194. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10195. }
  10196. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10197. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10200. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10201. // Create the framebuffer
  10202. var framebuffer = gl.createFramebuffer();
  10203. this.bindUnboundFramebuffer(framebuffer);
  10204. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10205. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10206. if (fullOptions.generateMipMaps) {
  10207. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10208. }
  10209. // Unbind
  10210. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10211. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10212. this.bindUnboundFramebuffer(null);
  10213. texture._framebuffer = framebuffer;
  10214. texture.baseWidth = width;
  10215. texture.baseHeight = height;
  10216. texture.width = width;
  10217. texture.height = height;
  10218. texture.isReady = true;
  10219. texture.samples = 1;
  10220. texture.generateMipMaps = fullOptions.generateMipMaps;
  10221. texture.samplingMode = fullOptions.samplingMode;
  10222. texture.type = fullOptions.type;
  10223. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10224. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10225. this.resetTextureCache();
  10226. this._internalTexturesCache.push(texture);
  10227. return texture;
  10228. };
  10229. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10230. var generateMipMaps = false;
  10231. var generateDepthBuffer = true;
  10232. var generateStencilBuffer = false;
  10233. var generateDepthTexture = false;
  10234. var textureCount = 1;
  10235. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10236. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10237. var types = [], samplingModes = [];
  10238. if (options !== undefined) {
  10239. generateMipMaps = options.generateMipMaps;
  10240. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10241. generateStencilBuffer = options.generateStencilBuffer;
  10242. generateDepthTexture = options.generateDepthTexture;
  10243. textureCount = options.textureCount || 1;
  10244. if (options.types) {
  10245. types = options.types;
  10246. }
  10247. if (options.samplingModes) {
  10248. samplingModes = options.samplingModes;
  10249. }
  10250. }
  10251. var gl = this._gl;
  10252. // Create the framebuffer
  10253. var framebuffer = gl.createFramebuffer();
  10254. this.bindUnboundFramebuffer(framebuffer);
  10255. var width = size.width || size;
  10256. var height = size.height || size;
  10257. var textures = [];
  10258. var attachments = [];
  10259. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10260. for (var i = 0; i < textureCount; i++) {
  10261. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10262. var type = types[i] || defaultType;
  10263. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10264. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10265. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10266. }
  10267. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10268. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10269. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10270. }
  10271. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10272. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10273. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10274. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10275. }
  10276. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10277. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10278. textures.push(texture);
  10279. attachments.push(attachment);
  10280. gl.activeTexture(gl["TEXTURE" + i]);
  10281. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10286. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10287. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10288. if (generateMipMaps) {
  10289. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10290. }
  10291. // Unbind
  10292. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10293. texture._framebuffer = framebuffer;
  10294. texture._depthStencilBuffer = depthStencilBuffer;
  10295. texture.baseWidth = width;
  10296. texture.baseHeight = height;
  10297. texture.width = width;
  10298. texture.height = height;
  10299. texture.isReady = true;
  10300. texture.samples = 1;
  10301. texture.generateMipMaps = generateMipMaps;
  10302. texture.samplingMode = samplingMode;
  10303. texture.type = type;
  10304. texture._generateDepthBuffer = generateDepthBuffer;
  10305. texture._generateStencilBuffer = generateStencilBuffer;
  10306. this._internalTexturesCache.push(texture);
  10307. }
  10308. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10309. // Depth texture
  10310. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10311. gl.activeTexture(gl.TEXTURE0);
  10312. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10313. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10314. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10315. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10316. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10317. 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);
  10318. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10319. depthTexture._framebuffer = framebuffer;
  10320. depthTexture.baseWidth = width;
  10321. depthTexture.baseHeight = height;
  10322. depthTexture.width = width;
  10323. depthTexture.height = height;
  10324. depthTexture.isReady = true;
  10325. depthTexture.samples = 1;
  10326. depthTexture.generateMipMaps = generateMipMaps;
  10327. depthTexture.samplingMode = gl.NEAREST;
  10328. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10329. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10330. textures.push(depthTexture);
  10331. this._internalTexturesCache.push(depthTexture);
  10332. }
  10333. gl.drawBuffers(attachments);
  10334. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10335. this.bindUnboundFramebuffer(null);
  10336. this.resetTextureCache();
  10337. return textures;
  10338. };
  10339. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10340. if (samples === void 0) { samples = 1; }
  10341. var depthStencilBuffer = null;
  10342. var gl = this._gl;
  10343. // Create the depth/stencil buffer
  10344. if (generateStencilBuffer) {
  10345. depthStencilBuffer = gl.createRenderbuffer();
  10346. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10347. if (samples > 1) {
  10348. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10349. }
  10350. else {
  10351. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10352. }
  10353. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10354. }
  10355. else if (generateDepthBuffer) {
  10356. depthStencilBuffer = gl.createRenderbuffer();
  10357. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10358. if (samples > 1) {
  10359. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10360. }
  10361. else {
  10362. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10363. }
  10364. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10365. }
  10366. return depthStencilBuffer;
  10367. };
  10368. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10369. if (this.webGLVersion < 2) {
  10370. return 1;
  10371. }
  10372. if (texture.samples === samples) {
  10373. return samples;
  10374. }
  10375. var gl = this._gl;
  10376. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10377. // Dispose previous render buffers
  10378. if (texture._depthStencilBuffer) {
  10379. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10380. }
  10381. if (texture._MSAAFramebuffer) {
  10382. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10383. }
  10384. if (texture._MSAARenderBuffer) {
  10385. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10386. }
  10387. if (samples > 1) {
  10388. texture._MSAAFramebuffer = gl.createFramebuffer();
  10389. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10390. var colorRenderbuffer = gl.createRenderbuffer();
  10391. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10392. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10393. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10394. texture._MSAARenderBuffer = colorRenderbuffer;
  10395. }
  10396. else {
  10397. this.bindUnboundFramebuffer(texture._framebuffer);
  10398. }
  10399. texture.samples = samples;
  10400. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10401. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10402. this.bindUnboundFramebuffer(null);
  10403. return samples;
  10404. };
  10405. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10406. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10407. };
  10408. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10409. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10410. };
  10411. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10412. var gl = this._gl;
  10413. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10414. var generateMipMaps = true;
  10415. var generateDepthBuffer = true;
  10416. var generateStencilBuffer = false;
  10417. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10418. if (options !== undefined) {
  10419. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10420. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10421. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10422. if (options.samplingMode !== undefined) {
  10423. samplingMode = options.samplingMode;
  10424. }
  10425. }
  10426. texture.isCube = true;
  10427. texture.generateMipMaps = generateMipMaps;
  10428. texture.samples = 1;
  10429. texture.samplingMode = samplingMode;
  10430. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10431. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10432. for (var face = 0; face < 6; face++) {
  10433. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10434. }
  10435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10438. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10439. // Create the framebuffer
  10440. var framebuffer = gl.createFramebuffer();
  10441. this.bindUnboundFramebuffer(framebuffer);
  10442. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10443. // Mipmaps
  10444. if (texture.generateMipMaps) {
  10445. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10446. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10447. }
  10448. // Unbind
  10449. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10450. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10451. this.bindUnboundFramebuffer(null);
  10452. texture._framebuffer = framebuffer;
  10453. texture.width = size;
  10454. texture.height = size;
  10455. texture.isReady = true;
  10456. this.resetTextureCache();
  10457. this._internalTexturesCache.push(texture);
  10458. return texture;
  10459. };
  10460. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10461. var _this = this;
  10462. if (onError === void 0) { onError = null; }
  10463. if (forcedExtension === void 0) { forcedExtension = null; }
  10464. var callback = function (loadData) {
  10465. if (!loadData) {
  10466. if (onLoad) {
  10467. onLoad(null);
  10468. }
  10469. return;
  10470. }
  10471. var texture = loadData.texture;
  10472. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10473. texture._lodGenerationScale = scale;
  10474. texture._lodGenerationOffset = offset;
  10475. if (_this._caps.textureLOD) {
  10476. // Do not add extra process if texture lod is supported.
  10477. if (onLoad) {
  10478. onLoad(texture);
  10479. }
  10480. return;
  10481. }
  10482. var mipSlices = 3;
  10483. var gl = _this._gl;
  10484. var width = loadData.width;
  10485. if (!width) {
  10486. return;
  10487. }
  10488. var textures = [];
  10489. for (var i = 0; i < mipSlices; i++) {
  10490. //compute LOD from even spacing in smoothness (matching shader calculation)
  10491. var smoothness = i / (mipSlices - 1);
  10492. var roughness = 1 - smoothness;
  10493. var minLODIndex = offset; // roughness = 0
  10494. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10495. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10496. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10497. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10498. glTextureFromLod.isCube = true;
  10499. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10504. if (loadData.isDDS) {
  10505. var info = loadData.info;
  10506. var data = loadData.data;
  10507. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10508. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10509. }
  10510. else {
  10511. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10512. }
  10513. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10514. // Wrap in a base texture for easy binding.
  10515. var lodTexture = new BABYLON.BaseTexture(scene);
  10516. lodTexture.isCube = true;
  10517. lodTexture._texture = glTextureFromLod;
  10518. glTextureFromLod.isReady = true;
  10519. textures.push(lodTexture);
  10520. }
  10521. texture._lodTextureHigh = textures[2];
  10522. texture._lodTextureMid = textures[1];
  10523. texture._lodTextureLow = textures[0];
  10524. if (onLoad) {
  10525. onLoad(texture);
  10526. }
  10527. };
  10528. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10529. };
  10530. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10531. var _this = this;
  10532. if (onLoad === void 0) { onLoad = null; }
  10533. if (onError === void 0) { onError = null; }
  10534. if (forcedExtension === void 0) { forcedExtension = null; }
  10535. var gl = this._gl;
  10536. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10537. texture.isCube = true;
  10538. texture.url = rootUrl;
  10539. texture.generateMipMaps = !noMipmap;
  10540. if (!this._doNotHandleContextLost) {
  10541. texture._extension = forcedExtension;
  10542. texture._files = files;
  10543. }
  10544. var isKTX = false;
  10545. var isDDS = false;
  10546. var lastDot = rootUrl.lastIndexOf('.');
  10547. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10548. if (this._textureFormatInUse) {
  10549. extension = this._textureFormatInUse;
  10550. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10551. isKTX = true;
  10552. }
  10553. else {
  10554. isDDS = (extension === ".dds");
  10555. }
  10556. var onerror = function (request, exception) {
  10557. if (onError) {
  10558. onError(request.status + " " + request.statusText, exception);
  10559. }
  10560. };
  10561. if (isKTX) {
  10562. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10563. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10564. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10565. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10566. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10567. ktx.uploadLevels(_this._gl, !noMipmap);
  10568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10572. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10573. _this.resetTextureCache();
  10574. texture.width = ktx.pixelWidth;
  10575. texture.height = ktx.pixelHeight;
  10576. texture.isReady = true;
  10577. }, null, null, true, onerror);
  10578. }
  10579. else if (isDDS) {
  10580. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10581. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10582. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10583. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10584. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10585. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10586. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10587. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10588. }
  10589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10592. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10593. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10594. _this.resetTextureCache();
  10595. texture.width = info.width;
  10596. texture.height = info.height;
  10597. texture.isReady = true;
  10598. texture.type = info.textureType;
  10599. if (onLoad) {
  10600. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10601. }
  10602. }, null, null, true, onerror);
  10603. }
  10604. else {
  10605. cascadeLoad(rootUrl, scene, function (imgs) {
  10606. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10607. var height = width;
  10608. _this._prepareWorkingCanvas();
  10609. _this._workingCanvas.width = width;
  10610. _this._workingCanvas.height = height;
  10611. var faces = [
  10612. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10613. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10614. ];
  10615. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10616. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10617. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10618. for (var index = 0; index < faces.length; index++) {
  10619. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10620. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10621. }
  10622. if (!noMipmap) {
  10623. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10624. }
  10625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10628. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10629. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10630. _this.resetTextureCache();
  10631. texture.width = width;
  10632. texture.height = height;
  10633. texture.isReady = true;
  10634. texture.format = format;
  10635. texture.onLoadedObservable.notifyObservers(texture);
  10636. texture.onLoadedObservable.clear();
  10637. if (onLoad) {
  10638. onLoad();
  10639. }
  10640. }, files, onError);
  10641. }
  10642. this._internalTexturesCache.push(texture);
  10643. return texture;
  10644. };
  10645. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10646. if (compression === void 0) { compression = null; }
  10647. if (level === void 0) { level = 0; }
  10648. texture._bufferViewArray = data;
  10649. texture.format = format;
  10650. texture.type = type;
  10651. texture.invertY = invertY;
  10652. texture._compression = compression;
  10653. var gl = this._gl;
  10654. var textureType = this._getWebGLTextureType(type);
  10655. var internalFormat = this._getInternalFormat(format);
  10656. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10657. var needConversion = false;
  10658. if (internalFormat === gl.RGB) {
  10659. internalFormat = gl.RGBA;
  10660. needConversion = true;
  10661. }
  10662. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10663. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10664. if (texture.width % 4 !== 0) {
  10665. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10666. }
  10667. // Data are known to be in +X +Y +Z -X -Y -Z
  10668. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10669. var faceData = data[faceIndex];
  10670. if (compression) {
  10671. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10672. }
  10673. else {
  10674. if (needConversion) {
  10675. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10676. }
  10677. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10678. }
  10679. }
  10680. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10681. if (isPot && texture.generateMipMaps && level === 0) {
  10682. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10683. }
  10684. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10685. this.resetTextureCache();
  10686. texture.isReady = true;
  10687. };
  10688. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10689. if (compression === void 0) { compression = null; }
  10690. var gl = this._gl;
  10691. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10692. texture.isCube = true;
  10693. texture.generateMipMaps = generateMipMaps;
  10694. texture.format = format;
  10695. texture.type = type;
  10696. if (!this._doNotHandleContextLost) {
  10697. texture._bufferViewArray = data;
  10698. }
  10699. var textureType = this._getWebGLTextureType(type);
  10700. var internalFormat = this._getInternalFormat(format);
  10701. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10702. var needConversion = false;
  10703. if (internalFormat === gl.RGB) {
  10704. internalFormat = gl.RGBA;
  10705. needConversion = true;
  10706. }
  10707. var width = size;
  10708. var height = width;
  10709. texture.width = width;
  10710. texture.height = height;
  10711. // Double check on POT to generate Mips.
  10712. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10713. if (!isPot) {
  10714. generateMipMaps = false;
  10715. }
  10716. // Upload data if needed. The texture won't be ready until then.
  10717. if (data) {
  10718. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10719. }
  10720. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10721. // Filters
  10722. if (data && generateMipMaps) {
  10723. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10724. }
  10725. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10728. }
  10729. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10732. }
  10733. else {
  10734. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10737. }
  10738. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10739. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10740. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10741. return texture;
  10742. };
  10743. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10744. var _this = this;
  10745. if (onLoad === void 0) { onLoad = null; }
  10746. if (onError === void 0) { onError = null; }
  10747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10748. if (invertY === void 0) { invertY = false; }
  10749. var gl = this._gl;
  10750. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10751. scene._addPendingData(texture);
  10752. texture.url = url;
  10753. this._internalTexturesCache.push(texture);
  10754. var onerror = function (request, exception) {
  10755. scene._removePendingData(texture);
  10756. if (onError) {
  10757. onError(request.status + " " + request.statusText, exception);
  10758. }
  10759. };
  10760. var internalCallback = function (data) {
  10761. var width = texture.width;
  10762. var height = texture.height;
  10763. var faceDataArrays = callback(data);
  10764. if (mipmmapGenerator) {
  10765. var textureType = _this._getWebGLTextureType(type);
  10766. var internalFormat = _this._getInternalFormat(format);
  10767. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10768. var needConversion = false;
  10769. if (internalFormat === gl.RGB) {
  10770. internalFormat = gl.RGBA;
  10771. needConversion = true;
  10772. }
  10773. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10774. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10775. var mipData = mipmmapGenerator(faceDataArrays);
  10776. for (var level = 0; level < mipData.length; level++) {
  10777. var mipSize = width >> level;
  10778. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10779. var mipFaceData = mipData[level][faceIndex];
  10780. if (needConversion) {
  10781. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10782. }
  10783. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10784. }
  10785. }
  10786. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10787. }
  10788. else {
  10789. texture.generateMipMaps = !noMipmap;
  10790. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10791. }
  10792. texture.isReady = true;
  10793. _this.resetTextureCache();
  10794. scene._removePendingData(texture);
  10795. if (onLoad) {
  10796. onLoad();
  10797. }
  10798. };
  10799. BABYLON.Tools.LoadFile(url, function (data) {
  10800. internalCallback(data);
  10801. }, undefined, scene.database, true, onerror);
  10802. return texture;
  10803. };
  10804. ;
  10805. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10806. var gl = this._gl;
  10807. if (!gl) {
  10808. return;
  10809. }
  10810. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10811. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10813. if (!noMipmap && !isCompressed) {
  10814. gl.generateMipmap(gl.TEXTURE_2D);
  10815. }
  10816. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10817. this.resetTextureCache();
  10818. if (scene) {
  10819. scene._removePendingData(texture);
  10820. }
  10821. texture.onLoadedObservable.notifyObservers(texture);
  10822. texture.onLoadedObservable.clear();
  10823. };
  10824. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10825. var _this = this;
  10826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10827. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10828. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10829. var gl = this._gl;
  10830. if (!gl) {
  10831. return;
  10832. }
  10833. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10834. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10835. texture.baseWidth = width;
  10836. texture.baseHeight = height;
  10837. texture.width = potWidth;
  10838. texture.height = potHeight;
  10839. texture.isReady = true;
  10840. if (processFunction(potWidth, potHeight, function () {
  10841. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10842. })) {
  10843. // Returning as texture needs extra async steps
  10844. return;
  10845. }
  10846. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10847. };
  10848. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10849. // Create new RGBA data container.
  10850. var rgbaData;
  10851. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10852. rgbaData = new Float32Array(width * height * 4);
  10853. }
  10854. else {
  10855. rgbaData = new Uint32Array(width * height * 4);
  10856. }
  10857. // Convert each pixel.
  10858. for (var x = 0; x < width; x++) {
  10859. for (var y = 0; y < height; y++) {
  10860. var index = (y * width + x) * 3;
  10861. var newIndex = (y * width + x) * 4;
  10862. // Map Old Value to new value.
  10863. rgbaData[newIndex + 0] = rgbData[index + 0];
  10864. rgbaData[newIndex + 1] = rgbData[index + 1];
  10865. rgbaData[newIndex + 2] = rgbData[index + 2];
  10866. // Add fully opaque alpha channel.
  10867. rgbaData[newIndex + 3] = 1;
  10868. }
  10869. }
  10870. return rgbaData;
  10871. };
  10872. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10873. var gl = this._gl;
  10874. if (texture._framebuffer) {
  10875. gl.deleteFramebuffer(texture._framebuffer);
  10876. texture._framebuffer = null;
  10877. }
  10878. if (texture._depthStencilBuffer) {
  10879. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10880. texture._depthStencilBuffer = null;
  10881. }
  10882. if (texture._MSAAFramebuffer) {
  10883. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10884. texture._MSAAFramebuffer = null;
  10885. }
  10886. if (texture._MSAARenderBuffer) {
  10887. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10888. texture._MSAARenderBuffer = null;
  10889. }
  10890. };
  10891. Engine.prototype._releaseTexture = function (texture) {
  10892. var gl = this._gl;
  10893. this._releaseFramebufferObjects(texture);
  10894. gl.deleteTexture(texture._webGLTexture);
  10895. // Unbind channels
  10896. this.unbindAllTextures();
  10897. var index = this._internalTexturesCache.indexOf(texture);
  10898. if (index !== -1) {
  10899. this._internalTexturesCache.splice(index, 1);
  10900. }
  10901. // Integrated fixed lod samplers.
  10902. if (texture._lodTextureHigh) {
  10903. texture._lodTextureHigh.dispose();
  10904. }
  10905. if (texture._lodTextureMid) {
  10906. texture._lodTextureMid.dispose();
  10907. }
  10908. if (texture._lodTextureLow) {
  10909. texture._lodTextureLow.dispose();
  10910. }
  10911. };
  10912. Engine.prototype.setProgram = function (program) {
  10913. if (this._currentProgram !== program) {
  10914. this._gl.useProgram(program);
  10915. this._currentProgram = program;
  10916. }
  10917. };
  10918. Engine.prototype.bindSamplers = function (effect) {
  10919. this.setProgram(effect.getProgram());
  10920. var samplers = effect.getSamplers();
  10921. for (var index = 0; index < samplers.length; index++) {
  10922. var uniform = effect.getUniform(samplers[index]);
  10923. this._gl.uniform1i(uniform, index);
  10924. }
  10925. this._currentEffect = null;
  10926. };
  10927. Engine.prototype.activateTexture = function (texture) {
  10928. if (this._activeTexture !== texture) {
  10929. this._gl.activeTexture(texture);
  10930. this._activeTexture = texture;
  10931. }
  10932. };
  10933. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10934. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10935. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10936. this._activeTexturesCache[this._activeTexture] = texture;
  10937. }
  10938. };
  10939. Engine.prototype._bindTexture = function (channel, texture) {
  10940. if (channel < 0) {
  10941. return;
  10942. }
  10943. this.activateTexture(this._gl.TEXTURE0 + channel);
  10944. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10945. };
  10946. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10947. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10948. };
  10949. Engine.prototype.unbindAllTextures = function () {
  10950. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10951. this.activateTexture(this._gl["TEXTURE" + channel]);
  10952. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10953. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10954. }
  10955. };
  10956. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10957. if (channel < 0) {
  10958. return;
  10959. }
  10960. this._gl.uniform1i(uniform, channel);
  10961. this._setTexture(channel, texture);
  10962. };
  10963. Engine.prototype._setTexture = function (channel, texture) {
  10964. // Not ready?
  10965. if (!texture) {
  10966. if (this._activeTexturesCache[channel] != null) {
  10967. this.activateTexture(this._gl["TEXTURE" + channel]);
  10968. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10969. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10970. }
  10971. return;
  10972. }
  10973. // Video
  10974. var alreadyActivated = false;
  10975. if (texture.video) {
  10976. this.activateTexture(this._gl["TEXTURE" + channel]);
  10977. alreadyActivated = true;
  10978. texture.update();
  10979. }
  10980. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10981. texture.delayLoad();
  10982. return;
  10983. }
  10984. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10985. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10986. if (this._activeTexturesCache[channel] === internalTexture) {
  10987. return;
  10988. }
  10989. if (!alreadyActivated) {
  10990. this.activateTexture(this._gl["TEXTURE" + channel]);
  10991. }
  10992. if (internalTexture.isCube) {
  10993. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10994. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10995. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10996. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10997. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10998. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10999. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11000. }
  11001. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11002. }
  11003. else {
  11004. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11005. if (internalTexture._cachedWrapU !== texture.wrapU) {
  11006. internalTexture._cachedWrapU = texture.wrapU;
  11007. switch (texture.wrapU) {
  11008. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11009. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11010. break;
  11011. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11012. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11013. break;
  11014. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11015. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11016. break;
  11017. }
  11018. }
  11019. if (internalTexture._cachedWrapV !== texture.wrapV) {
  11020. internalTexture._cachedWrapV = texture.wrapV;
  11021. switch (texture.wrapV) {
  11022. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11023. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11024. break;
  11025. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11026. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11027. break;
  11028. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11029. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11030. break;
  11031. }
  11032. }
  11033. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11034. }
  11035. };
  11036. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11037. if (channel < 0) {
  11038. return;
  11039. }
  11040. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11041. this._textureUnits = new Int32Array(textures.length);
  11042. }
  11043. for (var i = 0; i < textures.length; i++) {
  11044. this._textureUnits[i] = channel + i;
  11045. }
  11046. this._gl.uniform1iv(uniform, this._textureUnits);
  11047. for (var index = 0; index < textures.length; index++) {
  11048. this._setTexture(channel + index, textures[index]);
  11049. }
  11050. };
  11051. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11052. var internalTexture = texture.getInternalTexture();
  11053. if (!internalTexture) {
  11054. return;
  11055. }
  11056. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11057. var value = texture.anisotropicFilteringLevel;
  11058. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11059. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11060. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11061. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11062. }
  11063. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11064. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11065. internalTexture._cachedAnisotropicFilteringLevel = value;
  11066. }
  11067. };
  11068. Engine.prototype.readPixels = function (x, y, width, height) {
  11069. var data = new Uint8Array(height * width * 4);
  11070. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11071. return data;
  11072. };
  11073. /**
  11074. * Add an externaly attached data from its key.
  11075. * This method call will fail and return false, if such key already exists.
  11076. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11077. * @param key the unique key that identifies the data
  11078. * @param data the data object to associate to the key for this Engine instance
  11079. * @return true if no such key were already present and the data was added successfully, false otherwise
  11080. */
  11081. Engine.prototype.addExternalData = function (key, data) {
  11082. if (!this._externalData) {
  11083. this._externalData = new BABYLON.StringDictionary();
  11084. }
  11085. return this._externalData.add(key, data);
  11086. };
  11087. /**
  11088. * Get an externaly attached data from its key
  11089. * @param key the unique key that identifies the data
  11090. * @return the associated data, if present (can be null), or undefined if not present
  11091. */
  11092. Engine.prototype.getExternalData = function (key) {
  11093. if (!this._externalData) {
  11094. this._externalData = new BABYLON.StringDictionary();
  11095. }
  11096. return this._externalData.get(key);
  11097. };
  11098. /**
  11099. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11100. * @param key the unique key that identifies the data
  11101. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11102. * @return the associated data, can be null if the factory returned null.
  11103. */
  11104. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11105. if (!this._externalData) {
  11106. this._externalData = new BABYLON.StringDictionary();
  11107. }
  11108. return this._externalData.getOrAddWithFactory(key, factory);
  11109. };
  11110. /**
  11111. * Remove an externaly attached data from the Engine instance
  11112. * @param key the unique key that identifies the data
  11113. * @return true if the data was successfully removed, false if it doesn't exist
  11114. */
  11115. Engine.prototype.removeExternalData = function (key) {
  11116. if (!this._externalData) {
  11117. this._externalData = new BABYLON.StringDictionary();
  11118. }
  11119. return this._externalData.remove(key);
  11120. };
  11121. Engine.prototype.unbindAllAttributes = function () {
  11122. if (this._mustWipeVertexAttributes) {
  11123. this._mustWipeVertexAttributes = false;
  11124. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11125. this._gl.disableVertexAttribArray(i);
  11126. this._vertexAttribArraysEnabled[i] = false;
  11127. this._currentBufferPointers[i].active = false;
  11128. }
  11129. return;
  11130. }
  11131. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11132. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11133. continue;
  11134. }
  11135. this._gl.disableVertexAttribArray(i);
  11136. this._vertexAttribArraysEnabled[i] = false;
  11137. this._currentBufferPointers[i].active = false;
  11138. }
  11139. };
  11140. Engine.prototype.releaseEffects = function () {
  11141. for (var name in this._compiledEffects) {
  11142. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11143. }
  11144. this._compiledEffects = {};
  11145. };
  11146. // Dispose
  11147. Engine.prototype.dispose = function () {
  11148. this.hideLoadingUI();
  11149. this.stopRenderLoop();
  11150. // Release postProcesses
  11151. while (this.postProcesses.length) {
  11152. this.postProcesses[0].dispose();
  11153. }
  11154. // Empty texture
  11155. if (this._emptyTexture) {
  11156. this._releaseTexture(this._emptyTexture);
  11157. this._emptyTexture = null;
  11158. }
  11159. if (this._emptyCubeTexture) {
  11160. this._releaseTexture(this._emptyCubeTexture);
  11161. this._emptyCubeTexture = null;
  11162. }
  11163. // Rescale PP
  11164. if (this._rescalePostProcess) {
  11165. this._rescalePostProcess.dispose();
  11166. }
  11167. // Release scenes
  11168. while (this.scenes.length) {
  11169. this.scenes[0].dispose();
  11170. }
  11171. // Release audio engine
  11172. if (Engine.audioEngine) {
  11173. Engine.audioEngine.dispose();
  11174. }
  11175. // Release effects
  11176. this.releaseEffects();
  11177. // Unbind
  11178. this.unbindAllAttributes();
  11179. if (this._dummyFramebuffer) {
  11180. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11181. }
  11182. this._gl = null;
  11183. //WebVR
  11184. this.disableVR();
  11185. // Events
  11186. window.removeEventListener("blur", this._onBlur);
  11187. window.removeEventListener("focus", this._onFocus);
  11188. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11189. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11190. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11191. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11192. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11193. if (!this._doNotHandleContextLost) {
  11194. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11195. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11196. }
  11197. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11198. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11199. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11200. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11201. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11202. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11203. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11204. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11205. if (this._onVrDisplayConnect) {
  11206. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11207. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11208. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11209. this._onVrDisplayConnect = undefined;
  11210. this._onVrDisplayDisconnect = undefined;
  11211. }
  11212. // Remove from Instances
  11213. var index = Engine.Instances.indexOf(this);
  11214. if (index >= 0) {
  11215. Engine.Instances.splice(index, 1);
  11216. }
  11217. this._workingCanvas = null;
  11218. this._workingContext = null;
  11219. this._currentBufferPointers = null;
  11220. this._renderingCanvas = null;
  11221. this._currentProgram = null;
  11222. this.onResizeObservable.clear();
  11223. this.onCanvasBlurObservable.clear();
  11224. this.onCanvasFocusObservable.clear();
  11225. this.onCanvasPointerOutObservable.clear();
  11226. BABYLON.Effect.ResetCache();
  11227. };
  11228. // Loading screen
  11229. Engine.prototype.displayLoadingUI = function () {
  11230. var loadingScreen = this.loadingScreen;
  11231. if (loadingScreen) {
  11232. loadingScreen.displayLoadingUI();
  11233. }
  11234. };
  11235. Engine.prototype.hideLoadingUI = function () {
  11236. var loadingScreen = this.loadingScreen;
  11237. if (loadingScreen) {
  11238. loadingScreen.hideLoadingUI();
  11239. }
  11240. };
  11241. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11242. get: function () {
  11243. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11244. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11245. return this._loadingScreen;
  11246. },
  11247. set: function (loadingScreen) {
  11248. this._loadingScreen = loadingScreen;
  11249. },
  11250. enumerable: true,
  11251. configurable: true
  11252. });
  11253. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11254. set: function (text) {
  11255. this.loadingScreen.loadingUIText = text;
  11256. },
  11257. enumerable: true,
  11258. configurable: true
  11259. });
  11260. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11261. set: function (color) {
  11262. this.loadingScreen.loadingUIBackgroundColor = color;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. Engine.prototype.attachContextLostEvent = function (callback) {
  11268. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11269. };
  11270. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11271. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11272. };
  11273. Engine.prototype.getVertexShaderSource = function (program) {
  11274. var shaders = this._gl.getAttachedShaders(program);
  11275. return this._gl.getShaderSource(shaders[0]);
  11276. };
  11277. Engine.prototype.getFragmentShaderSource = function (program) {
  11278. var shaders = this._gl.getAttachedShaders(program);
  11279. return this._gl.getShaderSource(shaders[1]);
  11280. };
  11281. Engine.prototype.getError = function () {
  11282. return this._gl.getError();
  11283. };
  11284. // FPS
  11285. Engine.prototype.getFps = function () {
  11286. return this._fps;
  11287. };
  11288. Engine.prototype.getDeltaTime = function () {
  11289. return this._deltaTime;
  11290. };
  11291. Engine.prototype._measureFps = function () {
  11292. this._performanceMonitor.sampleFrame();
  11293. this._fps = this._performanceMonitor.averageFPS;
  11294. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11295. };
  11296. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11297. if (faceIndex === void 0) { faceIndex = -1; }
  11298. var gl = this._gl;
  11299. if (!this._dummyFramebuffer) {
  11300. this._dummyFramebuffer = gl.createFramebuffer();
  11301. }
  11302. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11303. if (faceIndex > -1) {
  11304. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11305. }
  11306. else {
  11307. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11308. }
  11309. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11310. var buffer;
  11311. switch (readType) {
  11312. case gl.UNSIGNED_BYTE:
  11313. buffer = new Uint8Array(4 * width * height);
  11314. readType = gl.UNSIGNED_BYTE;
  11315. break;
  11316. default:
  11317. buffer = new Float32Array(4 * width * height);
  11318. readType = gl.FLOAT;
  11319. break;
  11320. }
  11321. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11322. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11323. return buffer;
  11324. };
  11325. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11326. if (this._webGLVersion > 1) {
  11327. return this._caps.colorBufferFloat;
  11328. }
  11329. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11330. };
  11331. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11332. if (this._webGLVersion > 1) {
  11333. return this._caps.colorBufferFloat;
  11334. }
  11335. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11336. };
  11337. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11338. Engine.prototype._canRenderToFramebuffer = function (type) {
  11339. var gl = this._gl;
  11340. //clear existing errors
  11341. while (gl.getError() !== gl.NO_ERROR) { }
  11342. var successful = true;
  11343. var texture = gl.createTexture();
  11344. gl.bindTexture(gl.TEXTURE_2D, texture);
  11345. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11347. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11348. var fb = gl.createFramebuffer();
  11349. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11350. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11351. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11352. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11353. successful = successful && (gl.getError() === gl.NO_ERROR);
  11354. //try render by clearing frame buffer's color buffer
  11355. if (successful) {
  11356. gl.clear(gl.COLOR_BUFFER_BIT);
  11357. successful = successful && (gl.getError() === gl.NO_ERROR);
  11358. }
  11359. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11360. if (successful) {
  11361. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11362. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11363. var readFormat = gl.RGBA;
  11364. var readType = gl.UNSIGNED_BYTE;
  11365. var buffer = new Uint8Array(4);
  11366. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11367. successful = successful && (gl.getError() === gl.NO_ERROR);
  11368. }
  11369. //clean up
  11370. gl.deleteTexture(texture);
  11371. gl.deleteFramebuffer(fb);
  11372. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11373. //clear accumulated errors
  11374. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11375. return successful;
  11376. };
  11377. Engine.prototype._getWebGLTextureType = function (type) {
  11378. if (type === Engine.TEXTURETYPE_FLOAT) {
  11379. return this._gl.FLOAT;
  11380. }
  11381. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11382. // Add Half Float Constant.
  11383. return this._gl.HALF_FLOAT_OES;
  11384. }
  11385. return this._gl.UNSIGNED_BYTE;
  11386. };
  11387. ;
  11388. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11389. if (this._webGLVersion === 1) {
  11390. return this._gl.RGBA;
  11391. }
  11392. if (type === Engine.TEXTURETYPE_FLOAT) {
  11393. return this._gl.RGBA32F;
  11394. }
  11395. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11396. return this._gl.RGBA16F;
  11397. }
  11398. return this._gl.RGBA;
  11399. };
  11400. ;
  11401. Engine.prototype.createQuery = function () {
  11402. return this._gl.createQuery();
  11403. };
  11404. Engine.prototype.deleteQuery = function (query) {
  11405. this._gl.deleteQuery(query);
  11406. return this;
  11407. };
  11408. Engine.prototype.isQueryResultAvailable = function (query) {
  11409. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11410. };
  11411. Engine.prototype.getQueryResult = function (query) {
  11412. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11413. };
  11414. Engine.prototype.beginQuery = function (algorithmType, query) {
  11415. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11416. this._gl.beginQuery(glAlgorithm, query);
  11417. };
  11418. Engine.prototype.endQuery = function (algorithmType) {
  11419. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11420. this._gl.endQuery(glAlgorithm);
  11421. return this;
  11422. };
  11423. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11424. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11425. };
  11426. // Statics
  11427. Engine.isSupported = function () {
  11428. try {
  11429. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11430. if (navigator.isCocoonJS) {
  11431. return true;
  11432. }
  11433. var tempcanvas = document.createElement("canvas");
  11434. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11435. return gl != null && !!window.WebGLRenderingContext;
  11436. }
  11437. catch (e) {
  11438. return false;
  11439. }
  11440. };
  11441. Engine.Instances = new Array();
  11442. // Const statics
  11443. Engine._ALPHA_DISABLE = 0;
  11444. Engine._ALPHA_ADD = 1;
  11445. Engine._ALPHA_COMBINE = 2;
  11446. Engine._ALPHA_SUBTRACT = 3;
  11447. Engine._ALPHA_MULTIPLY = 4;
  11448. Engine._ALPHA_MAXIMIZED = 5;
  11449. Engine._ALPHA_ONEONE = 6;
  11450. Engine._ALPHA_PREMULTIPLIED = 7;
  11451. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11452. Engine._ALPHA_INTERPOLATE = 9;
  11453. Engine._ALPHA_SCREENMODE = 10;
  11454. Engine._DELAYLOADSTATE_NONE = 0;
  11455. Engine._DELAYLOADSTATE_LOADED = 1;
  11456. Engine._DELAYLOADSTATE_LOADING = 2;
  11457. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11458. Engine._TEXTUREFORMAT_ALPHA = 0;
  11459. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11460. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11461. Engine._TEXTUREFORMAT_RGB = 4;
  11462. Engine._TEXTUREFORMAT_RGBA = 5;
  11463. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11464. Engine._TEXTURETYPE_FLOAT = 1;
  11465. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11466. // Depht or Stencil test Constants.
  11467. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11468. 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.
  11469. 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.
  11470. 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.
  11471. 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.
  11472. 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.
  11473. 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.
  11474. 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.
  11475. // Stencil Actions Constants.
  11476. Engine._KEEP = 0x1E00;
  11477. Engine._REPLACE = 0x1E01;
  11478. Engine._INCR = 0x1E02;
  11479. Engine._DECR = 0x1E03;
  11480. Engine._INVERT = 0x150A;
  11481. Engine._INCR_WRAP = 0x8507;
  11482. Engine._DECR_WRAP = 0x8508;
  11483. // Texture rescaling mode
  11484. Engine._SCALEMODE_FLOOR = 1;
  11485. Engine._SCALEMODE_NEAREST = 2;
  11486. Engine._SCALEMODE_CEILING = 3;
  11487. // Updatable statics so stick with vars here
  11488. Engine.CollisionsEpsilon = 0.001;
  11489. Engine.CodeRepository = "src/";
  11490. Engine.ShadersRepository = "src/Shaders/";
  11491. return Engine;
  11492. }());
  11493. BABYLON.Engine = Engine;
  11494. })(BABYLON || (BABYLON = {}));
  11495. //# sourceMappingURL=babylon.engine.js.map
  11496. /// <reference path="Tools\babylon.decorators.ts" />
  11497. var BABYLON;
  11498. (function (BABYLON) {
  11499. /**
  11500. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11501. */
  11502. var Node = (function () {
  11503. /**
  11504. * @constructor
  11505. * @param {string} name - the name and id to be given to this node
  11506. * @param {BABYLON.Scene} the scene this node will be added to
  11507. */
  11508. function Node(name, scene) {
  11509. this.state = "";
  11510. this.metadata = null;
  11511. this.doNotSerialize = false;
  11512. this.animations = new Array();
  11513. this._ranges = {};
  11514. this._childrenFlag = -1;
  11515. this._isEnabled = true;
  11516. this._isReady = true;
  11517. this._currentRenderId = -1;
  11518. this._parentRenderId = -1;
  11519. /**
  11520. * An event triggered when the mesh is disposed.
  11521. * @type {BABYLON.Observable}
  11522. */
  11523. this.onDisposeObservable = new BABYLON.Observable();
  11524. // Behaviors
  11525. this._behaviors = new Array();
  11526. this.name = name;
  11527. this.id = name;
  11528. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11529. this.uniqueId = this._scene.getUniqueId();
  11530. this._initCache();
  11531. }
  11532. Object.defineProperty(Node.prototype, "parent", {
  11533. get: function () {
  11534. return this._parentNode;
  11535. },
  11536. set: function (parent) {
  11537. if (this._parentNode === parent) {
  11538. return;
  11539. }
  11540. if (this._parentNode) {
  11541. var index = this._parentNode._children.indexOf(this);
  11542. if (index !== -1) {
  11543. this._parentNode._children.splice(index, 1);
  11544. }
  11545. }
  11546. this._parentNode = parent;
  11547. if (this._parentNode) {
  11548. if (!this._parentNode._children) {
  11549. this._parentNode._children = new Array();
  11550. }
  11551. this._parentNode._children.push(this);
  11552. }
  11553. },
  11554. enumerable: true,
  11555. configurable: true
  11556. });
  11557. Node.prototype.getClassName = function () {
  11558. return "Node";
  11559. };
  11560. Object.defineProperty(Node.prototype, "onDispose", {
  11561. set: function (callback) {
  11562. if (this._onDisposeObserver) {
  11563. this.onDisposeObservable.remove(this._onDisposeObserver);
  11564. }
  11565. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11566. },
  11567. enumerable: true,
  11568. configurable: true
  11569. });
  11570. Node.prototype.getScene = function () {
  11571. return this._scene;
  11572. };
  11573. Node.prototype.getEngine = function () {
  11574. return this._scene.getEngine();
  11575. };
  11576. Node.prototype.addBehavior = function (behavior) {
  11577. var index = this._behaviors.indexOf(behavior);
  11578. if (index !== -1) {
  11579. return;
  11580. }
  11581. behavior.attach(this);
  11582. this._behaviors.push(behavior);
  11583. return this;
  11584. };
  11585. Node.prototype.removeBehavior = function (behavior) {
  11586. var index = this._behaviors.indexOf(behavior);
  11587. if (index === -1) {
  11588. return;
  11589. }
  11590. this._behaviors[index].detach();
  11591. this._behaviors.splice(index, 1);
  11592. return this;
  11593. };
  11594. Object.defineProperty(Node.prototype, "behaviors", {
  11595. get: function () {
  11596. return this._behaviors;
  11597. },
  11598. enumerable: true,
  11599. configurable: true
  11600. });
  11601. Node.prototype.getBehaviorByName = function (name) {
  11602. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11603. var behavior = _a[_i];
  11604. if (behavior.name === name) {
  11605. return behavior;
  11606. }
  11607. }
  11608. return null;
  11609. };
  11610. // override it in derived class
  11611. Node.prototype.getWorldMatrix = function () {
  11612. return BABYLON.Matrix.Identity();
  11613. };
  11614. // override it in derived class if you add new variables to the cache
  11615. // and call the parent class method
  11616. Node.prototype._initCache = function () {
  11617. this._cache = {};
  11618. this._cache.parent = undefined;
  11619. };
  11620. Node.prototype.updateCache = function (force) {
  11621. if (!force && this.isSynchronized())
  11622. return;
  11623. this._cache.parent = this.parent;
  11624. this._updateCache();
  11625. };
  11626. // override it in derived class if you add new variables to the cache
  11627. // and call the parent class method if !ignoreParentClass
  11628. Node.prototype._updateCache = function (ignoreParentClass) {
  11629. };
  11630. // override it in derived class if you add new variables to the cache
  11631. Node.prototype._isSynchronized = function () {
  11632. return true;
  11633. };
  11634. Node.prototype._markSyncedWithParent = function () {
  11635. this._parentRenderId = this.parent._currentRenderId;
  11636. };
  11637. Node.prototype.isSynchronizedWithParent = function () {
  11638. if (!this.parent) {
  11639. return true;
  11640. }
  11641. if (this._parentRenderId !== this.parent._currentRenderId) {
  11642. return false;
  11643. }
  11644. return this.parent.isSynchronized();
  11645. };
  11646. Node.prototype.isSynchronized = function (updateCache) {
  11647. var check = this.hasNewParent();
  11648. check = check || !this.isSynchronizedWithParent();
  11649. check = check || !this._isSynchronized();
  11650. if (updateCache)
  11651. this.updateCache(true);
  11652. return !check;
  11653. };
  11654. Node.prototype.hasNewParent = function (update) {
  11655. if (this._cache.parent === this.parent)
  11656. return false;
  11657. if (update)
  11658. this._cache.parent = this.parent;
  11659. return true;
  11660. };
  11661. /**
  11662. * Is this node ready to be used/rendered
  11663. * @return {boolean} is it ready
  11664. */
  11665. Node.prototype.isReady = function () {
  11666. return this._isReady;
  11667. };
  11668. /**
  11669. * Is this node enabled.
  11670. * If the node has a parent and is enabled, the parent will be inspected as well.
  11671. * @return {boolean} whether this node (and its parent) is enabled.
  11672. * @see setEnabled
  11673. */
  11674. Node.prototype.isEnabled = function () {
  11675. if (!this._isEnabled) {
  11676. return false;
  11677. }
  11678. if (this.parent) {
  11679. return this.parent.isEnabled();
  11680. }
  11681. return true;
  11682. };
  11683. /**
  11684. * Set the enabled state of this node.
  11685. * @param {boolean} value - the new enabled state
  11686. * @see isEnabled
  11687. */
  11688. Node.prototype.setEnabled = function (value) {
  11689. this._isEnabled = value;
  11690. };
  11691. /**
  11692. * Is this node a descendant of the given node.
  11693. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11694. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11695. * @see parent
  11696. */
  11697. Node.prototype.isDescendantOf = function (ancestor) {
  11698. if (this.parent) {
  11699. if (this.parent === ancestor) {
  11700. return true;
  11701. }
  11702. return this.parent.isDescendantOf(ancestor);
  11703. }
  11704. return false;
  11705. };
  11706. /**
  11707. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11708. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11709. * @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.
  11710. * @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.
  11711. */
  11712. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11713. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11714. if (!this._children) {
  11715. return;
  11716. }
  11717. for (var index = 0; index < this._children.length; index++) {
  11718. var item = this._children[index];
  11719. if (!predicate || predicate(item)) {
  11720. results.push(item);
  11721. }
  11722. if (!directDescendantsOnly) {
  11723. item._getDescendants(results, false, predicate);
  11724. }
  11725. }
  11726. };
  11727. /**
  11728. * Will return all nodes that have this node as ascendant.
  11729. * @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.
  11730. * @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.
  11731. * @return {BABYLON.Node[]} all children nodes of all types.
  11732. */
  11733. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11734. var results = [];
  11735. this._getDescendants(results, directDescendantsOnly, predicate);
  11736. return results;
  11737. };
  11738. /**
  11739. * Get all child-meshes of this node.
  11740. */
  11741. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11742. var results = [];
  11743. this._getDescendants(results, directDecendantsOnly, function (node) {
  11744. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11745. });
  11746. return results;
  11747. };
  11748. /**
  11749. * Get all direct children of this node.
  11750. */
  11751. Node.prototype.getChildren = function (predicate) {
  11752. return this.getDescendants(true, predicate);
  11753. };
  11754. Node.prototype._setReady = function (state) {
  11755. if (state === this._isReady) {
  11756. return;
  11757. }
  11758. if (!state) {
  11759. this._isReady = false;
  11760. return;
  11761. }
  11762. this._isReady = true;
  11763. if (this.onReady) {
  11764. this.onReady(this);
  11765. }
  11766. };
  11767. Node.prototype.getAnimationByName = function (name) {
  11768. for (var i = 0; i < this.animations.length; i++) {
  11769. var animation = this.animations[i];
  11770. if (animation.name === name) {
  11771. return animation;
  11772. }
  11773. }
  11774. return null;
  11775. };
  11776. Node.prototype.createAnimationRange = function (name, from, to) {
  11777. // check name not already in use
  11778. if (!this._ranges[name]) {
  11779. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11780. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11781. if (this.animations[i]) {
  11782. this.animations[i].createRange(name, from, to);
  11783. }
  11784. }
  11785. }
  11786. };
  11787. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11788. if (deleteFrames === void 0) { deleteFrames = true; }
  11789. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11790. if (this.animations[i]) {
  11791. this.animations[i].deleteRange(name, deleteFrames);
  11792. }
  11793. }
  11794. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11795. };
  11796. Node.prototype.getAnimationRange = function (name) {
  11797. return this._ranges[name];
  11798. };
  11799. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11800. var range = this.getAnimationRange(name);
  11801. if (!range) {
  11802. return null;
  11803. }
  11804. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11805. };
  11806. Node.prototype.serializeAnimationRanges = function () {
  11807. var serializationRanges = [];
  11808. for (var name in this._ranges) {
  11809. var range = {};
  11810. range.name = name;
  11811. range.from = this._ranges[name].from;
  11812. range.to = this._ranges[name].to;
  11813. serializationRanges.push(range);
  11814. }
  11815. return serializationRanges;
  11816. };
  11817. Node.prototype.dispose = function () {
  11818. this.parent = null;
  11819. // Callback
  11820. this.onDisposeObservable.notifyObservers(this);
  11821. this.onDisposeObservable.clear();
  11822. // Behaviors
  11823. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11824. var behavior = _a[_i];
  11825. behavior.detach();
  11826. }
  11827. this._behaviors = [];
  11828. };
  11829. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11830. if (parsedNode.ranges) {
  11831. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11832. var data = parsedNode.ranges[index];
  11833. node.createAnimationRange(data.name, data.from, data.to);
  11834. }
  11835. }
  11836. };
  11837. __decorate([
  11838. BABYLON.serialize()
  11839. ], Node.prototype, "name", void 0);
  11840. __decorate([
  11841. BABYLON.serialize()
  11842. ], Node.prototype, "id", void 0);
  11843. __decorate([
  11844. BABYLON.serialize()
  11845. ], Node.prototype, "uniqueId", void 0);
  11846. __decorate([
  11847. BABYLON.serialize()
  11848. ], Node.prototype, "state", void 0);
  11849. __decorate([
  11850. BABYLON.serialize()
  11851. ], Node.prototype, "metadata", void 0);
  11852. return Node;
  11853. }());
  11854. BABYLON.Node = Node;
  11855. })(BABYLON || (BABYLON = {}));
  11856. //# sourceMappingURL=babylon.node.js.map
  11857. var BABYLON;
  11858. (function (BABYLON) {
  11859. var BoundingSphere = (function () {
  11860. function BoundingSphere(minimum, maximum) {
  11861. this.minimum = minimum;
  11862. this.maximum = maximum;
  11863. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11864. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11865. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11866. this.radius = distance * 0.5;
  11867. this.centerWorld = BABYLON.Vector3.Zero();
  11868. this._update(BABYLON.Matrix.Identity());
  11869. }
  11870. // Methods
  11871. BoundingSphere.prototype._update = function (world) {
  11872. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11873. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11874. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11875. };
  11876. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11877. for (var i = 0; i < 6; i++) {
  11878. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11879. return false;
  11880. }
  11881. return true;
  11882. };
  11883. BoundingSphere.prototype.intersectsPoint = function (point) {
  11884. var x = this.centerWorld.x - point.x;
  11885. var y = this.centerWorld.y - point.y;
  11886. var z = this.centerWorld.z - point.z;
  11887. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11888. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11889. return false;
  11890. return true;
  11891. };
  11892. // Statics
  11893. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11894. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11895. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11896. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11897. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11898. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11899. return false;
  11900. return true;
  11901. };
  11902. return BoundingSphere;
  11903. }());
  11904. BABYLON.BoundingSphere = BoundingSphere;
  11905. })(BABYLON || (BABYLON = {}));
  11906. //# sourceMappingURL=babylon.boundingSphere.js.map
  11907. var BABYLON;
  11908. (function (BABYLON) {
  11909. var BoundingBox = (function () {
  11910. function BoundingBox(minimum, maximum) {
  11911. this.minimum = minimum;
  11912. this.maximum = maximum;
  11913. this.vectors = new Array();
  11914. this.vectorsWorld = new Array();
  11915. // Bounding vectors
  11916. this.vectors.push(this.minimum.clone());
  11917. this.vectors.push(this.maximum.clone());
  11918. this.vectors.push(this.minimum.clone());
  11919. this.vectors[2].x = this.maximum.x;
  11920. this.vectors.push(this.minimum.clone());
  11921. this.vectors[3].y = this.maximum.y;
  11922. this.vectors.push(this.minimum.clone());
  11923. this.vectors[4].z = this.maximum.z;
  11924. this.vectors.push(this.maximum.clone());
  11925. this.vectors[5].z = this.minimum.z;
  11926. this.vectors.push(this.maximum.clone());
  11927. this.vectors[6].x = this.minimum.x;
  11928. this.vectors.push(this.maximum.clone());
  11929. this.vectors[7].y = this.minimum.y;
  11930. // OBB
  11931. this.center = this.maximum.add(this.minimum).scale(0.5);
  11932. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11933. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11934. // World
  11935. for (var index = 0; index < this.vectors.length; index++) {
  11936. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11937. }
  11938. this.minimumWorld = BABYLON.Vector3.Zero();
  11939. this.maximumWorld = BABYLON.Vector3.Zero();
  11940. this.centerWorld = BABYLON.Vector3.Zero();
  11941. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11942. this._update(BABYLON.Matrix.Identity());
  11943. }
  11944. // Methods
  11945. BoundingBox.prototype.getWorldMatrix = function () {
  11946. return this._worldMatrix;
  11947. };
  11948. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11949. this._worldMatrix.copyFrom(matrix);
  11950. return this;
  11951. };
  11952. BoundingBox.prototype._update = function (world) {
  11953. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11954. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11955. for (var index = 0; index < this.vectors.length; index++) {
  11956. var v = this.vectorsWorld[index];
  11957. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11958. if (v.x < this.minimumWorld.x)
  11959. this.minimumWorld.x = v.x;
  11960. if (v.y < this.minimumWorld.y)
  11961. this.minimumWorld.y = v.y;
  11962. if (v.z < this.minimumWorld.z)
  11963. this.minimumWorld.z = v.z;
  11964. if (v.x > this.maximumWorld.x)
  11965. this.maximumWorld.x = v.x;
  11966. if (v.y > this.maximumWorld.y)
  11967. this.maximumWorld.y = v.y;
  11968. if (v.z > this.maximumWorld.z)
  11969. this.maximumWorld.z = v.z;
  11970. }
  11971. // Extend
  11972. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11973. this.extendSizeWorld.scaleInPlace(0.5);
  11974. // OBB
  11975. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11976. this.centerWorld.scaleInPlace(0.5);
  11977. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11978. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11979. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11980. this._worldMatrix = world;
  11981. };
  11982. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11983. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11984. };
  11985. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11986. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11987. };
  11988. BoundingBox.prototype.intersectsPoint = function (point) {
  11989. var delta = -BABYLON.Epsilon;
  11990. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11991. return false;
  11992. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11993. return false;
  11994. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11995. return false;
  11996. return true;
  11997. };
  11998. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11999. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12000. };
  12001. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12002. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12003. return false;
  12004. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12005. return false;
  12006. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12007. return false;
  12008. return true;
  12009. };
  12010. // Statics
  12011. BoundingBox.Intersects = function (box0, box1) {
  12012. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12013. return false;
  12014. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12015. return false;
  12016. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12017. return false;
  12018. return true;
  12019. };
  12020. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12021. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12022. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12023. return (num <= (sphereRadius * sphereRadius));
  12024. };
  12025. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12026. for (var p = 0; p < 6; p++) {
  12027. for (var i = 0; i < 8; i++) {
  12028. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12029. return false;
  12030. }
  12031. }
  12032. }
  12033. return true;
  12034. };
  12035. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12036. for (var p = 0; p < 6; p++) {
  12037. var inCount = 8;
  12038. for (var i = 0; i < 8; i++) {
  12039. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12040. --inCount;
  12041. }
  12042. else {
  12043. break;
  12044. }
  12045. }
  12046. if (inCount === 0)
  12047. return false;
  12048. }
  12049. return true;
  12050. };
  12051. return BoundingBox;
  12052. }());
  12053. BABYLON.BoundingBox = BoundingBox;
  12054. })(BABYLON || (BABYLON = {}));
  12055. //# sourceMappingURL=babylon.boundingBox.js.map
  12056. var BABYLON;
  12057. (function (BABYLON) {
  12058. var computeBoxExtents = function (axis, box) {
  12059. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12060. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12061. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12062. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12063. var r = r0 + r1 + r2;
  12064. return {
  12065. min: p - r,
  12066. max: p + r
  12067. };
  12068. };
  12069. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12070. var axisOverlap = function (axis, box0, box1) {
  12071. var result0 = computeBoxExtents(axis, box0);
  12072. var result1 = computeBoxExtents(axis, box1);
  12073. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12074. };
  12075. var BoundingInfo = (function () {
  12076. function BoundingInfo(minimum, maximum) {
  12077. this.minimum = minimum;
  12078. this.maximum = maximum;
  12079. this._isLocked = false;
  12080. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12081. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12082. }
  12083. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12084. get: function () {
  12085. return this._isLocked;
  12086. },
  12087. set: function (value) {
  12088. this._isLocked = value;
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. // Methods
  12094. BoundingInfo.prototype.update = function (world) {
  12095. if (this._isLocked) {
  12096. return;
  12097. }
  12098. this.boundingBox._update(world);
  12099. this.boundingSphere._update(world);
  12100. };
  12101. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12102. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12103. return false;
  12104. return this.boundingBox.isInFrustum(frustumPlanes);
  12105. };
  12106. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12107. /**
  12108. * Gets the world distance between the min and max points of the bounding box
  12109. */
  12110. get: function () {
  12111. var boundingBox = this.boundingBox;
  12112. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12113. return size.length();
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12119. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12120. };
  12121. BoundingInfo.prototype._checkCollision = function (collider) {
  12122. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12123. };
  12124. BoundingInfo.prototype.intersectsPoint = function (point) {
  12125. if (!this.boundingSphere.centerWorld) {
  12126. return false;
  12127. }
  12128. if (!this.boundingSphere.intersectsPoint(point)) {
  12129. return false;
  12130. }
  12131. if (!this.boundingBox.intersectsPoint(point)) {
  12132. return false;
  12133. }
  12134. return true;
  12135. };
  12136. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12137. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12138. return false;
  12139. }
  12140. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12141. return false;
  12142. }
  12143. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12144. return false;
  12145. }
  12146. if (!precise) {
  12147. return true;
  12148. }
  12149. var box0 = this.boundingBox;
  12150. var box1 = boundingInfo.boundingBox;
  12151. if (!axisOverlap(box0.directions[0], box0, box1))
  12152. return false;
  12153. if (!axisOverlap(box0.directions[1], box0, box1))
  12154. return false;
  12155. if (!axisOverlap(box0.directions[2], box0, box1))
  12156. return false;
  12157. if (!axisOverlap(box1.directions[0], box0, box1))
  12158. return false;
  12159. if (!axisOverlap(box1.directions[1], box0, box1))
  12160. return false;
  12161. if (!axisOverlap(box1.directions[2], box0, box1))
  12162. return false;
  12163. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12164. return false;
  12165. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12166. return false;
  12167. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12168. return false;
  12169. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12170. return false;
  12171. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12172. return false;
  12173. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12174. return false;
  12175. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12176. return false;
  12177. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12178. return false;
  12179. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12180. return false;
  12181. return true;
  12182. };
  12183. return BoundingInfo;
  12184. }());
  12185. BABYLON.BoundingInfo = BoundingInfo;
  12186. })(BABYLON || (BABYLON = {}));
  12187. //# sourceMappingURL=babylon.boundingInfo.js.map
  12188. var BABYLON;
  12189. (function (BABYLON) {
  12190. var AbstractMesh = (function (_super) {
  12191. __extends(AbstractMesh, _super);
  12192. // Constructor
  12193. function AbstractMesh(name, scene) {
  12194. var _this = _super.call(this, name, scene) || this;
  12195. _this._facetNb = 0; // facet number
  12196. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12197. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12198. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12199. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12200. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12201. _this._subDiv = {
  12202. max: 1,
  12203. X: 1,
  12204. Y: 1,
  12205. Z: 1
  12206. };
  12207. // Events
  12208. /**
  12209. * An event triggered when this mesh collides with another one
  12210. * @type {BABYLON.Observable}
  12211. */
  12212. _this.onCollideObservable = new BABYLON.Observable();
  12213. /**
  12214. * An event triggered when the collision's position changes
  12215. * @type {BABYLON.Observable}
  12216. */
  12217. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12218. /**
  12219. * An event triggered after the world matrix is updated
  12220. * @type {BABYLON.Observable}
  12221. */
  12222. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12223. /**
  12224. * An event triggered when material is changed
  12225. * @type {BABYLON.Observable}
  12226. */
  12227. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12228. // Properties
  12229. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12230. _this.position = BABYLON.Vector3.Zero();
  12231. /**
  12232. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12233. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12234. * or
  12235. * 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.
  12236. * for more info check WebGl documentations
  12237. */
  12238. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12239. /**
  12240. * 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:
  12241. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12242. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12243. * 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.
  12244. */
  12245. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12246. /**
  12247. * 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.
  12248. * The default value is -1 which means don't break the query and wait till the result.
  12249. */
  12250. _this.occlusionRetryCount = -1;
  12251. _this._occlusionInternalRetryCounter = 0;
  12252. _this._isOccluded = false;
  12253. _this._isOcclusionQueryInProgress = false;
  12254. _this._rotation = BABYLON.Vector3.Zero();
  12255. _this._scaling = BABYLON.Vector3.One();
  12256. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12257. _this.visibility = 1.0;
  12258. _this.alphaIndex = Number.MAX_VALUE;
  12259. _this.infiniteDistance = false;
  12260. _this.isVisible = true;
  12261. _this.isPickable = true;
  12262. _this.showBoundingBox = false;
  12263. _this.showSubMeshesBoundingBox = false;
  12264. _this.isBlocker = false;
  12265. _this.enablePointerMoveEvents = false;
  12266. _this.renderingGroupId = 0;
  12267. _this._receiveShadows = false;
  12268. _this.renderOutline = false;
  12269. _this.outlineColor = BABYLON.Color3.Red();
  12270. _this.outlineWidth = 0.02;
  12271. _this.renderOverlay = false;
  12272. _this.overlayColor = BABYLON.Color3.Red();
  12273. _this.overlayAlpha = 0.5;
  12274. _this._hasVertexAlpha = false;
  12275. _this._useVertexColors = true;
  12276. _this._computeBonesUsingShaders = true;
  12277. _this._numBoneInfluencers = 4;
  12278. _this._applyFog = true;
  12279. _this.scalingDeterminant = 1;
  12280. _this.useOctreeForRenderingSelection = true;
  12281. _this.useOctreeForPicking = true;
  12282. _this.useOctreeForCollisions = true;
  12283. _this._layerMask = 0x0FFFFFFF;
  12284. /**
  12285. * True if the mesh must be rendered in any case.
  12286. */
  12287. _this.alwaysSelectAsActiveMesh = false;
  12288. // Collisions
  12289. _this._checkCollisions = false;
  12290. _this._collisionMask = -1;
  12291. _this._collisionGroup = -1;
  12292. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12293. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12294. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12295. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12296. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12297. // Edges
  12298. _this.edgesWidth = 1;
  12299. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12300. // Cache
  12301. _this._localWorld = BABYLON.Matrix.Zero();
  12302. _this._worldMatrix = BABYLON.Matrix.Zero();
  12303. _this._absolutePosition = BABYLON.Vector3.Zero();
  12304. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12305. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12306. _this._isDirty = false;
  12307. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12308. _this._postMultiplyPivotMatrix = false;
  12309. _this._isDisposed = false;
  12310. _this._renderId = 0;
  12311. _this._intersectionsInProgress = new Array();
  12312. _this._isWorldMatrixFrozen = false;
  12313. _this._unIndexed = false;
  12314. _this._lightSources = new Array();
  12315. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12316. if (collidedMesh === void 0) { collidedMesh = null; }
  12317. //TODO move this to the collision coordinator!
  12318. if (_this.getScene().workerCollisions)
  12319. newPosition.multiplyInPlace(_this._collider.radius);
  12320. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12321. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12322. _this.position.addInPlace(_this._diffPositionForCollisions);
  12323. }
  12324. if (collidedMesh) {
  12325. _this.onCollideObservable.notifyObservers(collidedMesh);
  12326. }
  12327. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12328. };
  12329. _this.getScene().addMesh(_this);
  12330. _this._resyncLightSources();
  12331. return _this;
  12332. }
  12333. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12334. get: function () {
  12335. return AbstractMesh._BILLBOARDMODE_NONE;
  12336. },
  12337. enumerable: true,
  12338. configurable: true
  12339. });
  12340. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12341. get: function () {
  12342. return AbstractMesh._BILLBOARDMODE_X;
  12343. },
  12344. enumerable: true,
  12345. configurable: true
  12346. });
  12347. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12348. get: function () {
  12349. return AbstractMesh._BILLBOARDMODE_Y;
  12350. },
  12351. enumerable: true,
  12352. configurable: true
  12353. });
  12354. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12355. get: function () {
  12356. return AbstractMesh._BILLBOARDMODE_Z;
  12357. },
  12358. enumerable: true,
  12359. configurable: true
  12360. });
  12361. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12362. get: function () {
  12363. return AbstractMesh._BILLBOARDMODE_ALL;
  12364. },
  12365. enumerable: true,
  12366. configurable: true
  12367. });
  12368. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12369. /**
  12370. * Read-only : the number of facets in the mesh
  12371. */
  12372. get: function () {
  12373. return this._facetNb;
  12374. },
  12375. enumerable: true,
  12376. configurable: true
  12377. });
  12378. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12379. /**
  12380. * The number (integer) of subdivisions per axis in the partioning space
  12381. */
  12382. get: function () {
  12383. return this._partitioningSubdivisions;
  12384. },
  12385. set: function (nb) {
  12386. this._partitioningSubdivisions = nb;
  12387. },
  12388. enumerable: true,
  12389. configurable: true
  12390. });
  12391. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12392. /**
  12393. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12394. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12395. */
  12396. get: function () {
  12397. return this._partitioningBBoxRatio;
  12398. },
  12399. set: function (ratio) {
  12400. this._partitioningBBoxRatio = ratio;
  12401. },
  12402. enumerable: true,
  12403. configurable: true
  12404. });
  12405. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12406. /**
  12407. * Read-only boolean : is the feature facetData enabled ?
  12408. */
  12409. get: function () {
  12410. return this._facetDataEnabled;
  12411. },
  12412. enumerable: true,
  12413. configurable: true
  12414. });
  12415. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12416. set: function (callback) {
  12417. if (this._onCollideObserver) {
  12418. this.onCollideObservable.remove(this._onCollideObserver);
  12419. }
  12420. this._onCollideObserver = this.onCollideObservable.add(callback);
  12421. },
  12422. enumerable: true,
  12423. configurable: true
  12424. });
  12425. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12426. set: function (callback) {
  12427. if (this._onCollisionPositionChangeObserver) {
  12428. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12429. }
  12430. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12431. },
  12432. enumerable: true,
  12433. configurable: true
  12434. });
  12435. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12436. /**
  12437. * 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.
  12438. */
  12439. get: function () {
  12440. return this._isOccluded;
  12441. },
  12442. set: function (value) {
  12443. this._isOccluded = value;
  12444. },
  12445. enumerable: true,
  12446. configurable: true
  12447. });
  12448. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12449. /**
  12450. * Flag to check the progress status of the query
  12451. */
  12452. get: function () {
  12453. return this._isOcclusionQueryInProgress;
  12454. },
  12455. enumerable: true,
  12456. configurable: true
  12457. });
  12458. Object.defineProperty(AbstractMesh.prototype, "material", {
  12459. get: function () {
  12460. return this._material;
  12461. },
  12462. set: function (value) {
  12463. if (this._material === value) {
  12464. return;
  12465. }
  12466. this._material = value;
  12467. if (this.onMaterialChangedObservable.hasObservers) {
  12468. this.onMaterialChangedObservable.notifyObservers(this);
  12469. }
  12470. if (!this.subMeshes) {
  12471. return;
  12472. }
  12473. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12474. var subMesh = _a[_i];
  12475. subMesh.setEffect(null);
  12476. }
  12477. },
  12478. enumerable: true,
  12479. configurable: true
  12480. });
  12481. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12482. get: function () {
  12483. return this._receiveShadows;
  12484. },
  12485. set: function (value) {
  12486. if (this._receiveShadows === value) {
  12487. return;
  12488. }
  12489. this._receiveShadows = value;
  12490. this._markSubMeshesAsLightDirty();
  12491. },
  12492. enumerable: true,
  12493. configurable: true
  12494. });
  12495. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12496. get: function () {
  12497. return this._hasVertexAlpha;
  12498. },
  12499. set: function (value) {
  12500. if (this._hasVertexAlpha === value) {
  12501. return;
  12502. }
  12503. this._hasVertexAlpha = value;
  12504. this._markSubMeshesAsAttributesDirty();
  12505. },
  12506. enumerable: true,
  12507. configurable: true
  12508. });
  12509. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12510. get: function () {
  12511. return this._useVertexColors;
  12512. },
  12513. set: function (value) {
  12514. if (this._useVertexColors === value) {
  12515. return;
  12516. }
  12517. this._useVertexColors = value;
  12518. this._markSubMeshesAsAttributesDirty();
  12519. },
  12520. enumerable: true,
  12521. configurable: true
  12522. });
  12523. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12524. get: function () {
  12525. return this._computeBonesUsingShaders;
  12526. },
  12527. set: function (value) {
  12528. if (this._computeBonesUsingShaders === value) {
  12529. return;
  12530. }
  12531. this._computeBonesUsingShaders = value;
  12532. this._markSubMeshesAsAttributesDirty();
  12533. },
  12534. enumerable: true,
  12535. configurable: true
  12536. });
  12537. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12538. get: function () {
  12539. return this._numBoneInfluencers;
  12540. },
  12541. set: function (value) {
  12542. if (this._numBoneInfluencers === value) {
  12543. return;
  12544. }
  12545. this._numBoneInfluencers = value;
  12546. this._markSubMeshesAsAttributesDirty();
  12547. },
  12548. enumerable: true,
  12549. configurable: true
  12550. });
  12551. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12552. get: function () {
  12553. return this._applyFog;
  12554. },
  12555. set: function (value) {
  12556. if (this._applyFog === value) {
  12557. return;
  12558. }
  12559. this._applyFog = value;
  12560. this._markSubMeshesAsMiscDirty();
  12561. },
  12562. enumerable: true,
  12563. configurable: true
  12564. });
  12565. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12566. get: function () {
  12567. return this._layerMask;
  12568. },
  12569. set: function (value) {
  12570. if (value === this._layerMask) {
  12571. return;
  12572. }
  12573. this._layerMask = value;
  12574. this._resyncLightSources();
  12575. },
  12576. enumerable: true,
  12577. configurable: true
  12578. });
  12579. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12580. get: function () {
  12581. return this._collisionMask;
  12582. },
  12583. set: function (mask) {
  12584. this._collisionMask = !isNaN(mask) ? mask : -1;
  12585. },
  12586. enumerable: true,
  12587. configurable: true
  12588. });
  12589. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12590. get: function () {
  12591. return this._collisionGroup;
  12592. },
  12593. set: function (mask) {
  12594. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12595. },
  12596. enumerable: true,
  12597. configurable: true
  12598. });
  12599. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12600. get: function () {
  12601. return null;
  12602. },
  12603. enumerable: true,
  12604. configurable: true
  12605. });
  12606. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12607. get: function () {
  12608. return this._skeleton;
  12609. },
  12610. set: function (value) {
  12611. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12612. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12613. }
  12614. if (value && value.needInitialSkinMatrix) {
  12615. value._registerMeshWithPoseMatrix(this);
  12616. }
  12617. this._skeleton = value;
  12618. if (!this._skeleton) {
  12619. this._bonesTransformMatrices = null;
  12620. }
  12621. this._markSubMeshesAsAttributesDirty();
  12622. },
  12623. enumerable: true,
  12624. configurable: true
  12625. });
  12626. /**
  12627. * Boolean : true if the mesh has been disposed.
  12628. */
  12629. AbstractMesh.prototype.isDisposed = function () {
  12630. return this._isDisposed;
  12631. };
  12632. /**
  12633. * Returns the string "AbstractMesh"
  12634. */
  12635. AbstractMesh.prototype.getClassName = function () {
  12636. return "AbstractMesh";
  12637. };
  12638. /**
  12639. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12640. */
  12641. AbstractMesh.prototype.toString = function (fullDetails) {
  12642. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12643. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12644. if (this._skeleton) {
  12645. ret += ", skeleton: " + this._skeleton.name;
  12646. }
  12647. if (fullDetails) {
  12648. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12649. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12650. }
  12651. return ret;
  12652. };
  12653. AbstractMesh.prototype._rebuild = function () {
  12654. if (this._occlusionQuery) {
  12655. this._occlusionQuery = null;
  12656. }
  12657. if (this._edgesRenderer) {
  12658. this._edgesRenderer._rebuild();
  12659. }
  12660. if (!this.subMeshes) {
  12661. return;
  12662. }
  12663. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12664. var subMesh = _a[_i];
  12665. subMesh._rebuild();
  12666. }
  12667. };
  12668. AbstractMesh.prototype._resyncLightSources = function () {
  12669. this._lightSources.length = 0;
  12670. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12671. var light = _a[_i];
  12672. if (!light.isEnabled()) {
  12673. continue;
  12674. }
  12675. if (light.canAffectMesh(this)) {
  12676. this._lightSources.push(light);
  12677. }
  12678. }
  12679. this._markSubMeshesAsLightDirty();
  12680. };
  12681. AbstractMesh.prototype._resyncLighSource = function (light) {
  12682. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12683. var index = this._lightSources.indexOf(light);
  12684. if (index === -1) {
  12685. if (!isIn) {
  12686. return;
  12687. }
  12688. this._lightSources.push(light);
  12689. }
  12690. else {
  12691. if (isIn) {
  12692. return;
  12693. }
  12694. this._lightSources.splice(index, 1);
  12695. }
  12696. this._markSubMeshesAsLightDirty();
  12697. };
  12698. AbstractMesh.prototype._removeLightSource = function (light) {
  12699. var index = this._lightSources.indexOf(light);
  12700. if (index === -1) {
  12701. return;
  12702. }
  12703. this._lightSources.splice(index, 1);
  12704. };
  12705. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12706. if (!this.subMeshes) {
  12707. return;
  12708. }
  12709. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12710. var subMesh = _a[_i];
  12711. if (subMesh._materialDefines) {
  12712. func(subMesh._materialDefines);
  12713. }
  12714. }
  12715. };
  12716. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12717. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12718. };
  12719. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12720. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12721. };
  12722. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12723. if (!this.subMeshes) {
  12724. return;
  12725. }
  12726. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12727. var subMesh = _a[_i];
  12728. var material = subMesh.getMaterial();
  12729. if (material) {
  12730. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12731. }
  12732. }
  12733. };
  12734. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12735. /**
  12736. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12737. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12738. * Default : (0.0, 0.0, 0.0)
  12739. */
  12740. get: function () {
  12741. return this._rotation;
  12742. },
  12743. set: function (newRotation) {
  12744. this._rotation = newRotation;
  12745. },
  12746. enumerable: true,
  12747. configurable: true
  12748. });
  12749. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12750. /**
  12751. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12752. * Default : (1.0, 1.0, 1.0)
  12753. */
  12754. get: function () {
  12755. return this._scaling;
  12756. },
  12757. set: function (newScaling) {
  12758. this._scaling = newScaling;
  12759. if (this.physicsImpostor) {
  12760. this.physicsImpostor.forceUpdate();
  12761. }
  12762. },
  12763. enumerable: true,
  12764. configurable: true
  12765. });
  12766. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12767. /**
  12768. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12769. * It's null by default.
  12770. * 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)
  12771. */
  12772. get: function () {
  12773. return this._rotationQuaternion;
  12774. },
  12775. set: function (quaternion) {
  12776. this._rotationQuaternion = quaternion;
  12777. //reset the rotation vector.
  12778. if (quaternion && this.rotation.length()) {
  12779. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12780. }
  12781. },
  12782. enumerable: true,
  12783. configurable: true
  12784. });
  12785. // Methods
  12786. /**
  12787. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12788. * Returns the AbstractMesh.
  12789. */
  12790. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12791. this._poseMatrix.copyFrom(matrix);
  12792. return this;
  12793. };
  12794. /**
  12795. * Returns the mesh Pose matrix.
  12796. * Returned object : Matrix
  12797. */
  12798. AbstractMesh.prototype.getPoseMatrix = function () {
  12799. return this._poseMatrix;
  12800. };
  12801. /**
  12802. * Disables the mesh edger rendering mode.
  12803. * Returns the AbstractMesh.
  12804. */
  12805. AbstractMesh.prototype.disableEdgesRendering = function () {
  12806. if (this._edgesRenderer !== undefined) {
  12807. this._edgesRenderer.dispose();
  12808. this._edgesRenderer = undefined;
  12809. }
  12810. return this;
  12811. };
  12812. /**
  12813. * Enables the edge rendering mode on the mesh.
  12814. * This mode makes the mesh edges visible.
  12815. * Returns the AbstractMesh.
  12816. */
  12817. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12818. if (epsilon === void 0) { epsilon = 0.95; }
  12819. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12820. this.disableEdgesRendering();
  12821. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12822. return this;
  12823. };
  12824. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12825. /**
  12826. * Returns true if the mesh is blocked. Used by the class Mesh.
  12827. * Returns the boolean `false` by default.
  12828. */
  12829. get: function () {
  12830. return false;
  12831. },
  12832. enumerable: true,
  12833. configurable: true
  12834. });
  12835. /**
  12836. * Returns the mesh itself by default, used by the class Mesh.
  12837. * Returned type : AbstractMesh
  12838. */
  12839. AbstractMesh.prototype.getLOD = function (camera) {
  12840. return this;
  12841. };
  12842. /**
  12843. * Returns 0 by default, used by the class Mesh.
  12844. * Returns an integer.
  12845. */
  12846. AbstractMesh.prototype.getTotalVertices = function () {
  12847. return 0;
  12848. };
  12849. /**
  12850. * Returns null by default, used by the class Mesh.
  12851. * Returned type : integer array
  12852. */
  12853. AbstractMesh.prototype.getIndices = function () {
  12854. return null;
  12855. };
  12856. /**
  12857. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12858. * Returned type : float array or Float32Array
  12859. */
  12860. AbstractMesh.prototype.getVerticesData = function (kind) {
  12861. return null;
  12862. };
  12863. /**
  12864. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12865. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12866. * The `data` are either a numeric array either a Float32Array.
  12867. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12868. * 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).
  12869. * Note that a new underlying VertexBuffer object is created each call.
  12870. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12871. *
  12872. * Possible `kind` values :
  12873. * - BABYLON.VertexBuffer.PositionKind
  12874. * - BABYLON.VertexBuffer.UVKind
  12875. * - BABYLON.VertexBuffer.UV2Kind
  12876. * - BABYLON.VertexBuffer.UV3Kind
  12877. * - BABYLON.VertexBuffer.UV4Kind
  12878. * - BABYLON.VertexBuffer.UV5Kind
  12879. * - BABYLON.VertexBuffer.UV6Kind
  12880. * - BABYLON.VertexBuffer.ColorKind
  12881. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12882. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12883. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12884. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12885. *
  12886. * Returns the Mesh.
  12887. */
  12888. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12889. return null;
  12890. };
  12891. /**
  12892. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12893. * If the mesh has no geometry, it is simply returned as it is.
  12894. * The `data` are either a numeric array either a Float32Array.
  12895. * No new underlying VertexBuffer object is created.
  12896. * 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.
  12897. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12898. *
  12899. * Possible `kind` values :
  12900. * - BABYLON.VertexBuffer.PositionKind
  12901. * - BABYLON.VertexBuffer.UVKind
  12902. * - BABYLON.VertexBuffer.UV2Kind
  12903. * - BABYLON.VertexBuffer.UV3Kind
  12904. * - BABYLON.VertexBuffer.UV4Kind
  12905. * - BABYLON.VertexBuffer.UV5Kind
  12906. * - BABYLON.VertexBuffer.UV6Kind
  12907. * - BABYLON.VertexBuffer.ColorKind
  12908. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12909. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12910. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12911. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12912. *
  12913. * Returns the Mesh.
  12914. */
  12915. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12916. return null;
  12917. };
  12918. /**
  12919. * Sets the mesh indices.
  12920. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12921. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12922. * This method creates a new index buffer each call.
  12923. * Returns the Mesh.
  12924. */
  12925. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12926. return null;
  12927. };
  12928. /** Returns false by default, used by the class Mesh.
  12929. * Returns a boolean
  12930. */
  12931. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12932. return false;
  12933. };
  12934. /**
  12935. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12936. * Returns a BoundingInfo
  12937. */
  12938. AbstractMesh.prototype.getBoundingInfo = function () {
  12939. if (this._masterMesh) {
  12940. return this._masterMesh.getBoundingInfo();
  12941. }
  12942. if (!this._boundingInfo) {
  12943. this._updateBoundingInfo();
  12944. }
  12945. return this._boundingInfo;
  12946. };
  12947. /**
  12948. * Sets a mesh new object BoundingInfo.
  12949. * Returns the AbstractMesh.
  12950. */
  12951. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12952. this._boundingInfo = boundingInfo;
  12953. return this;
  12954. };
  12955. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12956. get: function () {
  12957. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12958. },
  12959. enumerable: true,
  12960. configurable: true
  12961. });
  12962. AbstractMesh.prototype._preActivate = function () {
  12963. };
  12964. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12965. };
  12966. AbstractMesh.prototype._activate = function (renderId) {
  12967. this._renderId = renderId;
  12968. };
  12969. /**
  12970. * Returns the last update of the World matrix
  12971. * Returns a Matrix.
  12972. */
  12973. AbstractMesh.prototype.getWorldMatrix = function () {
  12974. if (this._masterMesh) {
  12975. return this._masterMesh.getWorldMatrix();
  12976. }
  12977. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12978. this.computeWorldMatrix();
  12979. }
  12980. return this._worldMatrix;
  12981. };
  12982. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12983. /**
  12984. * Returns directly the last state of the mesh World matrix.
  12985. * A Matrix is returned.
  12986. */
  12987. get: function () {
  12988. return this._worldMatrix;
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12994. /**
  12995. * Returns the current mesh absolute position.
  12996. * Retuns a Vector3.
  12997. */
  12998. get: function () {
  12999. return this._absolutePosition;
  13000. },
  13001. enumerable: true,
  13002. configurable: true
  13003. });
  13004. /**
  13005. * Prevents the World matrix to be computed any longer.
  13006. * Returns the AbstractMesh.
  13007. */
  13008. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13009. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13010. this.computeWorldMatrix(true);
  13011. this._isWorldMatrixFrozen = true;
  13012. return this;
  13013. };
  13014. /**
  13015. * Allows back the World matrix computation.
  13016. * Returns the AbstractMesh.
  13017. */
  13018. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13019. this._isWorldMatrixFrozen = false;
  13020. this.computeWorldMatrix(true);
  13021. return this;
  13022. };
  13023. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13024. /**
  13025. * True if the World matrix has been frozen.
  13026. * Returns a boolean.
  13027. */
  13028. get: function () {
  13029. return this._isWorldMatrixFrozen;
  13030. },
  13031. enumerable: true,
  13032. configurable: true
  13033. });
  13034. /**
  13035. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13036. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13037. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13038. * The passed axis is also normalized.
  13039. * Returns the AbstractMesh.
  13040. */
  13041. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13042. axis.normalize();
  13043. if (!this.rotationQuaternion) {
  13044. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13045. this.rotation = BABYLON.Vector3.Zero();
  13046. }
  13047. var rotationQuaternion;
  13048. if (!space || space === BABYLON.Space.LOCAL) {
  13049. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13050. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13051. }
  13052. else {
  13053. if (this.parent) {
  13054. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13055. invertParentWorldMatrix.invert();
  13056. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13057. }
  13058. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13059. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13060. }
  13061. return this;
  13062. };
  13063. /**
  13064. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13065. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13066. * The passed axis is also normalized.
  13067. * Returns the AbstractMesh.
  13068. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13069. */
  13070. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13071. axis.normalize();
  13072. if (!this.rotationQuaternion) {
  13073. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13074. this.rotation.copyFromFloats(0, 0, 0);
  13075. }
  13076. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13077. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13078. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13079. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13080. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13081. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13082. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13083. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13084. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13085. return this;
  13086. };
  13087. /**
  13088. * Translates the mesh along the axis vector for the passed distance in the given space.
  13089. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13090. * Returns the AbstractMesh.
  13091. */
  13092. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13093. var displacementVector = axis.scale(distance);
  13094. if (!space || space === BABYLON.Space.LOCAL) {
  13095. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13096. this.setPositionWithLocalVector(tempV3);
  13097. }
  13098. else {
  13099. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13100. }
  13101. return this;
  13102. };
  13103. /**
  13104. * Adds a rotation step to the mesh current rotation.
  13105. * x, y, z are Euler angles expressed in radians.
  13106. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13107. * This means this rotation is made in the mesh local space only.
  13108. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13109. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13110. * ```javascript
  13111. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13112. * ```
  13113. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13114. * 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.
  13115. * Returns the AbstractMesh.
  13116. */
  13117. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13118. var rotationQuaternion;
  13119. if (this.rotationQuaternion) {
  13120. rotationQuaternion = this.rotationQuaternion;
  13121. }
  13122. else {
  13123. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13124. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13125. }
  13126. var accumulation = BABYLON.Tmp.Quaternion[0];
  13127. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13128. rotationQuaternion.multiplyInPlace(accumulation);
  13129. if (!this.rotationQuaternion) {
  13130. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13131. }
  13132. return this;
  13133. };
  13134. /**
  13135. * Retuns the mesh absolute position in the World.
  13136. * Returns a Vector3.
  13137. */
  13138. AbstractMesh.prototype.getAbsolutePosition = function () {
  13139. this.computeWorldMatrix();
  13140. return this._absolutePosition;
  13141. };
  13142. /**
  13143. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13144. * Returns the AbstractMesh.
  13145. */
  13146. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13147. if (!absolutePosition) {
  13148. return;
  13149. }
  13150. var absolutePositionX;
  13151. var absolutePositionY;
  13152. var absolutePositionZ;
  13153. if (absolutePosition.x === undefined) {
  13154. if (arguments.length < 3) {
  13155. return;
  13156. }
  13157. absolutePositionX = arguments[0];
  13158. absolutePositionY = arguments[1];
  13159. absolutePositionZ = arguments[2];
  13160. }
  13161. else {
  13162. absolutePositionX = absolutePosition.x;
  13163. absolutePositionY = absolutePosition.y;
  13164. absolutePositionZ = absolutePosition.z;
  13165. }
  13166. if (this.parent) {
  13167. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13168. invertParentWorldMatrix.invert();
  13169. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13170. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13171. }
  13172. else {
  13173. this.position.x = absolutePositionX;
  13174. this.position.y = absolutePositionY;
  13175. this.position.z = absolutePositionZ;
  13176. }
  13177. return this;
  13178. };
  13179. // ================================== Point of View Movement =================================
  13180. /**
  13181. * Perform relative position change from the point of view of behind the front of the mesh.
  13182. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13183. * Supports definition of mesh facing forward or backward.
  13184. * @param {number} amountRight
  13185. * @param {number} amountUp
  13186. * @param {number} amountForward
  13187. *
  13188. * Returns the AbstractMesh.
  13189. */
  13190. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13191. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13192. return this;
  13193. };
  13194. /**
  13195. * Calculate relative position change from the point of view of behind the front of the mesh.
  13196. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13197. * Supports definition of mesh facing forward or backward.
  13198. * @param {number} amountRight
  13199. * @param {number} amountUp
  13200. * @param {number} amountForward
  13201. *
  13202. * Returns a new Vector3.
  13203. */
  13204. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13205. var rotMatrix = new BABYLON.Matrix();
  13206. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13207. rotQuaternion.toRotationMatrix(rotMatrix);
  13208. var translationDelta = BABYLON.Vector3.Zero();
  13209. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13210. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13211. return translationDelta;
  13212. };
  13213. // ================================== Point of View Rotation =================================
  13214. /**
  13215. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13216. * Supports definition of mesh facing forward or backward.
  13217. * @param {number} flipBack
  13218. * @param {number} twirlClockwise
  13219. * @param {number} tiltRight
  13220. *
  13221. * Returns the AbstractMesh.
  13222. */
  13223. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13224. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13225. return this;
  13226. };
  13227. /**
  13228. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13229. * Supports definition of mesh facing forward or backward.
  13230. * @param {number} flipBack
  13231. * @param {number} twirlClockwise
  13232. * @param {number} tiltRight
  13233. *
  13234. * Returns a new Vector3.
  13235. */
  13236. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13237. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13238. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13239. };
  13240. /**
  13241. * Sets a new pivot matrix to the mesh.
  13242. * Returns the AbstractMesh.
  13243. */
  13244. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13245. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13246. this._pivotMatrix = matrix;
  13247. this._cache.pivotMatrixUpdated = true;
  13248. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13249. if (this._postMultiplyPivotMatrix) {
  13250. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13251. }
  13252. return this;
  13253. };
  13254. /**
  13255. * Returns the mesh pivot matrix.
  13256. * Default : Identity.
  13257. * A Matrix is returned.
  13258. */
  13259. AbstractMesh.prototype.getPivotMatrix = function () {
  13260. return this._pivotMatrix;
  13261. };
  13262. AbstractMesh.prototype._isSynchronized = function () {
  13263. if (this._isDirty) {
  13264. return false;
  13265. }
  13266. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13267. return false;
  13268. if (this._cache.pivotMatrixUpdated) {
  13269. return false;
  13270. }
  13271. if (this.infiniteDistance) {
  13272. return false;
  13273. }
  13274. if (!this._cache.position.equals(this.position))
  13275. return false;
  13276. if (this.rotationQuaternion) {
  13277. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13278. return false;
  13279. }
  13280. if (!this._cache.rotation.equals(this.rotation))
  13281. return false;
  13282. if (!this._cache.scaling.equals(this.scaling))
  13283. return false;
  13284. return true;
  13285. };
  13286. AbstractMesh.prototype._initCache = function () {
  13287. _super.prototype._initCache.call(this);
  13288. this._cache.localMatrixUpdated = false;
  13289. this._cache.position = BABYLON.Vector3.Zero();
  13290. this._cache.scaling = BABYLON.Vector3.Zero();
  13291. this._cache.rotation = BABYLON.Vector3.Zero();
  13292. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13293. this._cache.billboardMode = -1;
  13294. };
  13295. AbstractMesh.prototype.markAsDirty = function (property) {
  13296. if (property === "rotation") {
  13297. this.rotationQuaternion = null;
  13298. }
  13299. this._currentRenderId = Number.MAX_VALUE;
  13300. this._isDirty = true;
  13301. return this;
  13302. };
  13303. /**
  13304. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13305. */
  13306. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13307. this.computeWorldMatrix(true);
  13308. var min;
  13309. var max;
  13310. if (!this.subMeshes) {
  13311. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13312. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13313. }
  13314. else {
  13315. min = this.getBoundingInfo().boundingBox.minimumWorld;
  13316. max = this.getBoundingInfo().boundingBox.maximumWorld;
  13317. }
  13318. var descendants = this.getDescendants(false);
  13319. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13320. var descendant = descendants_1[_i];
  13321. var childMesh = descendant;
  13322. childMesh.computeWorldMatrix(true);
  13323. if (childMesh.getTotalVertices() === 0) {
  13324. continue;
  13325. }
  13326. var boundingBox = childMesh.getBoundingInfo().boundingBox;
  13327. var minBox = boundingBox.minimumWorld;
  13328. var maxBox = boundingBox.maximumWorld;
  13329. BABYLON.Tools.CheckExtends(minBox, min, max);
  13330. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13331. }
  13332. return {
  13333. min: min,
  13334. max: max
  13335. };
  13336. };
  13337. /**
  13338. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13339. * Returns the AbstractMesh.
  13340. */
  13341. AbstractMesh.prototype._updateBoundingInfo = function () {
  13342. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13343. this._boundingInfo.update(this.worldMatrixFromCache);
  13344. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13345. return this;
  13346. };
  13347. /**
  13348. * Update a mesh's children BoundingInfo objects only.
  13349. * Returns the AbstractMesh.
  13350. */
  13351. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13352. if (!this.subMeshes) {
  13353. return;
  13354. }
  13355. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13356. var subMesh = this.subMeshes[subIndex];
  13357. if (!subMesh.IsGlobal) {
  13358. subMesh.updateBoundingInfo(matrix);
  13359. }
  13360. }
  13361. return this;
  13362. };
  13363. /**
  13364. * Computes the mesh World matrix and returns it.
  13365. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13366. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13367. * If the parameter `force`is set to `true`, the actual computation is done.
  13368. * Returns the mesh World Matrix.
  13369. */
  13370. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13371. if (this._isWorldMatrixFrozen) {
  13372. return this._worldMatrix;
  13373. }
  13374. if (!force && this.isSynchronized(true)) {
  13375. this._currentRenderId = this.getScene().getRenderId();
  13376. return this._worldMatrix;
  13377. }
  13378. this._cache.position.copyFrom(this.position);
  13379. this._cache.scaling.copyFrom(this.scaling);
  13380. this._cache.pivotMatrixUpdated = false;
  13381. this._cache.billboardMode = this.billboardMode;
  13382. this._currentRenderId = this.getScene().getRenderId();
  13383. this._isDirty = false;
  13384. // Scaling
  13385. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13386. // Rotation
  13387. //rotate, if quaternion is set and rotation was used
  13388. if (this.rotationQuaternion) {
  13389. var len = this.rotation.length();
  13390. if (len) {
  13391. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13392. this.rotation.copyFromFloats(0, 0, 0);
  13393. }
  13394. }
  13395. if (this.rotationQuaternion) {
  13396. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13397. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13398. }
  13399. else {
  13400. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13401. this._cache.rotation.copyFrom(this.rotation);
  13402. }
  13403. // Translation
  13404. if (this.infiniteDistance && !this.parent) {
  13405. var camera = this.getScene().activeCamera;
  13406. if (camera) {
  13407. var cameraWorldMatrix = camera.getWorldMatrix();
  13408. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13409. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13410. }
  13411. }
  13412. else {
  13413. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13414. }
  13415. // Composing transformations
  13416. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13417. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13418. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13419. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13420. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13421. // Need to decompose each rotation here
  13422. var currentPosition = BABYLON.Tmp.Vector3[3];
  13423. if (this.parent && this.parent.getWorldMatrix) {
  13424. if (this._meshToBoneReferal) {
  13425. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13426. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13427. }
  13428. else {
  13429. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13430. }
  13431. }
  13432. else {
  13433. currentPosition.copyFrom(this.position);
  13434. }
  13435. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13436. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13437. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13438. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13439. }
  13440. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13441. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13442. }
  13443. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13444. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13445. }
  13446. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13447. }
  13448. else {
  13449. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13450. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13451. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13452. }
  13453. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13454. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13455. }
  13456. // Local world
  13457. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13458. // Parent
  13459. if (this.parent && this.parent.getWorldMatrix) {
  13460. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13461. if (this._meshToBoneReferal) {
  13462. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13463. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13464. }
  13465. else {
  13466. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13467. }
  13468. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13469. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13470. this._worldMatrix.copyFrom(this._localWorld);
  13471. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13472. }
  13473. else {
  13474. if (this._meshToBoneReferal) {
  13475. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13476. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13477. }
  13478. else {
  13479. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13480. }
  13481. }
  13482. this._markSyncedWithParent();
  13483. }
  13484. else {
  13485. this._worldMatrix.copyFrom(this._localWorld);
  13486. }
  13487. // Post multiply inverse of pivotMatrix
  13488. if (this._postMultiplyPivotMatrix) {
  13489. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13490. }
  13491. // Bounding info
  13492. this._updateBoundingInfo();
  13493. // Absolute position
  13494. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13495. // Callbacks
  13496. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13497. if (!this._poseMatrix) {
  13498. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13499. }
  13500. return this._worldMatrix;
  13501. };
  13502. /**
  13503. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13504. * @param func: callback function to add
  13505. *
  13506. * Returns the AbstractMesh.
  13507. */
  13508. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13509. this.onAfterWorldMatrixUpdateObservable.add(func);
  13510. return this;
  13511. };
  13512. /**
  13513. * Removes a registered callback function.
  13514. * Returns the AbstractMesh.
  13515. */
  13516. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13517. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13518. return this;
  13519. };
  13520. /**
  13521. * Sets the mesh position in its local space.
  13522. * Returns the AbstractMesh.
  13523. */
  13524. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13525. this.computeWorldMatrix();
  13526. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13527. return this;
  13528. };
  13529. /**
  13530. * Returns the mesh position in the local space from the current World matrix values.
  13531. * Returns a new Vector3.
  13532. */
  13533. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13534. this.computeWorldMatrix();
  13535. var invLocalWorldMatrix = this._localWorld.clone();
  13536. invLocalWorldMatrix.invert();
  13537. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13538. };
  13539. /**
  13540. * Translates the mesh along the passed Vector3 in its local space.
  13541. * Returns the AbstractMesh.
  13542. */
  13543. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13544. this.computeWorldMatrix(true);
  13545. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13546. return this;
  13547. };
  13548. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13549. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13550. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13551. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13552. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13553. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13554. /// <returns>Mesh oriented towards targetMesh</returns>
  13555. if (yawCor === void 0) { yawCor = 0; }
  13556. if (pitchCor === void 0) { pitchCor = 0; }
  13557. if (rollCor === void 0) { rollCor = 0; }
  13558. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13559. var dv = AbstractMesh._lookAtVectorCache;
  13560. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13561. targetPoint.subtractToRef(pos, dv);
  13562. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13563. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13564. var pitch = Math.atan2(dv.y, len);
  13565. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13566. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13567. return this;
  13568. };
  13569. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13570. this._meshToBoneReferal = affectedMesh;
  13571. this.parent = bone;
  13572. if (bone.getWorldMatrix().determinant() < 0) {
  13573. this.scalingDeterminant *= -1;
  13574. }
  13575. return this;
  13576. };
  13577. AbstractMesh.prototype.detachFromBone = function () {
  13578. if (this.parent.getWorldMatrix().determinant() < 0) {
  13579. this.scalingDeterminant *= -1;
  13580. }
  13581. this._meshToBoneReferal = null;
  13582. this.parent = null;
  13583. return this;
  13584. };
  13585. /**
  13586. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13587. * A mesh is in the frustum if its bounding box intersects the frustum.
  13588. * Boolean returned.
  13589. */
  13590. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13591. return this._boundingInfo.isInFrustum(frustumPlanes);
  13592. };
  13593. /**
  13594. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13595. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13596. * Boolean returned.
  13597. */
  13598. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13599. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13600. ;
  13601. };
  13602. /**
  13603. * True if the mesh intersects another mesh or a SolidParticle object.
  13604. * 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)
  13605. * Returns a boolean.
  13606. */
  13607. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13608. if (!this._boundingInfo || !mesh._boundingInfo) {
  13609. return false;
  13610. }
  13611. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13612. };
  13613. /**
  13614. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13615. * Returns a boolean.
  13616. */
  13617. AbstractMesh.prototype.intersectsPoint = function (point) {
  13618. if (!this._boundingInfo) {
  13619. return false;
  13620. }
  13621. return this._boundingInfo.intersectsPoint(point);
  13622. };
  13623. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13624. return this.physicsImpostor;
  13625. };
  13626. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13627. if (!camera) {
  13628. camera = this.getScene().activeCamera;
  13629. }
  13630. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13631. };
  13632. /**
  13633. * Returns the distance from the mesh to the active camera.
  13634. * Returns a float.
  13635. */
  13636. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13637. if (!camera) {
  13638. camera = this.getScene().activeCamera;
  13639. }
  13640. return this.absolutePosition.subtract(camera.position).length();
  13641. };
  13642. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13643. if (!this.physicsImpostor) {
  13644. return;
  13645. }
  13646. this.physicsImpostor.applyImpulse(force, contactPoint);
  13647. return this;
  13648. };
  13649. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13650. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13651. return;
  13652. }
  13653. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13654. mainPivot: pivot1,
  13655. connectedPivot: pivot2,
  13656. nativeParams: options
  13657. });
  13658. return this;
  13659. };
  13660. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13661. // Collisions
  13662. /**
  13663. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13664. * Default `false`.
  13665. */
  13666. get: function () {
  13667. return this._checkCollisions;
  13668. },
  13669. set: function (collisionEnabled) {
  13670. this._checkCollisions = collisionEnabled;
  13671. if (this.getScene().workerCollisions) {
  13672. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13673. }
  13674. },
  13675. enumerable: true,
  13676. configurable: true
  13677. });
  13678. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13679. var globalPosition = this.getAbsolutePosition();
  13680. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13681. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13682. if (!this._collider) {
  13683. this._collider = new BABYLON.Collider();
  13684. }
  13685. this._collider.radius = this.ellipsoid;
  13686. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13687. return this;
  13688. };
  13689. // Submeshes octree
  13690. /**
  13691. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13692. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13693. * Returns an Octree of submeshes.
  13694. */
  13695. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13696. if (maxCapacity === void 0) { maxCapacity = 64; }
  13697. if (maxDepth === void 0) { maxDepth = 2; }
  13698. if (!this._submeshesOctree) {
  13699. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13700. }
  13701. this.computeWorldMatrix(true);
  13702. // Update octree
  13703. var bbox = this.getBoundingInfo().boundingBox;
  13704. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13705. return this._submeshesOctree;
  13706. };
  13707. // Collisions
  13708. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13709. this._generatePointsArray();
  13710. // Transformation
  13711. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13712. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13713. subMesh._lastColliderWorldVertices = [];
  13714. subMesh._trianglePlanes = [];
  13715. var start = subMesh.verticesStart;
  13716. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13717. for (var i = start; i < end; i++) {
  13718. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13719. }
  13720. }
  13721. // Collide
  13722. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13723. if (collider.collisionFound) {
  13724. collider.collidedMesh = this;
  13725. }
  13726. return this;
  13727. };
  13728. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13729. var subMeshes;
  13730. var len;
  13731. // Octrees
  13732. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13733. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13734. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13735. len = intersections.length;
  13736. subMeshes = intersections.data;
  13737. }
  13738. else {
  13739. subMeshes = this.subMeshes;
  13740. len = subMeshes.length;
  13741. }
  13742. for (var index = 0; index < len; index++) {
  13743. var subMesh = subMeshes[index];
  13744. // Bounding test
  13745. if (len > 1 && !subMesh._checkCollision(collider))
  13746. continue;
  13747. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13748. }
  13749. return this;
  13750. };
  13751. AbstractMesh.prototype._checkCollision = function (collider) {
  13752. // Bounding box test
  13753. if (!this._boundingInfo._checkCollision(collider))
  13754. return this;
  13755. // Transformation matrix
  13756. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13757. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13758. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13759. return this;
  13760. };
  13761. // Picking
  13762. AbstractMesh.prototype._generatePointsArray = function () {
  13763. return false;
  13764. };
  13765. /**
  13766. * Checks if the passed Ray intersects with the mesh.
  13767. * Returns an object PickingInfo.
  13768. */
  13769. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13770. var pickingInfo = new BABYLON.PickingInfo();
  13771. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13772. return pickingInfo;
  13773. }
  13774. if (!this._generatePointsArray()) {
  13775. return pickingInfo;
  13776. }
  13777. var intersectInfo = null;
  13778. // Octrees
  13779. var subMeshes;
  13780. var len;
  13781. if (this._submeshesOctree && this.useOctreeForPicking) {
  13782. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13783. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13784. len = intersections.length;
  13785. subMeshes = intersections.data;
  13786. }
  13787. else {
  13788. subMeshes = this.subMeshes;
  13789. len = subMeshes.length;
  13790. }
  13791. for (var index = 0; index < len; index++) {
  13792. var subMesh = subMeshes[index];
  13793. // Bounding test
  13794. if (len > 1 && !subMesh.canIntersects(ray))
  13795. continue;
  13796. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13797. if (currentIntersectInfo) {
  13798. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13799. intersectInfo = currentIntersectInfo;
  13800. intersectInfo.subMeshId = index;
  13801. if (fastCheck) {
  13802. break;
  13803. }
  13804. }
  13805. }
  13806. }
  13807. if (intersectInfo) {
  13808. // Get picked point
  13809. var world = this.getWorldMatrix();
  13810. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13811. var direction = ray.direction.clone();
  13812. direction = direction.scale(intersectInfo.distance);
  13813. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13814. var pickedPoint = worldOrigin.add(worldDirection);
  13815. // Return result
  13816. pickingInfo.hit = true;
  13817. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13818. pickingInfo.pickedPoint = pickedPoint;
  13819. pickingInfo.pickedMesh = this;
  13820. pickingInfo.bu = intersectInfo.bu;
  13821. pickingInfo.bv = intersectInfo.bv;
  13822. pickingInfo.faceId = intersectInfo.faceId;
  13823. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13824. return pickingInfo;
  13825. }
  13826. return pickingInfo;
  13827. };
  13828. /**
  13829. * Clones the mesh, used by the class Mesh.
  13830. * Just returns `null` for an AbstractMesh.
  13831. */
  13832. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13833. return null;
  13834. };
  13835. /**
  13836. * Disposes all the mesh submeshes.
  13837. * Returns the AbstractMesh.
  13838. */
  13839. AbstractMesh.prototype.releaseSubMeshes = function () {
  13840. if (this.subMeshes) {
  13841. while (this.subMeshes.length) {
  13842. this.subMeshes[0].dispose();
  13843. }
  13844. }
  13845. else {
  13846. this.subMeshes = new Array();
  13847. }
  13848. return this;
  13849. };
  13850. /**
  13851. * Disposes the AbstractMesh.
  13852. * Some internal references are kept for further use.
  13853. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13854. * Returns nothing.
  13855. */
  13856. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13857. var _this = this;
  13858. var index;
  13859. // Action manager
  13860. if (this.actionManager) {
  13861. this.actionManager.dispose();
  13862. this.actionManager = null;
  13863. }
  13864. // Skeleton
  13865. this.skeleton = null;
  13866. // Animations
  13867. this.getScene().stopAnimation(this);
  13868. // Physics
  13869. if (this.physicsImpostor) {
  13870. this.physicsImpostor.dispose();
  13871. }
  13872. // Intersections in progress
  13873. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13874. var other = this._intersectionsInProgress[index];
  13875. var pos = other._intersectionsInProgress.indexOf(this);
  13876. other._intersectionsInProgress.splice(pos, 1);
  13877. }
  13878. this._intersectionsInProgress = [];
  13879. // Lights
  13880. var lights = this.getScene().lights;
  13881. lights.forEach(function (light) {
  13882. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13883. if (meshIndex !== -1) {
  13884. light.includedOnlyMeshes.splice(meshIndex, 1);
  13885. }
  13886. meshIndex = light.excludedMeshes.indexOf(_this);
  13887. if (meshIndex !== -1) {
  13888. light.excludedMeshes.splice(meshIndex, 1);
  13889. }
  13890. // Shadow generators
  13891. var generator = light.getShadowGenerator();
  13892. if (generator) {
  13893. var shadowMap = generator.getShadowMap();
  13894. meshIndex = shadowMap.renderList.indexOf(_this);
  13895. if (meshIndex !== -1) {
  13896. shadowMap.renderList.splice(meshIndex, 1);
  13897. }
  13898. }
  13899. });
  13900. // Edges
  13901. if (this._edgesRenderer) {
  13902. this._edgesRenderer.dispose();
  13903. this._edgesRenderer = null;
  13904. }
  13905. // SubMeshes
  13906. if (this.getClassName() !== "InstancedMesh") {
  13907. this.releaseSubMeshes();
  13908. }
  13909. // Octree
  13910. var sceneOctree = this.getScene().selectionOctree;
  13911. if (sceneOctree) {
  13912. var index = sceneOctree.dynamicContent.indexOf(this);
  13913. if (index !== -1) {
  13914. sceneOctree.dynamicContent.splice(index, 1);
  13915. }
  13916. }
  13917. // Query
  13918. var engine = this.getScene().getEngine();
  13919. if (this._occlusionQuery) {
  13920. this._isOcclusionQueryInProgress = false;
  13921. engine.deleteQuery(this._occlusionQuery);
  13922. this._occlusionQuery = null;
  13923. }
  13924. // Engine
  13925. engine.wipeCaches();
  13926. // Remove from scene
  13927. this.getScene().removeMesh(this);
  13928. if (!doNotRecurse) {
  13929. // Particles
  13930. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13931. if (this.getScene().particleSystems[index].emitter === this) {
  13932. this.getScene().particleSystems[index].dispose();
  13933. index--;
  13934. }
  13935. }
  13936. // Children
  13937. var objects = this.getDescendants(true);
  13938. for (index = 0; index < objects.length; index++) {
  13939. objects[index].dispose();
  13940. }
  13941. }
  13942. else {
  13943. var childMeshes = this.getChildMeshes(true);
  13944. for (index = 0; index < childMeshes.length; index++) {
  13945. var child = childMeshes[index];
  13946. child.parent = null;
  13947. child.computeWorldMatrix(true);
  13948. }
  13949. }
  13950. // facet data
  13951. if (this._facetDataEnabled) {
  13952. this.disableFacetData();
  13953. }
  13954. this.onAfterWorldMatrixUpdateObservable.clear();
  13955. this.onCollideObservable.clear();
  13956. this.onCollisionPositionChangeObservable.clear();
  13957. this._isDisposed = true;
  13958. _super.prototype.dispose.call(this);
  13959. };
  13960. /**
  13961. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13962. * This Vector3 is expressed in the World space.
  13963. */
  13964. AbstractMesh.prototype.getDirection = function (localAxis) {
  13965. var result = BABYLON.Vector3.Zero();
  13966. this.getDirectionToRef(localAxis, result);
  13967. return result;
  13968. };
  13969. /**
  13970. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13971. * localAxis is expressed in the mesh local space.
  13972. * result is computed in the Wordl space from the mesh World matrix.
  13973. * Returns the AbstractMesh.
  13974. */
  13975. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13976. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13977. return this;
  13978. };
  13979. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13980. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13981. if (this.getScene().getRenderId() == 0) {
  13982. this.computeWorldMatrix(true);
  13983. }
  13984. var wm = this.getWorldMatrix();
  13985. if (space == BABYLON.Space.WORLD) {
  13986. var tmat = BABYLON.Tmp.Matrix[0];
  13987. wm.invertToRef(tmat);
  13988. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13989. }
  13990. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13991. this._pivotMatrix.m[12] = -point.x;
  13992. this._pivotMatrix.m[13] = -point.y;
  13993. this._pivotMatrix.m[14] = -point.z;
  13994. this._cache.pivotMatrixUpdated = true;
  13995. return this;
  13996. };
  13997. /**
  13998. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13999. */
  14000. AbstractMesh.prototype.getPivotPoint = function () {
  14001. var point = BABYLON.Vector3.Zero();
  14002. this.getPivotPointToRef(point);
  14003. return point;
  14004. };
  14005. /**
  14006. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14007. * Returns the AbstractMesh.
  14008. */
  14009. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14010. result.x = -this._pivotMatrix.m[12];
  14011. result.y = -this._pivotMatrix.m[13];
  14012. result.z = -this._pivotMatrix.m[14];
  14013. return this;
  14014. };
  14015. /**
  14016. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14017. */
  14018. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14019. var point = BABYLON.Vector3.Zero();
  14020. this.getAbsolutePivotPointToRef(point);
  14021. return point;
  14022. };
  14023. /**
  14024. * Defines the passed mesh as the parent of the current mesh.
  14025. * Returns the AbstractMesh.
  14026. */
  14027. AbstractMesh.prototype.setParent = function (mesh) {
  14028. var child = this;
  14029. var parent = mesh;
  14030. if (mesh == null) {
  14031. var rotation = BABYLON.Tmp.Quaternion[0];
  14032. var position = BABYLON.Tmp.Vector3[0];
  14033. var scale = BABYLON.Tmp.Vector3[1];
  14034. child.getWorldMatrix().decompose(scale, rotation, position);
  14035. if (child.rotationQuaternion) {
  14036. child.rotationQuaternion.copyFrom(rotation);
  14037. }
  14038. else {
  14039. rotation.toEulerAnglesToRef(child.rotation);
  14040. }
  14041. child.position.x = position.x;
  14042. child.position.y = position.y;
  14043. child.position.z = position.z;
  14044. }
  14045. else {
  14046. var position = BABYLON.Tmp.Vector3[0];
  14047. var m1 = BABYLON.Tmp.Matrix[0];
  14048. parent.getWorldMatrix().invertToRef(m1);
  14049. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  14050. child.position.copyFrom(position);
  14051. }
  14052. child.parent = parent;
  14053. return this;
  14054. };
  14055. /**
  14056. * Adds the passed mesh as a child to the current mesh.
  14057. * Returns the AbstractMesh.
  14058. */
  14059. AbstractMesh.prototype.addChild = function (mesh) {
  14060. mesh.setParent(this);
  14061. return this;
  14062. };
  14063. /**
  14064. * Removes the passed mesh from the current mesh children list.
  14065. * Returns the AbstractMesh.
  14066. */
  14067. AbstractMesh.prototype.removeChild = function (mesh) {
  14068. mesh.setParent(null);
  14069. return this;
  14070. };
  14071. /**
  14072. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14073. * Returns the AbstractMesh.
  14074. */
  14075. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14076. result.x = this._pivotMatrix.m[12];
  14077. result.y = this._pivotMatrix.m[13];
  14078. result.z = this._pivotMatrix.m[14];
  14079. this.getPivotPointToRef(result);
  14080. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14081. return this;
  14082. };
  14083. // Facet data
  14084. /**
  14085. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14086. * Returns the AbstractMesh.
  14087. */
  14088. AbstractMesh.prototype._initFacetData = function () {
  14089. if (!this._facetNormals) {
  14090. this._facetNormals = new Array();
  14091. }
  14092. if (!this._facetPositions) {
  14093. this._facetPositions = new Array();
  14094. }
  14095. if (!this._facetPartitioning) {
  14096. this._facetPartitioning = new Array();
  14097. }
  14098. this._facetNb = this.getIndices().length / 3;
  14099. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14100. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14101. for (var f = 0; f < this._facetNb; f++) {
  14102. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14103. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14104. }
  14105. this._facetDataEnabled = true;
  14106. return this;
  14107. };
  14108. /**
  14109. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14110. * This method can be called within the render loop.
  14111. * 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.
  14112. * Returns the AbstractMesh.
  14113. */
  14114. AbstractMesh.prototype.updateFacetData = function () {
  14115. if (!this._facetDataEnabled) {
  14116. this._initFacetData();
  14117. }
  14118. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14119. var indices = this.getIndices();
  14120. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14121. var bInfo = this.getBoundingInfo();
  14122. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14123. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14124. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14125. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14126. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14127. this._subDiv.max = this._partitioningSubdivisions;
  14128. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14129. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14130. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14131. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14132. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14133. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14134. // set the parameters for ComputeNormals()
  14135. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14136. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14137. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14138. this._facetParameters.bInfo = bInfo;
  14139. this._facetParameters.bbSize = this._bbSize;
  14140. this._facetParameters.subDiv = this._subDiv;
  14141. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14142. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14143. return this;
  14144. };
  14145. /**
  14146. * Returns the facetLocalNormals array.
  14147. * The normals are expressed in the mesh local space.
  14148. */
  14149. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14150. if (!this._facetNormals) {
  14151. this.updateFacetData();
  14152. }
  14153. return this._facetNormals;
  14154. };
  14155. /**
  14156. * Returns the facetLocalPositions array.
  14157. * The facet positions are expressed in the mesh local space.
  14158. */
  14159. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14160. if (!this._facetPositions) {
  14161. this.updateFacetData();
  14162. }
  14163. return this._facetPositions;
  14164. };
  14165. /**
  14166. * Returns the facetLocalPartioning array.
  14167. */
  14168. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14169. if (!this._facetPartitioning) {
  14170. this.updateFacetData();
  14171. }
  14172. return this._facetPartitioning;
  14173. };
  14174. /**
  14175. * Returns the i-th facet position in the world system.
  14176. * This method allocates a new Vector3 per call.
  14177. */
  14178. AbstractMesh.prototype.getFacetPosition = function (i) {
  14179. var pos = BABYLON.Vector3.Zero();
  14180. this.getFacetPositionToRef(i, pos);
  14181. return pos;
  14182. };
  14183. /**
  14184. * Sets the reference Vector3 with the i-th facet position in the world system.
  14185. * Returns the AbstractMesh.
  14186. */
  14187. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14188. var localPos = (this.getFacetLocalPositions())[i];
  14189. var world = this.getWorldMatrix();
  14190. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14191. return this;
  14192. };
  14193. /**
  14194. * Returns the i-th facet normal in the world system.
  14195. * This method allocates a new Vector3 per call.
  14196. */
  14197. AbstractMesh.prototype.getFacetNormal = function (i) {
  14198. var norm = BABYLON.Vector3.Zero();
  14199. this.getFacetNormalToRef(i, norm);
  14200. return norm;
  14201. };
  14202. /**
  14203. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14204. * Returns the AbstractMesh.
  14205. */
  14206. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14207. var localNorm = (this.getFacetLocalNormals())[i];
  14208. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14209. return this;
  14210. };
  14211. /**
  14212. * 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).
  14213. */
  14214. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14215. var bInfo = this.getBoundingInfo();
  14216. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14217. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14218. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14219. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14220. return null;
  14221. }
  14222. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14223. };
  14224. /**
  14225. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14226. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14227. * 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.
  14228. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14229. * 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.
  14230. */
  14231. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14232. if (checkFace === void 0) { checkFace = false; }
  14233. if (facing === void 0) { facing = true; }
  14234. var world = this.getWorldMatrix();
  14235. var invMat = BABYLON.Tmp.Matrix[5];
  14236. world.invertToRef(invMat);
  14237. var invVect = BABYLON.Tmp.Vector3[8];
  14238. var closest = null;
  14239. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14240. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14241. if (projected) {
  14242. // tranform the local computed projected vector to world coordinates
  14243. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14244. }
  14245. return closest;
  14246. };
  14247. /**
  14248. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14249. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14250. * 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.
  14251. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14252. * 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.
  14253. */
  14254. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14255. if (checkFace === void 0) { checkFace = false; }
  14256. if (facing === void 0) { facing = true; }
  14257. var closest = null;
  14258. var tmpx = 0.0;
  14259. var tmpy = 0.0;
  14260. var tmpz = 0.0;
  14261. var d = 0.0; // tmp dot facet normal * facet position
  14262. var t0 = 0.0;
  14263. var projx = 0.0;
  14264. var projy = 0.0;
  14265. var projz = 0.0;
  14266. // Get all the facets in the same partitioning block than (x, y, z)
  14267. var facetPositions = this.getFacetLocalPositions();
  14268. var facetNormals = this.getFacetLocalNormals();
  14269. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14270. if (!facetsInBlock) {
  14271. return null;
  14272. }
  14273. // Get the closest facet to (x, y, z)
  14274. var shortest = Number.MAX_VALUE; // init distance vars
  14275. var tmpDistance = shortest;
  14276. var fib; // current facet in the block
  14277. var norm; // current facet normal
  14278. var p0; // current facet barycenter position
  14279. // loop on all the facets in the current partitioning block
  14280. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14281. fib = facetsInBlock[idx];
  14282. norm = facetNormals[fib];
  14283. p0 = facetPositions[fib];
  14284. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14285. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14286. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14287. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14288. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14289. projx = x + norm.x * t0;
  14290. projy = y + norm.y * t0;
  14291. projz = z + norm.z * t0;
  14292. tmpx = projx - x;
  14293. tmpy = projy - y;
  14294. tmpz = projz - z;
  14295. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14296. if (tmpDistance < shortest) {
  14297. shortest = tmpDistance;
  14298. closest = fib;
  14299. if (projected) {
  14300. projected.x = projx;
  14301. projected.y = projy;
  14302. projected.z = projz;
  14303. }
  14304. }
  14305. }
  14306. }
  14307. return closest;
  14308. };
  14309. /**
  14310. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14311. */
  14312. AbstractMesh.prototype.getFacetDataParameters = function () {
  14313. return this._facetParameters;
  14314. };
  14315. /**
  14316. * Disables the feature FacetData and frees the related memory.
  14317. * Returns the AbstractMesh.
  14318. */
  14319. AbstractMesh.prototype.disableFacetData = function () {
  14320. if (this._facetDataEnabled) {
  14321. this._facetDataEnabled = false;
  14322. this._facetPositions = null;
  14323. this._facetNormals = null;
  14324. this._facetPartitioning = null;
  14325. this._facetParameters = null;
  14326. }
  14327. return this;
  14328. };
  14329. /**
  14330. * Creates new normals data for the mesh.
  14331. * @param updatable.
  14332. */
  14333. AbstractMesh.prototype.createNormals = function (updatable) {
  14334. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14335. var indices = this.getIndices();
  14336. var normals;
  14337. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14338. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14339. }
  14340. else {
  14341. normals = [];
  14342. }
  14343. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14344. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14345. };
  14346. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14347. var engine = this.getEngine();
  14348. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14349. this._isOccluded = false;
  14350. return;
  14351. }
  14352. if (this.isOcclusionQueryInProgress) {
  14353. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14354. if (isOcclusionQueryAvailable) {
  14355. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14356. this._isOcclusionQueryInProgress = false;
  14357. this._occlusionInternalRetryCounter = 0;
  14358. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14359. }
  14360. else {
  14361. this._occlusionInternalRetryCounter++;
  14362. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14363. this._isOcclusionQueryInProgress = false;
  14364. this._occlusionInternalRetryCounter = 0;
  14365. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14366. // if strict continue the last state of the object.
  14367. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14368. }
  14369. else {
  14370. return;
  14371. }
  14372. }
  14373. }
  14374. var scene = this.getScene();
  14375. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14376. if (!this._occlusionQuery) {
  14377. this._occlusionQuery = engine.createQuery();
  14378. }
  14379. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14380. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14381. engine.endQuery(this.occlusionQueryAlgorithmType);
  14382. this._isOcclusionQueryInProgress = true;
  14383. };
  14384. // Statics
  14385. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14386. AbstractMesh._BILLBOARDMODE_X = 1;
  14387. AbstractMesh._BILLBOARDMODE_Y = 2;
  14388. AbstractMesh._BILLBOARDMODE_Z = 4;
  14389. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14390. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14391. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14392. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14393. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14394. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14395. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14396. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14397. return AbstractMesh;
  14398. }(BABYLON.Node));
  14399. BABYLON.AbstractMesh = AbstractMesh;
  14400. })(BABYLON || (BABYLON = {}));
  14401. //# sourceMappingURL=babylon.abstractMesh.js.map
  14402. var BABYLON;
  14403. (function (BABYLON) {
  14404. var Light = (function (_super) {
  14405. __extends(Light, _super);
  14406. /**
  14407. * Creates a Light object in the scene.
  14408. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14409. */
  14410. function Light(name, scene) {
  14411. var _this = _super.call(this, name, scene) || this;
  14412. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14413. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14414. _this.intensity = 1.0;
  14415. _this.range = Number.MAX_VALUE;
  14416. /**
  14417. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14418. * of light.
  14419. */
  14420. _this._photometricScale = 1.0;
  14421. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14422. _this._radius = 0.00001;
  14423. _this.renderPriority = 0;
  14424. /**
  14425. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14426. * the current shadow generator.
  14427. */
  14428. _this.shadowEnabled = true;
  14429. _this._excludeWithLayerMask = 0;
  14430. _this._includeOnlyWithLayerMask = 0;
  14431. _this._lightmapMode = 0;
  14432. _this._excludedMeshesIds = new Array();
  14433. _this._includedOnlyMeshesIds = new Array();
  14434. _this.getScene().addLight(_this);
  14435. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14436. _this._buildUniformLayout();
  14437. _this.includedOnlyMeshes = new Array();
  14438. _this.excludedMeshes = new Array();
  14439. _this._resyncMeshes();
  14440. return _this;
  14441. }
  14442. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14443. /**
  14444. * If every light affecting the material is in this lightmapMode,
  14445. * material.lightmapTexture adds or multiplies
  14446. * (depends on material.useLightmapAsShadowmap)
  14447. * after every other light calculations.
  14448. */
  14449. get: function () {
  14450. return Light._LIGHTMAP_DEFAULT;
  14451. },
  14452. enumerable: true,
  14453. configurable: true
  14454. });
  14455. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14456. /**
  14457. * material.lightmapTexture as only diffuse lighting from this light
  14458. * adds pnly specular lighting from this light
  14459. * adds dynamic shadows
  14460. */
  14461. get: function () {
  14462. return Light._LIGHTMAP_SPECULAR;
  14463. },
  14464. enumerable: true,
  14465. configurable: true
  14466. });
  14467. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14468. /**
  14469. * material.lightmapTexture as only lighting
  14470. * no light calculation from this light
  14471. * only adds dynamic shadows from this light
  14472. */
  14473. get: function () {
  14474. return Light._LIGHTMAP_SHADOWSONLY;
  14475. },
  14476. enumerable: true,
  14477. configurable: true
  14478. });
  14479. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14480. /**
  14481. * Each light type uses the default quantity according to its type:
  14482. * point/spot lights use luminous intensity
  14483. * directional lights use illuminance
  14484. */
  14485. get: function () {
  14486. return Light._INTENSITYMODE_AUTOMATIC;
  14487. },
  14488. enumerable: true,
  14489. configurable: true
  14490. });
  14491. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14492. /**
  14493. * lumen (lm)
  14494. */
  14495. get: function () {
  14496. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14497. },
  14498. enumerable: true,
  14499. configurable: true
  14500. });
  14501. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14502. /**
  14503. * candela (lm/sr)
  14504. */
  14505. get: function () {
  14506. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14507. },
  14508. enumerable: true,
  14509. configurable: true
  14510. });
  14511. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14512. /**
  14513. * lux (lm/m^2)
  14514. */
  14515. get: function () {
  14516. return Light._INTENSITYMODE_ILLUMINANCE;
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14522. /**
  14523. * nit (cd/m^2)
  14524. */
  14525. get: function () {
  14526. return Light._INTENSITYMODE_LUMINANCE;
  14527. },
  14528. enumerable: true,
  14529. configurable: true
  14530. });
  14531. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14532. /**
  14533. * Light type const id of the point light.
  14534. */
  14535. get: function () {
  14536. return Light._LIGHTTYPEID_POINTLIGHT;
  14537. },
  14538. enumerable: true,
  14539. configurable: true
  14540. });
  14541. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14542. /**
  14543. * Light type const id of the directional light.
  14544. */
  14545. get: function () {
  14546. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14547. },
  14548. enumerable: true,
  14549. configurable: true
  14550. });
  14551. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14552. /**
  14553. * Light type const id of the spot light.
  14554. */
  14555. get: function () {
  14556. return Light._LIGHTTYPEID_SPOTLIGHT;
  14557. },
  14558. enumerable: true,
  14559. configurable: true
  14560. });
  14561. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14562. /**
  14563. * Light type const id of the hemispheric light.
  14564. */
  14565. get: function () {
  14566. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14567. },
  14568. enumerable: true,
  14569. configurable: true
  14570. });
  14571. Object.defineProperty(Light.prototype, "intensityMode", {
  14572. /**
  14573. * Gets the photometric scale used to interpret the intensity.
  14574. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14575. */
  14576. get: function () {
  14577. return this._intensityMode;
  14578. },
  14579. /**
  14580. * Sets the photometric scale used to interpret the intensity.
  14581. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14582. */
  14583. set: function (value) {
  14584. this._intensityMode = value;
  14585. this._computePhotometricScale();
  14586. },
  14587. enumerable: true,
  14588. configurable: true
  14589. });
  14590. ;
  14591. ;
  14592. Object.defineProperty(Light.prototype, "radius", {
  14593. /**
  14594. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14595. */
  14596. get: function () {
  14597. return this._radius;
  14598. },
  14599. /**
  14600. * sets the light radius used by PBR Materials to simulate soft area lights.
  14601. */
  14602. set: function (value) {
  14603. this._radius = value;
  14604. this._computePhotometricScale();
  14605. },
  14606. enumerable: true,
  14607. configurable: true
  14608. });
  14609. ;
  14610. ;
  14611. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14612. get: function () {
  14613. return this._includedOnlyMeshes;
  14614. },
  14615. set: function (value) {
  14616. this._includedOnlyMeshes = value;
  14617. this._hookArrayForIncludedOnly(value);
  14618. },
  14619. enumerable: true,
  14620. configurable: true
  14621. });
  14622. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14623. get: function () {
  14624. return this._excludedMeshes;
  14625. },
  14626. set: function (value) {
  14627. this._excludedMeshes = value;
  14628. this._hookArrayForExcluded(value);
  14629. },
  14630. enumerable: true,
  14631. configurable: true
  14632. });
  14633. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14634. get: function () {
  14635. return this._excludeWithLayerMask;
  14636. },
  14637. set: function (value) {
  14638. this._excludeWithLayerMask = value;
  14639. this._resyncMeshes();
  14640. },
  14641. enumerable: true,
  14642. configurable: true
  14643. });
  14644. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14645. get: function () {
  14646. return this._includeOnlyWithLayerMask;
  14647. },
  14648. set: function (value) {
  14649. this._includeOnlyWithLayerMask = value;
  14650. this._resyncMeshes();
  14651. },
  14652. enumerable: true,
  14653. configurable: true
  14654. });
  14655. Object.defineProperty(Light.prototype, "lightmapMode", {
  14656. get: function () {
  14657. return this._lightmapMode;
  14658. },
  14659. set: function (value) {
  14660. if (this._lightmapMode === value) {
  14661. return;
  14662. }
  14663. this._lightmapMode = value;
  14664. this._markMeshesAsLightDirty();
  14665. },
  14666. enumerable: true,
  14667. configurable: true
  14668. });
  14669. Light.prototype._buildUniformLayout = function () {
  14670. // Overridden
  14671. };
  14672. /**
  14673. * Returns the string "Light".
  14674. */
  14675. Light.prototype.getClassName = function () {
  14676. return "Light";
  14677. };
  14678. /**
  14679. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14680. */
  14681. Light.prototype.toString = function (fullDetails) {
  14682. var ret = "Name: " + this.name;
  14683. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14684. if (this.animations) {
  14685. for (var i = 0; i < this.animations.length; i++) {
  14686. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14687. }
  14688. }
  14689. if (fullDetails) {
  14690. }
  14691. return ret;
  14692. };
  14693. /**
  14694. * Set the enabled state of this node.
  14695. * @param {boolean} value - the new enabled state
  14696. * @see isEnabled
  14697. */
  14698. Light.prototype.setEnabled = function (value) {
  14699. _super.prototype.setEnabled.call(this, value);
  14700. this._resyncMeshes();
  14701. };
  14702. /**
  14703. * Returns the Light associated shadow generator.
  14704. */
  14705. Light.prototype.getShadowGenerator = function () {
  14706. return this._shadowGenerator;
  14707. };
  14708. /**
  14709. * Returns a Vector3, the absolute light position in the World.
  14710. */
  14711. Light.prototype.getAbsolutePosition = function () {
  14712. return BABYLON.Vector3.Zero();
  14713. };
  14714. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14715. };
  14716. Light.prototype._getWorldMatrix = function () {
  14717. return BABYLON.Matrix.Identity();
  14718. };
  14719. /**
  14720. * Boolean : True if the light will affect the passed mesh.
  14721. */
  14722. Light.prototype.canAffectMesh = function (mesh) {
  14723. if (!mesh) {
  14724. return true;
  14725. }
  14726. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14727. return false;
  14728. }
  14729. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14730. return false;
  14731. }
  14732. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14733. return false;
  14734. }
  14735. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14736. return false;
  14737. }
  14738. return true;
  14739. };
  14740. /**
  14741. * Returns the light World matrix.
  14742. */
  14743. Light.prototype.getWorldMatrix = function () {
  14744. this._currentRenderId = this.getScene().getRenderId();
  14745. var worldMatrix = this._getWorldMatrix();
  14746. if (this.parent && this.parent.getWorldMatrix) {
  14747. if (!this._parentedWorldMatrix) {
  14748. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14749. }
  14750. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14751. this._markSyncedWithParent();
  14752. return this._parentedWorldMatrix;
  14753. }
  14754. return worldMatrix;
  14755. };
  14756. /**
  14757. * Sort function to order lights for rendering.
  14758. * @param a First Light object to compare to second.
  14759. * @param b Second Light object to compare first.
  14760. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14761. */
  14762. Light.compareLightsPriority = function (a, b) {
  14763. //shadow-casting lights have priority over non-shadow-casting lights
  14764. //the renderPrioirty is a secondary sort criterion
  14765. if (a.shadowEnabled !== b.shadowEnabled) {
  14766. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14767. }
  14768. return b.renderPriority - a.renderPriority;
  14769. };
  14770. /**
  14771. * Disposes the light.
  14772. */
  14773. Light.prototype.dispose = function () {
  14774. if (this._shadowGenerator) {
  14775. this._shadowGenerator.dispose();
  14776. this._shadowGenerator = null;
  14777. }
  14778. // Animations
  14779. this.getScene().stopAnimation(this);
  14780. // Remove from meshes
  14781. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14782. var mesh = _a[_i];
  14783. mesh._removeLightSource(this);
  14784. }
  14785. this._uniformBuffer.dispose();
  14786. // Remove from scene
  14787. this.getScene().removeLight(this);
  14788. _super.prototype.dispose.call(this);
  14789. };
  14790. /**
  14791. * Returns the light type ID (integer).
  14792. */
  14793. Light.prototype.getTypeID = function () {
  14794. return 0;
  14795. };
  14796. /**
  14797. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14798. */
  14799. Light.prototype.getScaledIntensity = function () {
  14800. return this._photometricScale * this.intensity;
  14801. };
  14802. /**
  14803. * Returns a new Light object, named "name", from the current one.
  14804. */
  14805. Light.prototype.clone = function (name) {
  14806. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14807. };
  14808. /**
  14809. * Serializes the current light into a Serialization object.
  14810. * Returns the serialized object.
  14811. */
  14812. Light.prototype.serialize = function () {
  14813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14814. // Type
  14815. serializationObject.type = this.getTypeID();
  14816. // Parent
  14817. if (this.parent) {
  14818. serializationObject.parentId = this.parent.id;
  14819. }
  14820. // Inclusion / exclusions
  14821. if (this.excludedMeshes.length > 0) {
  14822. serializationObject.excludedMeshesIds = [];
  14823. this.excludedMeshes.forEach(function (mesh) {
  14824. serializationObject.excludedMeshesIds.push(mesh.id);
  14825. });
  14826. }
  14827. if (this.includedOnlyMeshes.length > 0) {
  14828. serializationObject.includedOnlyMeshesIds = [];
  14829. this.includedOnlyMeshes.forEach(function (mesh) {
  14830. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14831. });
  14832. }
  14833. // Animations
  14834. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14835. serializationObject.ranges = this.serializeAnimationRanges();
  14836. return serializationObject;
  14837. };
  14838. /**
  14839. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14840. * This new light is named "name" and added to the passed scene.
  14841. */
  14842. Light.GetConstructorFromName = function (type, name, scene) {
  14843. switch (type) {
  14844. case 0:
  14845. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14846. case 1:
  14847. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14848. case 2:
  14849. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14850. case 3:
  14851. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14852. }
  14853. };
  14854. /**
  14855. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14856. */
  14857. Light.Parse = function (parsedLight, scene) {
  14858. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14859. // Inclusion / exclusions
  14860. if (parsedLight.excludedMeshesIds) {
  14861. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14862. }
  14863. if (parsedLight.includedOnlyMeshesIds) {
  14864. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14865. }
  14866. // Parent
  14867. if (parsedLight.parentId) {
  14868. light._waitingParentId = parsedLight.parentId;
  14869. }
  14870. // Animations
  14871. if (parsedLight.animations) {
  14872. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14873. var parsedAnimation = parsedLight.animations[animationIndex];
  14874. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14875. }
  14876. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14877. }
  14878. if (parsedLight.autoAnimate) {
  14879. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14880. }
  14881. return light;
  14882. };
  14883. Light.prototype._hookArrayForExcluded = function (array) {
  14884. var _this = this;
  14885. var oldPush = array.push;
  14886. array.push = function () {
  14887. var items = [];
  14888. for (var _i = 0; _i < arguments.length; _i++) {
  14889. items[_i] = arguments[_i];
  14890. }
  14891. var result = oldPush.apply(array, items);
  14892. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14893. var item = items_1[_a];
  14894. item._resyncLighSource(_this);
  14895. }
  14896. return result;
  14897. };
  14898. var oldSplice = array.splice;
  14899. array.splice = function (index, deleteCount) {
  14900. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14901. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14902. var item = deleted_1[_i];
  14903. item._resyncLighSource(_this);
  14904. }
  14905. return deleted;
  14906. };
  14907. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14908. var item = array_1[_i];
  14909. item._resyncLighSource(this);
  14910. }
  14911. };
  14912. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14913. var _this = this;
  14914. var oldPush = array.push;
  14915. array.push = function () {
  14916. var items = [];
  14917. for (var _i = 0; _i < arguments.length; _i++) {
  14918. items[_i] = arguments[_i];
  14919. }
  14920. var result = oldPush.apply(array, items);
  14921. _this._resyncMeshes();
  14922. return result;
  14923. };
  14924. var oldSplice = array.splice;
  14925. array.splice = function (index, deleteCount) {
  14926. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14927. _this._resyncMeshes();
  14928. return deleted;
  14929. };
  14930. this._resyncMeshes();
  14931. };
  14932. Light.prototype._resyncMeshes = function () {
  14933. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14934. var mesh = _a[_i];
  14935. mesh._resyncLighSource(this);
  14936. }
  14937. };
  14938. Light.prototype._markMeshesAsLightDirty = function () {
  14939. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14940. var mesh = _a[_i];
  14941. if (mesh._lightSources.indexOf(this) !== -1) {
  14942. mesh._markSubMeshesAsLightDirty();
  14943. }
  14944. }
  14945. };
  14946. /**
  14947. * Recomputes the cached photometric scale if needed.
  14948. */
  14949. Light.prototype._computePhotometricScale = function () {
  14950. this._photometricScale = this._getPhotometricScale();
  14951. this.getScene().resetCachedMaterial();
  14952. };
  14953. /**
  14954. * Returns the Photometric Scale according to the light type and intensity mode.
  14955. */
  14956. Light.prototype._getPhotometricScale = function () {
  14957. var photometricScale = 0.0;
  14958. var lightTypeID = this.getTypeID();
  14959. //get photometric mode
  14960. var photometricMode = this.intensityMode;
  14961. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14962. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14963. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14964. }
  14965. else {
  14966. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14967. }
  14968. }
  14969. //compute photometric scale
  14970. switch (lightTypeID) {
  14971. case Light.LIGHTTYPEID_POINTLIGHT:
  14972. case Light.LIGHTTYPEID_SPOTLIGHT:
  14973. switch (photometricMode) {
  14974. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14975. photometricScale = 1.0 / (4.0 * Math.PI);
  14976. break;
  14977. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14978. photometricScale = 1.0;
  14979. break;
  14980. case Light.INTENSITYMODE_LUMINANCE:
  14981. photometricScale = this.radius * this.radius;
  14982. break;
  14983. }
  14984. break;
  14985. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14986. switch (photometricMode) {
  14987. case Light.INTENSITYMODE_ILLUMINANCE:
  14988. photometricScale = 1.0;
  14989. break;
  14990. case Light.INTENSITYMODE_LUMINANCE:
  14991. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14992. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14993. var apexAngleRadians = this.radius;
  14994. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14995. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14996. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14997. photometricScale = solidAngle;
  14998. break;
  14999. }
  15000. break;
  15001. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15002. // No fall off in hemisperic light.
  15003. photometricScale = 1.0;
  15004. break;
  15005. }
  15006. return photometricScale;
  15007. };
  15008. Light.prototype._reorderLightsInScene = function () {
  15009. var scene = this.getScene();
  15010. if (this.renderPriority != 0) {
  15011. scene.requireLightSorting = true;
  15012. }
  15013. this.getScene().sortLightsByPriority();
  15014. };
  15015. //lightmapMode Consts
  15016. Light._LIGHTMAP_DEFAULT = 0;
  15017. Light._LIGHTMAP_SPECULAR = 1;
  15018. Light._LIGHTMAP_SHADOWSONLY = 2;
  15019. // Intensity Mode Consts
  15020. Light._INTENSITYMODE_AUTOMATIC = 0;
  15021. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15022. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15023. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15024. Light._INTENSITYMODE_LUMINANCE = 4;
  15025. // Light types ids const.
  15026. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15027. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15028. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15029. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15030. __decorate([
  15031. BABYLON.serializeAsColor3()
  15032. ], Light.prototype, "diffuse", void 0);
  15033. __decorate([
  15034. BABYLON.serializeAsColor3()
  15035. ], Light.prototype, "specular", void 0);
  15036. __decorate([
  15037. BABYLON.serialize()
  15038. ], Light.prototype, "intensity", void 0);
  15039. __decorate([
  15040. BABYLON.serialize()
  15041. ], Light.prototype, "range", void 0);
  15042. __decorate([
  15043. BABYLON.serialize()
  15044. ], Light.prototype, "intensityMode", null);
  15045. __decorate([
  15046. BABYLON.serialize()
  15047. ], Light.prototype, "radius", null);
  15048. __decorate([
  15049. BABYLON.serialize()
  15050. ], Light.prototype, "_renderPriority", void 0);
  15051. __decorate([
  15052. BABYLON.expandToProperty("_reorderLightsInScene")
  15053. ], Light.prototype, "renderPriority", void 0);
  15054. __decorate([
  15055. BABYLON.serialize()
  15056. ], Light.prototype, "shadowEnabled", void 0);
  15057. __decorate([
  15058. BABYLON.serialize("excludeWithLayerMask")
  15059. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15060. __decorate([
  15061. BABYLON.serialize("includeOnlyWithLayerMask")
  15062. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15063. __decorate([
  15064. BABYLON.serialize("lightmapMode")
  15065. ], Light.prototype, "_lightmapMode", void 0);
  15066. return Light;
  15067. }(BABYLON.Node));
  15068. BABYLON.Light = Light;
  15069. })(BABYLON || (BABYLON = {}));
  15070. //# sourceMappingURL=babylon.light.js.map
  15071. var BABYLON;
  15072. (function (BABYLON) {
  15073. var Camera = (function (_super) {
  15074. __extends(Camera, _super);
  15075. function Camera(name, position, scene) {
  15076. var _this = _super.call(this, name, scene) || this;
  15077. _this.upVector = BABYLON.Vector3.Up();
  15078. _this.orthoLeft = null;
  15079. _this.orthoRight = null;
  15080. _this.orthoBottom = null;
  15081. _this.orthoTop = null;
  15082. _this.fov = 0.8;
  15083. _this.minZ = 1;
  15084. _this.maxZ = 10000.0;
  15085. _this.inertia = 0.9;
  15086. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15087. _this.isIntermediate = false;
  15088. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15089. _this.layerMask = 0x0FFFFFFF;
  15090. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15091. // Camera rig members
  15092. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15093. _this._rigCameras = new Array();
  15094. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15095. _this._skipRendering = false;
  15096. _this.customRenderTargets = new Array();
  15097. // Observables
  15098. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15099. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15100. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15101. _this.onRestoreStateObservable = new BABYLON.Observable();
  15102. // Cache
  15103. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15104. _this._projectionMatrix = new BABYLON.Matrix();
  15105. _this._doNotComputeProjectionMatrix = false;
  15106. _this._postProcesses = new Array();
  15107. _this._transformMatrix = BABYLON.Matrix.Zero();
  15108. _this._activeMeshes = new BABYLON.SmartArray(256);
  15109. _this._globalPosition = BABYLON.Vector3.Zero();
  15110. _this._refreshFrustumPlanes = true;
  15111. _this.getScene().addCamera(_this);
  15112. if (!_this.getScene().activeCamera) {
  15113. _this.getScene().activeCamera = _this;
  15114. }
  15115. _this.position = position;
  15116. return _this;
  15117. }
  15118. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15119. get: function () {
  15120. return Camera._PERSPECTIVE_CAMERA;
  15121. },
  15122. enumerable: true,
  15123. configurable: true
  15124. });
  15125. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15126. get: function () {
  15127. return Camera._ORTHOGRAPHIC_CAMERA;
  15128. },
  15129. enumerable: true,
  15130. configurable: true
  15131. });
  15132. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15133. get: function () {
  15134. return Camera._FOVMODE_VERTICAL_FIXED;
  15135. },
  15136. enumerable: true,
  15137. configurable: true
  15138. });
  15139. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15140. get: function () {
  15141. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15142. },
  15143. enumerable: true,
  15144. configurable: true
  15145. });
  15146. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15147. get: function () {
  15148. return Camera._RIG_MODE_NONE;
  15149. },
  15150. enumerable: true,
  15151. configurable: true
  15152. });
  15153. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15154. get: function () {
  15155. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15156. },
  15157. enumerable: true,
  15158. configurable: true
  15159. });
  15160. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15161. get: function () {
  15162. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15163. },
  15164. enumerable: true,
  15165. configurable: true
  15166. });
  15167. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15168. get: function () {
  15169. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15170. },
  15171. enumerable: true,
  15172. configurable: true
  15173. });
  15174. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15175. get: function () {
  15176. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15177. },
  15178. enumerable: true,
  15179. configurable: true
  15180. });
  15181. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15182. get: function () {
  15183. return Camera._RIG_MODE_VR;
  15184. },
  15185. enumerable: true,
  15186. configurable: true
  15187. });
  15188. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15189. get: function () {
  15190. return Camera._RIG_MODE_WEBVR;
  15191. },
  15192. enumerable: true,
  15193. configurable: true
  15194. });
  15195. /**
  15196. * Store current camera state (fov, position, etc..)
  15197. */
  15198. Camera.prototype.storeState = function () {
  15199. this._stateStored = true;
  15200. this._storedFov = this.fov;
  15201. return this;
  15202. };
  15203. /**
  15204. * Restores the camera state values if it has been stored. You must call storeState() first
  15205. */
  15206. Camera.prototype._restoreStateValues = function () {
  15207. if (!this._stateStored) {
  15208. return false;
  15209. }
  15210. this.fov = this._storedFov;
  15211. return true;
  15212. };
  15213. /**
  15214. * Restored camera state. You must call storeState() first
  15215. */
  15216. Camera.prototype.restoreState = function () {
  15217. if (this._restoreStateValues()) {
  15218. this.onRestoreStateObservable.notifyObservers(this);
  15219. return true;
  15220. }
  15221. return false;
  15222. };
  15223. Camera.prototype.getClassName = function () {
  15224. return "Camera";
  15225. };
  15226. /**
  15227. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15228. */
  15229. Camera.prototype.toString = function (fullDetails) {
  15230. var ret = "Name: " + this.name;
  15231. ret += ", type: " + this.getClassName();
  15232. if (this.animations) {
  15233. for (var i = 0; i < this.animations.length; i++) {
  15234. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15235. }
  15236. }
  15237. if (fullDetails) {
  15238. }
  15239. return ret;
  15240. };
  15241. Object.defineProperty(Camera.prototype, "globalPosition", {
  15242. get: function () {
  15243. return this._globalPosition;
  15244. },
  15245. enumerable: true,
  15246. configurable: true
  15247. });
  15248. Camera.prototype.getActiveMeshes = function () {
  15249. return this._activeMeshes;
  15250. };
  15251. Camera.prototype.isActiveMesh = function (mesh) {
  15252. return (this._activeMeshes.indexOf(mesh) !== -1);
  15253. };
  15254. //Cache
  15255. Camera.prototype._initCache = function () {
  15256. _super.prototype._initCache.call(this);
  15257. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15258. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15259. this._cache.mode = undefined;
  15260. this._cache.minZ = undefined;
  15261. this._cache.maxZ = undefined;
  15262. this._cache.fov = undefined;
  15263. this._cache.fovMode = undefined;
  15264. this._cache.aspectRatio = undefined;
  15265. this._cache.orthoLeft = undefined;
  15266. this._cache.orthoRight = undefined;
  15267. this._cache.orthoBottom = undefined;
  15268. this._cache.orthoTop = undefined;
  15269. this._cache.renderWidth = undefined;
  15270. this._cache.renderHeight = undefined;
  15271. };
  15272. Camera.prototype._updateCache = function (ignoreParentClass) {
  15273. if (!ignoreParentClass) {
  15274. _super.prototype._updateCache.call(this);
  15275. }
  15276. var engine = this.getEngine();
  15277. this._cache.position.copyFrom(this.position);
  15278. this._cache.upVector.copyFrom(this.upVector);
  15279. };
  15280. // Synchronized
  15281. Camera.prototype._isSynchronized = function () {
  15282. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15283. };
  15284. Camera.prototype._isSynchronizedViewMatrix = function () {
  15285. if (!_super.prototype._isSynchronized.call(this))
  15286. return false;
  15287. return this._cache.position.equals(this.position)
  15288. && this._cache.upVector.equals(this.upVector)
  15289. && this.isSynchronizedWithParent();
  15290. };
  15291. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15292. var check = this._cache.mode === this.mode
  15293. && this._cache.minZ === this.minZ
  15294. && this._cache.maxZ === this.maxZ;
  15295. if (!check) {
  15296. return false;
  15297. }
  15298. var engine = this.getEngine();
  15299. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15300. check = this._cache.fov === this.fov
  15301. && this._cache.fovMode === this.fovMode
  15302. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15303. }
  15304. else {
  15305. check = this._cache.orthoLeft === this.orthoLeft
  15306. && this._cache.orthoRight === this.orthoRight
  15307. && this._cache.orthoBottom === this.orthoBottom
  15308. && this._cache.orthoTop === this.orthoTop
  15309. && this._cache.renderWidth === engine.getRenderWidth()
  15310. && this._cache.renderHeight === engine.getRenderHeight();
  15311. }
  15312. return check;
  15313. };
  15314. // Controls
  15315. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15316. };
  15317. Camera.prototype.detachControl = function (element) {
  15318. };
  15319. Camera.prototype.update = function () {
  15320. this._checkInputs();
  15321. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15322. this._updateRigCameras();
  15323. }
  15324. };
  15325. Camera.prototype._checkInputs = function () {
  15326. this.onAfterCheckInputsObservable.notifyObservers(this);
  15327. };
  15328. Object.defineProperty(Camera.prototype, "rigCameras", {
  15329. get: function () {
  15330. return this._rigCameras;
  15331. },
  15332. enumerable: true,
  15333. configurable: true
  15334. });
  15335. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15336. get: function () {
  15337. return this._rigPostProcess;
  15338. },
  15339. enumerable: true,
  15340. configurable: true
  15341. });
  15342. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15343. // invalidate framebuffer
  15344. if (this._postProcesses.length > 0) {
  15345. this._postProcesses[0].markTextureDirty();
  15346. }
  15347. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15348. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15349. var cam = this._rigCameras[i];
  15350. var rigPostProcess = cam._rigPostProcess;
  15351. // for VR rig, there does not have to be a post process
  15352. if (rigPostProcess) {
  15353. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15354. if (isPass) {
  15355. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15356. cam.isIntermediate = this._postProcesses.length === 0;
  15357. }
  15358. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15359. rigPostProcess.markTextureDirty();
  15360. }
  15361. else {
  15362. cam._postProcesses = this._postProcesses.slice(0);
  15363. }
  15364. }
  15365. };
  15366. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15367. if (insertAt === void 0) { insertAt = null; }
  15368. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15369. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15370. return 0;
  15371. }
  15372. if (insertAt == null || insertAt < 0) {
  15373. this._postProcesses.push(postProcess);
  15374. }
  15375. else {
  15376. this._postProcesses.splice(insertAt, 0, postProcess);
  15377. }
  15378. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15379. return this._postProcesses.indexOf(postProcess);
  15380. };
  15381. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15382. if (atIndices === void 0) { atIndices = null; }
  15383. var result = [];
  15384. var i;
  15385. var index;
  15386. if (!atIndices) {
  15387. var idx = this._postProcesses.indexOf(postProcess);
  15388. if (idx !== -1) {
  15389. this._postProcesses.splice(idx, 1);
  15390. }
  15391. }
  15392. else {
  15393. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15394. // iterate descending, so can just splice as we go
  15395. for (i = atIndices.length - 1; i >= 0; i--) {
  15396. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15397. result.push(i);
  15398. continue;
  15399. }
  15400. index = atIndices[i];
  15401. this._postProcesses.splice(index, 1);
  15402. }
  15403. }
  15404. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15405. return result;
  15406. };
  15407. Camera.prototype.getWorldMatrix = function () {
  15408. if (!this._worldMatrix) {
  15409. this._worldMatrix = BABYLON.Matrix.Identity();
  15410. }
  15411. var viewMatrix = this.getViewMatrix();
  15412. viewMatrix.invertToRef(this._worldMatrix);
  15413. return this._worldMatrix;
  15414. };
  15415. Camera.prototype._getViewMatrix = function () {
  15416. return BABYLON.Matrix.Identity();
  15417. };
  15418. Camera.prototype.getViewMatrix = function (force) {
  15419. if (!force && this._isSynchronizedViewMatrix()) {
  15420. return this._computedViewMatrix;
  15421. }
  15422. this.updateCache();
  15423. this._computedViewMatrix = this._getViewMatrix();
  15424. this._currentRenderId = this.getScene().getRenderId();
  15425. this._refreshFrustumPlanes = true;
  15426. if (!this.parent || !this.parent.getWorldMatrix) {
  15427. this._globalPosition.copyFrom(this.position);
  15428. }
  15429. else {
  15430. if (!this._worldMatrix) {
  15431. this._worldMatrix = BABYLON.Matrix.Identity();
  15432. }
  15433. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15434. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15435. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15436. this._computedViewMatrix.invert();
  15437. this._markSyncedWithParent();
  15438. }
  15439. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15440. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15441. }
  15442. this.onViewMatrixChangedObservable.notifyObservers(this);
  15443. return this._computedViewMatrix;
  15444. };
  15445. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15446. this._doNotComputeProjectionMatrix = true;
  15447. if (projection !== undefined) {
  15448. this._projectionMatrix = projection;
  15449. }
  15450. };
  15451. ;
  15452. Camera.prototype.unfreezeProjectionMatrix = function () {
  15453. this._doNotComputeProjectionMatrix = false;
  15454. };
  15455. ;
  15456. Camera.prototype.getProjectionMatrix = function (force) {
  15457. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15458. return this._projectionMatrix;
  15459. }
  15460. // Cache
  15461. this._cache.mode = this.mode;
  15462. this._cache.minZ = this.minZ;
  15463. this._cache.maxZ = this.maxZ;
  15464. // Matrix
  15465. this._refreshFrustumPlanes = true;
  15466. var engine = this.getEngine();
  15467. var scene = this.getScene();
  15468. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15469. this._cache.fov = this.fov;
  15470. this._cache.fovMode = this.fovMode;
  15471. this._cache.aspectRatio = engine.getAspectRatio(this);
  15472. if (this.minZ <= 0) {
  15473. this.minZ = 0.1;
  15474. }
  15475. if (scene.useRightHandedSystem) {
  15476. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15477. }
  15478. else {
  15479. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15480. }
  15481. }
  15482. else {
  15483. var halfWidth = engine.getRenderWidth() / 2.0;
  15484. var halfHeight = engine.getRenderHeight() / 2.0;
  15485. if (scene.useRightHandedSystem) {
  15486. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15487. }
  15488. else {
  15489. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15490. }
  15491. this._cache.orthoLeft = this.orthoLeft;
  15492. this._cache.orthoRight = this.orthoRight;
  15493. this._cache.orthoBottom = this.orthoBottom;
  15494. this._cache.orthoTop = this.orthoTop;
  15495. this._cache.renderWidth = engine.getRenderWidth();
  15496. this._cache.renderHeight = engine.getRenderHeight();
  15497. }
  15498. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15499. return this._projectionMatrix;
  15500. };
  15501. Camera.prototype.getTranformationMatrix = function () {
  15502. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15503. return this._transformMatrix;
  15504. };
  15505. Camera.prototype.updateFrustumPlanes = function () {
  15506. if (!this._refreshFrustumPlanes) {
  15507. return;
  15508. }
  15509. this.getTranformationMatrix();
  15510. if (!this._frustumPlanes) {
  15511. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15512. }
  15513. else {
  15514. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15515. }
  15516. this._refreshFrustumPlanes = false;
  15517. };
  15518. Camera.prototype.isInFrustum = function (target) {
  15519. this.updateFrustumPlanes();
  15520. return target.isInFrustum(this._frustumPlanes);
  15521. };
  15522. Camera.prototype.isCompletelyInFrustum = function (target) {
  15523. this.updateFrustumPlanes();
  15524. return target.isCompletelyInFrustum(this._frustumPlanes);
  15525. };
  15526. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15527. if (length === void 0) { length = 100; }
  15528. if (!transform) {
  15529. transform = this.getWorldMatrix();
  15530. }
  15531. if (!origin) {
  15532. origin = this.position;
  15533. }
  15534. var forward = new BABYLON.Vector3(0, 0, 1);
  15535. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15536. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15537. return new BABYLON.Ray(origin, direction, length);
  15538. };
  15539. Camera.prototype.dispose = function () {
  15540. // Observables
  15541. this.onViewMatrixChangedObservable.clear();
  15542. this.onProjectionMatrixChangedObservable.clear();
  15543. this.onAfterCheckInputsObservable.clear();
  15544. this.onRestoreStateObservable.clear();
  15545. // Inputs
  15546. if (this.inputs) {
  15547. this.inputs.clear();
  15548. }
  15549. // Animations
  15550. this.getScene().stopAnimation(this);
  15551. // Remove from scene
  15552. this.getScene().removeCamera(this);
  15553. while (this._rigCameras.length > 0) {
  15554. this._rigCameras.pop().dispose();
  15555. }
  15556. // Postprocesses
  15557. if (this._rigPostProcess) {
  15558. this._rigPostProcess.dispose(this);
  15559. this._rigPostProcess = null;
  15560. this._postProcesses = [];
  15561. }
  15562. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15563. this._rigPostProcess = null;
  15564. this._postProcesses = [];
  15565. }
  15566. else {
  15567. var i = this._postProcesses.length;
  15568. while (--i >= 0) {
  15569. this._postProcesses[i].dispose(this);
  15570. }
  15571. }
  15572. // Render targets
  15573. var i = this.customRenderTargets.length;
  15574. while (--i >= 0) {
  15575. this.customRenderTargets[i].dispose();
  15576. }
  15577. this.customRenderTargets = [];
  15578. // Active Meshes
  15579. this._activeMeshes.dispose();
  15580. _super.prototype.dispose.call(this);
  15581. };
  15582. Object.defineProperty(Camera.prototype, "leftCamera", {
  15583. // ---- Camera rigs section ----
  15584. get: function () {
  15585. if (this._rigCameras.length < 1) {
  15586. return undefined;
  15587. }
  15588. return this._rigCameras[0];
  15589. },
  15590. enumerable: true,
  15591. configurable: true
  15592. });
  15593. Object.defineProperty(Camera.prototype, "rightCamera", {
  15594. get: function () {
  15595. if (this._rigCameras.length < 2) {
  15596. return undefined;
  15597. }
  15598. return this._rigCameras[1];
  15599. },
  15600. enumerable: true,
  15601. configurable: true
  15602. });
  15603. Camera.prototype.getLeftTarget = function () {
  15604. if (this._rigCameras.length < 1) {
  15605. return undefined;
  15606. }
  15607. return this._rigCameras[0].getTarget();
  15608. };
  15609. Camera.prototype.getRightTarget = function () {
  15610. if (this._rigCameras.length < 2) {
  15611. return undefined;
  15612. }
  15613. return this._rigCameras[1].getTarget();
  15614. };
  15615. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15616. if (this.cameraRigMode === mode) {
  15617. return;
  15618. }
  15619. while (this._rigCameras.length > 0) {
  15620. this._rigCameras.pop().dispose();
  15621. }
  15622. this.cameraRigMode = mode;
  15623. this._cameraRigParams = {};
  15624. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15625. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15626. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15627. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15628. // create the rig cameras, unless none
  15629. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15630. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15631. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15632. }
  15633. switch (this.cameraRigMode) {
  15634. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15635. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15636. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15637. break;
  15638. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15639. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15640. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15641. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15642. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15643. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15644. break;
  15645. case Camera.RIG_MODE_VR:
  15646. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15647. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15648. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15649. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15650. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15651. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15652. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15653. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15654. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15655. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15656. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15657. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15658. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15659. if (metrics.compensateDistortion) {
  15660. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15661. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15662. }
  15663. break;
  15664. case Camera.RIG_MODE_WEBVR:
  15665. if (rigParams.vrDisplay) {
  15666. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15667. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15668. //Left eye
  15669. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15670. this._rigCameras[0].setCameraRigParameter("left", true);
  15671. //leaving this for future reference
  15672. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15673. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15674. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15675. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15676. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15677. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15678. this._rigCameras[0].parent = this;
  15679. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15680. //Right eye
  15681. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15682. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15683. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15684. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15685. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15686. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15687. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15688. this._rigCameras[1].parent = this;
  15689. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15690. if (Camera.UseAlternateWebVRRendering) {
  15691. this._rigCameras[1]._skipRendering = true;
  15692. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  15693. }
  15694. }
  15695. break;
  15696. }
  15697. this._cascadePostProcessesToRigCams();
  15698. this.update();
  15699. };
  15700. Camera.prototype._getVRProjectionMatrix = function () {
  15701. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15702. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15703. return this._projectionMatrix;
  15704. };
  15705. Camera.prototype._updateCameraRotationMatrix = function () {
  15706. //Here for WebVR
  15707. };
  15708. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15709. //Here for WebVR
  15710. };
  15711. /**
  15712. * This function MUST be overwritten by the different WebVR cameras available.
  15713. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15714. */
  15715. Camera.prototype._getWebVRProjectionMatrix = function () {
  15716. return BABYLON.Matrix.Identity();
  15717. };
  15718. /**
  15719. * This function MUST be overwritten by the different WebVR cameras available.
  15720. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15721. */
  15722. Camera.prototype._getWebVRViewMatrix = function () {
  15723. return BABYLON.Matrix.Identity();
  15724. };
  15725. Camera.prototype.setCameraRigParameter = function (name, value) {
  15726. if (!this._cameraRigParams) {
  15727. this._cameraRigParams = {};
  15728. }
  15729. this._cameraRigParams[name] = value;
  15730. //provisionnally:
  15731. if (name === "interaxialDistance") {
  15732. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15733. }
  15734. };
  15735. /**
  15736. * needs to be overridden by children so sub has required properties to be copied
  15737. */
  15738. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15739. return null;
  15740. };
  15741. /**
  15742. * May need to be overridden by children
  15743. */
  15744. Camera.prototype._updateRigCameras = function () {
  15745. for (var i = 0; i < this._rigCameras.length; i++) {
  15746. this._rigCameras[i].minZ = this.minZ;
  15747. this._rigCameras[i].maxZ = this.maxZ;
  15748. this._rigCameras[i].fov = this.fov;
  15749. }
  15750. // only update viewport when ANAGLYPH
  15751. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15752. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15753. }
  15754. };
  15755. Camera.prototype._setupInputs = function () {
  15756. };
  15757. Camera.prototype.serialize = function () {
  15758. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15759. // Type
  15760. serializationObject.type = this.getClassName();
  15761. // Parent
  15762. if (this.parent) {
  15763. serializationObject.parentId = this.parent.id;
  15764. }
  15765. if (this.inputs) {
  15766. this.inputs.serialize(serializationObject);
  15767. }
  15768. // Animations
  15769. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15770. serializationObject.ranges = this.serializeAnimationRanges();
  15771. return serializationObject;
  15772. };
  15773. Camera.prototype.clone = function (name) {
  15774. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15775. };
  15776. Camera.prototype.getDirection = function (localAxis) {
  15777. var result = BABYLON.Vector3.Zero();
  15778. this.getDirectionToRef(localAxis, result);
  15779. return result;
  15780. };
  15781. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15782. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15783. };
  15784. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15785. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15786. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15787. switch (type) {
  15788. case "ArcRotateCamera":
  15789. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15790. case "DeviceOrientationCamera":
  15791. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15792. case "FollowCamera":
  15793. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15794. case "ArcFollowCamera":
  15795. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15796. case "GamepadCamera":
  15797. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15798. case "TouchCamera":
  15799. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15800. case "VirtualJoysticksCamera":
  15801. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15802. case "WebVRFreeCamera":
  15803. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15804. case "WebVRGamepadCamera":
  15805. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15806. case "VRDeviceOrientationFreeCamera":
  15807. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15808. case "VRDeviceOrientationGamepadCamera":
  15809. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15810. case "AnaglyphArcRotateCamera":
  15811. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15812. case "AnaglyphFreeCamera":
  15813. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15814. case "AnaglyphGamepadCamera":
  15815. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15816. case "AnaglyphUniversalCamera":
  15817. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15818. case "StereoscopicArcRotateCamera":
  15819. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15820. case "StereoscopicFreeCamera":
  15821. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15822. case "StereoscopicGamepadCamera":
  15823. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15824. case "StereoscopicUniversalCamera":
  15825. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15826. case "FreeCamera":// Forcing Universal here
  15827. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15828. default:// Universal Camera is the default value
  15829. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15830. }
  15831. };
  15832. Camera.Parse = function (parsedCamera, scene) {
  15833. var type = parsedCamera.type;
  15834. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15835. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15836. // Parent
  15837. if (parsedCamera.parentId) {
  15838. camera._waitingParentId = parsedCamera.parentId;
  15839. }
  15840. //If camera has an input manager, let it parse inputs settings
  15841. if (camera.inputs) {
  15842. camera.inputs.parse(parsedCamera);
  15843. camera._setupInputs();
  15844. }
  15845. if (camera.setPosition) {
  15846. camera.position.copyFromFloats(0, 0, 0);
  15847. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15848. }
  15849. // Target
  15850. if (parsedCamera.target) {
  15851. if (camera.setTarget) {
  15852. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15853. }
  15854. }
  15855. // Apply 3d rig, when found
  15856. if (parsedCamera.cameraRigMode) {
  15857. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15858. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15859. }
  15860. // Animations
  15861. if (parsedCamera.animations) {
  15862. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15863. var parsedAnimation = parsedCamera.animations[animationIndex];
  15864. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15865. }
  15866. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15867. }
  15868. if (parsedCamera.autoAnimate) {
  15869. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15870. }
  15871. return camera;
  15872. };
  15873. // Statics
  15874. Camera._PERSPECTIVE_CAMERA = 0;
  15875. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15876. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15877. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15878. Camera._RIG_MODE_NONE = 0;
  15879. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15880. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15881. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15882. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15883. Camera._RIG_MODE_VR = 20;
  15884. Camera._RIG_MODE_WEBVR = 21;
  15885. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15886. Camera.UseAlternateWebVRRendering = false;
  15887. __decorate([
  15888. BABYLON.serializeAsVector3()
  15889. ], Camera.prototype, "position", void 0);
  15890. __decorate([
  15891. BABYLON.serializeAsVector3()
  15892. ], Camera.prototype, "upVector", void 0);
  15893. __decorate([
  15894. BABYLON.serialize()
  15895. ], Camera.prototype, "orthoLeft", void 0);
  15896. __decorate([
  15897. BABYLON.serialize()
  15898. ], Camera.prototype, "orthoRight", void 0);
  15899. __decorate([
  15900. BABYLON.serialize()
  15901. ], Camera.prototype, "orthoBottom", void 0);
  15902. __decorate([
  15903. BABYLON.serialize()
  15904. ], Camera.prototype, "orthoTop", void 0);
  15905. __decorate([
  15906. BABYLON.serialize()
  15907. ], Camera.prototype, "fov", void 0);
  15908. __decorate([
  15909. BABYLON.serialize()
  15910. ], Camera.prototype, "minZ", void 0);
  15911. __decorate([
  15912. BABYLON.serialize()
  15913. ], Camera.prototype, "maxZ", void 0);
  15914. __decorate([
  15915. BABYLON.serialize()
  15916. ], Camera.prototype, "inertia", void 0);
  15917. __decorate([
  15918. BABYLON.serialize()
  15919. ], Camera.prototype, "mode", void 0);
  15920. __decorate([
  15921. BABYLON.serialize()
  15922. ], Camera.prototype, "layerMask", void 0);
  15923. __decorate([
  15924. BABYLON.serialize()
  15925. ], Camera.prototype, "fovMode", void 0);
  15926. __decorate([
  15927. BABYLON.serialize()
  15928. ], Camera.prototype, "cameraRigMode", void 0);
  15929. __decorate([
  15930. BABYLON.serialize()
  15931. ], Camera.prototype, "interaxialDistance", void 0);
  15932. __decorate([
  15933. BABYLON.serialize()
  15934. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15935. return Camera;
  15936. }(BABYLON.Node));
  15937. BABYLON.Camera = Camera;
  15938. })(BABYLON || (BABYLON = {}));
  15939. //# sourceMappingURL=babylon.camera.js.map
  15940. var BABYLON;
  15941. (function (BABYLON) {
  15942. var RenderingManager = (function () {
  15943. function RenderingManager(scene) {
  15944. this._renderingGroups = new Array();
  15945. this._autoClearDepthStencil = {};
  15946. this._customOpaqueSortCompareFn = {};
  15947. this._customAlphaTestSortCompareFn = {};
  15948. this._customTransparentSortCompareFn = {};
  15949. this._renderinGroupInfo = null;
  15950. this._scene = scene;
  15951. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15952. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15953. }
  15954. }
  15955. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15956. if (depth === void 0) { depth = true; }
  15957. if (stencil === void 0) { stencil = true; }
  15958. if (this._depthStencilBufferAlreadyCleaned) {
  15959. return;
  15960. }
  15961. this._scene.getEngine().clear(null, false, depth, stencil);
  15962. this._depthStencilBufferAlreadyCleaned = true;
  15963. };
  15964. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15965. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15966. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15967. var info = null;
  15968. if (observable) {
  15969. if (!this._renderinGroupInfo) {
  15970. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15971. }
  15972. info = this._renderinGroupInfo;
  15973. info.scene = this._scene;
  15974. info.camera = this._scene.activeCamera;
  15975. }
  15976. // Dispatch sprites
  15977. if (renderSprites) {
  15978. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15979. var manager = this._scene.spriteManagers[index];
  15980. this.dispatchSprites(manager);
  15981. }
  15982. }
  15983. // Render
  15984. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15985. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15986. var renderingGroup = this._renderingGroups[index];
  15987. if (!renderingGroup && !observable)
  15988. continue;
  15989. this._currentIndex = index;
  15990. var renderingGroupMask = 0;
  15991. // Fire PRECLEAR stage
  15992. if (observable) {
  15993. renderingGroupMask = Math.pow(2, index);
  15994. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15995. info.renderingGroupId = index;
  15996. observable.notifyObservers(info, renderingGroupMask);
  15997. }
  15998. // Clear depth/stencil if needed
  15999. if (RenderingManager.AUTOCLEAR) {
  16000. var autoClear = this._autoClearDepthStencil[index];
  16001. if (autoClear && autoClear.autoClear) {
  16002. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16003. }
  16004. }
  16005. if (observable) {
  16006. // Fire PREOPAQUE stage
  16007. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16008. observable.notifyObservers(info, renderingGroupMask);
  16009. // Fire PRETRANSPARENT stage
  16010. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16011. observable.notifyObservers(info, renderingGroupMask);
  16012. }
  16013. if (renderingGroup)
  16014. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16015. // Fire POSTTRANSPARENT stage
  16016. if (observable) {
  16017. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16018. observable.notifyObservers(info, renderingGroupMask);
  16019. }
  16020. }
  16021. };
  16022. RenderingManager.prototype.reset = function () {
  16023. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16024. var renderingGroup = this._renderingGroups[index];
  16025. if (renderingGroup) {
  16026. renderingGroup.prepare();
  16027. }
  16028. }
  16029. };
  16030. RenderingManager.prototype.dispose = function () {
  16031. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16032. var renderingGroup = this._renderingGroups[index];
  16033. if (renderingGroup) {
  16034. renderingGroup.dispose();
  16035. }
  16036. }
  16037. this._renderingGroups.length = 0;
  16038. };
  16039. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16040. if (!this._renderingGroups[renderingGroupId]) {
  16041. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16042. }
  16043. };
  16044. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16045. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16046. this._prepareRenderingGroup(renderingGroupId);
  16047. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16048. };
  16049. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16050. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16051. this._prepareRenderingGroup(renderingGroupId);
  16052. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16053. };
  16054. RenderingManager.prototype.dispatch = function (subMesh) {
  16055. var mesh = subMesh.getMesh();
  16056. var renderingGroupId = mesh.renderingGroupId || 0;
  16057. this._prepareRenderingGroup(renderingGroupId);
  16058. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16059. };
  16060. /**
  16061. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16062. * This allowed control for front to back rendering or reversly depending of the special needs.
  16063. *
  16064. * @param renderingGroupId The rendering group id corresponding to its index
  16065. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16066. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16067. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16068. */
  16069. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16070. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16071. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16072. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16073. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16074. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16075. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16076. if (this._renderingGroups[renderingGroupId]) {
  16077. var group = this._renderingGroups[renderingGroupId];
  16078. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16079. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16080. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16081. }
  16082. };
  16083. /**
  16084. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16085. *
  16086. * @param renderingGroupId The rendering group id corresponding to its index
  16087. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16088. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16089. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16090. */
  16091. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16092. if (depth === void 0) { depth = true; }
  16093. if (stencil === void 0) { stencil = true; }
  16094. this._autoClearDepthStencil[renderingGroupId] = {
  16095. autoClear: autoClearDepthStencil,
  16096. depth: depth,
  16097. stencil: stencil
  16098. };
  16099. };
  16100. /**
  16101. * The max id used for rendering groups (not included)
  16102. */
  16103. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16104. /**
  16105. * The min id used for rendering groups (included)
  16106. */
  16107. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16108. /**
  16109. * Used to globally prevent autoclearing scenes.
  16110. */
  16111. RenderingManager.AUTOCLEAR = true;
  16112. return RenderingManager;
  16113. }());
  16114. BABYLON.RenderingManager = RenderingManager;
  16115. })(BABYLON || (BABYLON = {}));
  16116. //# sourceMappingURL=babylon.renderingManager.js.map
  16117. var BABYLON;
  16118. (function (BABYLON) {
  16119. var RenderingGroup = (function () {
  16120. /**
  16121. * Creates a new rendering group.
  16122. * @param index The rendering group index
  16123. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16124. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16125. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16126. */
  16127. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16128. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16129. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16130. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16131. this.index = index;
  16132. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16133. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16134. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16135. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16136. this._particleSystems = new BABYLON.SmartArray(256);
  16137. this._spriteManagers = new BABYLON.SmartArray(256);
  16138. this._edgesRenderers = new BABYLON.SmartArray(16);
  16139. this._scene = scene;
  16140. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16141. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16142. this.transparentSortCompareFn = transparentSortCompareFn;
  16143. }
  16144. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16145. /**
  16146. * Set the opaque sort comparison function.
  16147. * If null the sub meshes will be render in the order they were created
  16148. */
  16149. set: function (value) {
  16150. this._opaqueSortCompareFn = value;
  16151. if (value) {
  16152. this._renderOpaque = this.renderOpaqueSorted;
  16153. }
  16154. else {
  16155. this._renderOpaque = RenderingGroup.renderUnsorted;
  16156. }
  16157. },
  16158. enumerable: true,
  16159. configurable: true
  16160. });
  16161. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16162. /**
  16163. * Set the alpha test sort comparison function.
  16164. * If null the sub meshes will be render in the order they were created
  16165. */
  16166. set: function (value) {
  16167. this._alphaTestSortCompareFn = value;
  16168. if (value) {
  16169. this._renderAlphaTest = this.renderAlphaTestSorted;
  16170. }
  16171. else {
  16172. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16173. }
  16174. },
  16175. enumerable: true,
  16176. configurable: true
  16177. });
  16178. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16179. /**
  16180. * Set the transparent sort comparison function.
  16181. * If null the sub meshes will be render in the order they were created
  16182. */
  16183. set: function (value) {
  16184. if (value) {
  16185. this._transparentSortCompareFn = value;
  16186. }
  16187. else {
  16188. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16189. }
  16190. this._renderTransparent = this.renderTransparentSorted;
  16191. },
  16192. enumerable: true,
  16193. configurable: true
  16194. });
  16195. /**
  16196. * Render all the sub meshes contained in the group.
  16197. * @param customRenderFunction Used to override the default render behaviour of the group.
  16198. * @returns true if rendered some submeshes.
  16199. */
  16200. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16201. if (customRenderFunction) {
  16202. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16203. return;
  16204. }
  16205. var engine = this._scene.getEngine();
  16206. // Depth only
  16207. if (this._depthOnlySubMeshes.length !== 0) {
  16208. engine.setAlphaTesting(true);
  16209. engine.setColorWrite(false);
  16210. this._renderAlphaTest(this._depthOnlySubMeshes);
  16211. engine.setAlphaTesting(false);
  16212. engine.setColorWrite(true);
  16213. }
  16214. // Opaque
  16215. if (this._opaqueSubMeshes.length !== 0) {
  16216. this._renderOpaque(this._opaqueSubMeshes);
  16217. }
  16218. // Alpha test
  16219. if (this._alphaTestSubMeshes.length !== 0) {
  16220. engine.setAlphaTesting(true);
  16221. this._renderAlphaTest(this._alphaTestSubMeshes);
  16222. engine.setAlphaTesting(false);
  16223. }
  16224. var stencilState = engine.getStencilBuffer();
  16225. engine.setStencilBuffer(false);
  16226. // Sprites
  16227. if (renderSprites) {
  16228. this._renderSprites();
  16229. }
  16230. // Particles
  16231. if (renderParticles) {
  16232. this._renderParticles(activeMeshes);
  16233. }
  16234. if (this.onBeforeTransparentRendering) {
  16235. this.onBeforeTransparentRendering();
  16236. }
  16237. // Transparent
  16238. if (this._transparentSubMeshes.length !== 0) {
  16239. this._renderTransparent(this._transparentSubMeshes);
  16240. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16241. }
  16242. // Set back stencil to false in case it changes before the edge renderer.
  16243. engine.setStencilBuffer(false);
  16244. // Edges
  16245. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16246. this._edgesRenderers.data[edgesRendererIndex].render();
  16247. }
  16248. // Restore Stencil state.
  16249. engine.setStencilBuffer(stencilState);
  16250. };
  16251. /**
  16252. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16253. * @param subMeshes The submeshes to render
  16254. */
  16255. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16256. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16257. };
  16258. /**
  16259. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16260. * @param subMeshes The submeshes to render
  16261. */
  16262. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16263. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16264. };
  16265. /**
  16266. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16267. * @param subMeshes The submeshes to render
  16268. */
  16269. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16270. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16271. };
  16272. /**
  16273. * Renders the submeshes in a specified order.
  16274. * @param subMeshes The submeshes to sort before render
  16275. * @param sortCompareFn The comparison function use to sort
  16276. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16277. * @param transparent Specifies to activate blending if true
  16278. */
  16279. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16280. var subIndex = 0;
  16281. var subMesh;
  16282. for (; subIndex < subMeshes.length; subIndex++) {
  16283. subMesh = subMeshes.data[subIndex];
  16284. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16285. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16286. }
  16287. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16288. sortedArray.sort(sortCompareFn);
  16289. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16290. subMesh = sortedArray[subIndex];
  16291. if (transparent) {
  16292. var material = subMesh.getMaterial();
  16293. if (material.needDepthPrePass) {
  16294. var engine = material.getScene().getEngine();
  16295. engine.setColorWrite(false);
  16296. engine.setAlphaTesting(true);
  16297. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16298. subMesh.render(false);
  16299. engine.setAlphaTesting(false);
  16300. engine.setColorWrite(true);
  16301. }
  16302. }
  16303. subMesh.render(transparent);
  16304. }
  16305. };
  16306. /**
  16307. * Renders the submeshes in the order they were dispatched (no sort applied).
  16308. * @param subMeshes The submeshes to render
  16309. */
  16310. RenderingGroup.renderUnsorted = function (subMeshes) {
  16311. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16312. var submesh = subMeshes.data[subIndex];
  16313. submesh.render(false);
  16314. }
  16315. };
  16316. /**
  16317. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16318. * are rendered back to front if in the same alpha index.
  16319. *
  16320. * @param a The first submesh
  16321. * @param b The second submesh
  16322. * @returns The result of the comparison
  16323. */
  16324. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16325. // Alpha index first
  16326. if (a._alphaIndex > b._alphaIndex) {
  16327. return 1;
  16328. }
  16329. if (a._alphaIndex < b._alphaIndex) {
  16330. return -1;
  16331. }
  16332. // Then distance to camera
  16333. return RenderingGroup.backToFrontSortCompare(a, b);
  16334. };
  16335. /**
  16336. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16337. * are rendered back to front.
  16338. *
  16339. * @param a The first submesh
  16340. * @param b The second submesh
  16341. * @returns The result of the comparison
  16342. */
  16343. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16344. // Then distance to camera
  16345. if (a._distanceToCamera < b._distanceToCamera) {
  16346. return 1;
  16347. }
  16348. if (a._distanceToCamera > b._distanceToCamera) {
  16349. return -1;
  16350. }
  16351. return 0;
  16352. };
  16353. /**
  16354. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16355. * are rendered front to back (prevent overdraw).
  16356. *
  16357. * @param a The first submesh
  16358. * @param b The second submesh
  16359. * @returns The result of the comparison
  16360. */
  16361. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16362. // Then distance to camera
  16363. if (a._distanceToCamera < b._distanceToCamera) {
  16364. return -1;
  16365. }
  16366. if (a._distanceToCamera > b._distanceToCamera) {
  16367. return 1;
  16368. }
  16369. return 0;
  16370. };
  16371. /**
  16372. * Resets the different lists of submeshes to prepare a new frame.
  16373. */
  16374. RenderingGroup.prototype.prepare = function () {
  16375. this._opaqueSubMeshes.reset();
  16376. this._transparentSubMeshes.reset();
  16377. this._alphaTestSubMeshes.reset();
  16378. this._depthOnlySubMeshes.reset();
  16379. this._particleSystems.reset();
  16380. this._spriteManagers.reset();
  16381. this._edgesRenderers.reset();
  16382. };
  16383. RenderingGroup.prototype.dispose = function () {
  16384. this._opaqueSubMeshes.dispose();
  16385. this._transparentSubMeshes.dispose();
  16386. this._alphaTestSubMeshes.dispose();
  16387. this._depthOnlySubMeshes.dispose();
  16388. this._particleSystems.dispose();
  16389. this._spriteManagers.dispose();
  16390. this._edgesRenderers.dispose();
  16391. };
  16392. /**
  16393. * Inserts the submesh in its correct queue depending on its material.
  16394. * @param subMesh The submesh to dispatch
  16395. */
  16396. RenderingGroup.prototype.dispatch = function (subMesh) {
  16397. var material = subMesh.getMaterial();
  16398. var mesh = subMesh.getMesh();
  16399. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16400. this._transparentSubMeshes.push(subMesh);
  16401. }
  16402. else if (material.needAlphaTesting()) {
  16403. if (material.needDepthPrePass) {
  16404. this._depthOnlySubMeshes.push(subMesh);
  16405. }
  16406. this._alphaTestSubMeshes.push(subMesh);
  16407. }
  16408. else {
  16409. if (material.needDepthPrePass) {
  16410. this._depthOnlySubMeshes.push(subMesh);
  16411. }
  16412. this._opaqueSubMeshes.push(subMesh); // Opaque
  16413. }
  16414. if (mesh._edgesRenderer) {
  16415. this._edgesRenderers.push(mesh._edgesRenderer);
  16416. }
  16417. };
  16418. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16419. this._spriteManagers.push(spriteManager);
  16420. };
  16421. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16422. this._particleSystems.push(particleSystem);
  16423. };
  16424. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16425. if (this._particleSystems.length === 0) {
  16426. return;
  16427. }
  16428. // Particles
  16429. var activeCamera = this._scene.activeCamera;
  16430. this._scene._particlesDuration.beginMonitoring();
  16431. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16432. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16433. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16434. continue;
  16435. }
  16436. var emitter = particleSystem.emitter;
  16437. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16438. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16439. }
  16440. }
  16441. this._scene._particlesDuration.endMonitoring(false);
  16442. };
  16443. RenderingGroup.prototype._renderSprites = function () {
  16444. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16445. return;
  16446. }
  16447. // Sprites
  16448. var activeCamera = this._scene.activeCamera;
  16449. this._scene._spritesDuration.beginMonitoring();
  16450. for (var id = 0; id < this._spriteManagers.length; id++) {
  16451. var spriteManager = this._spriteManagers.data[id];
  16452. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16453. spriteManager.render();
  16454. }
  16455. }
  16456. this._scene._spritesDuration.endMonitoring(false);
  16457. };
  16458. return RenderingGroup;
  16459. }());
  16460. BABYLON.RenderingGroup = RenderingGroup;
  16461. })(BABYLON || (BABYLON = {}));
  16462. //# sourceMappingURL=babylon.renderingGroup.js.map
  16463. var BABYLON;
  16464. (function (BABYLON) {
  16465. var ClickInfo = (function () {
  16466. function ClickInfo() {
  16467. this._singleClick = false;
  16468. this._doubleClick = false;
  16469. this._hasSwiped = false;
  16470. this._ignore = false;
  16471. }
  16472. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16473. get: function () {
  16474. return this._singleClick;
  16475. },
  16476. set: function (b) {
  16477. this._singleClick = b;
  16478. },
  16479. enumerable: true,
  16480. configurable: true
  16481. });
  16482. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16483. get: function () {
  16484. return this._doubleClick;
  16485. },
  16486. set: function (b) {
  16487. this._doubleClick = b;
  16488. },
  16489. enumerable: true,
  16490. configurable: true
  16491. });
  16492. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16493. get: function () {
  16494. return this._hasSwiped;
  16495. },
  16496. set: function (b) {
  16497. this._hasSwiped = b;
  16498. },
  16499. enumerable: true,
  16500. configurable: true
  16501. });
  16502. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16503. get: function () {
  16504. return this._ignore;
  16505. },
  16506. set: function (b) {
  16507. this._ignore = b;
  16508. },
  16509. enumerable: true,
  16510. configurable: true
  16511. });
  16512. return ClickInfo;
  16513. }());
  16514. /**
  16515. * This class is used by the onRenderingGroupObservable
  16516. */
  16517. var RenderingGroupInfo = (function () {
  16518. function RenderingGroupInfo() {
  16519. }
  16520. /**
  16521. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16522. * This stage will be fired no matter what
  16523. */
  16524. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16525. /**
  16526. * Called before opaque object are rendered.
  16527. * This stage will be fired only if there's 3D Opaque content to render
  16528. */
  16529. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16530. /**
  16531. * Called after the opaque objects are rendered and before the transparent ones
  16532. * This stage will be fired only if there's 3D transparent content to render
  16533. */
  16534. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16535. /**
  16536. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16537. * This stage will be fired no matter what
  16538. */
  16539. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16540. return RenderingGroupInfo;
  16541. }());
  16542. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16543. /**
  16544. * Represents a scene to be rendered by the engine.
  16545. * @see http://doc.babylonjs.com/page.php?p=21911
  16546. */
  16547. var Scene = (function () {
  16548. /**
  16549. * @constructor
  16550. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16551. */
  16552. function Scene(engine) {
  16553. // Members
  16554. this.autoClear = true;
  16555. this.autoClearDepthAndStencil = true;
  16556. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16557. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16558. this.forceWireframe = false;
  16559. this._forcePointsCloud = false;
  16560. this.forceShowBoundingBoxes = false;
  16561. this.animationsEnabled = true;
  16562. this.constantlyUpdateMeshUnderPointer = false;
  16563. this.hoverCursor = "pointer";
  16564. this.defaultCursor = "";
  16565. // Metadata
  16566. this.metadata = null;
  16567. /**
  16568. * An event triggered when the scene is disposed.
  16569. * @type {BABYLON.Observable}
  16570. */
  16571. this.onDisposeObservable = new BABYLON.Observable();
  16572. /**
  16573. * An event triggered before rendering the scene
  16574. * @type {BABYLON.Observable}
  16575. */
  16576. this.onBeforeRenderObservable = new BABYLON.Observable();
  16577. /**
  16578. * An event triggered after rendering the scene
  16579. * @type {BABYLON.Observable}
  16580. */
  16581. this.onAfterRenderObservable = new BABYLON.Observable();
  16582. /**
  16583. * An event triggered when the scene is ready
  16584. * @type {BABYLON.Observable}
  16585. */
  16586. this.onReadyObservable = new BABYLON.Observable();
  16587. /**
  16588. * An event triggered before rendering a camera
  16589. * @type {BABYLON.Observable}
  16590. */
  16591. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16592. /**
  16593. * An event triggered after rendering a camera
  16594. * @type {BABYLON.Observable}
  16595. */
  16596. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16597. /**
  16598. * An event triggered when a camera is created
  16599. * @type {BABYLON.Observable}
  16600. */
  16601. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16602. /**
  16603. * An event triggered when a camera is removed
  16604. * @type {BABYLON.Observable}
  16605. */
  16606. this.onCameraRemovedObservable = new BABYLON.Observable();
  16607. /**
  16608. * An event triggered when a light is created
  16609. * @type {BABYLON.Observable}
  16610. */
  16611. this.onNewLightAddedObservable = new BABYLON.Observable();
  16612. /**
  16613. * An event triggered when a light is removed
  16614. * @type {BABYLON.Observable}
  16615. */
  16616. this.onLightRemovedObservable = new BABYLON.Observable();
  16617. /**
  16618. * An event triggered when a geometry is created
  16619. * @type {BABYLON.Observable}
  16620. */
  16621. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16622. /**
  16623. * An event triggered when a geometry is removed
  16624. * @type {BABYLON.Observable}
  16625. */
  16626. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16627. /**
  16628. * An event triggered when a mesh is created
  16629. * @type {BABYLON.Observable}
  16630. */
  16631. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16632. /**
  16633. * An event triggered when a mesh is removed
  16634. * @type {BABYLON.Observable}
  16635. */
  16636. this.onMeshRemovedObservable = new BABYLON.Observable();
  16637. /**
  16638. * An event triggered before calculating deterministic simulation step
  16639. * @type {BABYLON.Observable}
  16640. */
  16641. this.onBeforeStepObservable = new BABYLON.Observable();
  16642. /**
  16643. * An event triggered after calculating deterministic simulation step
  16644. * @type {BABYLON.Observable}
  16645. */
  16646. this.onAfterStepObservable = new BABYLON.Observable();
  16647. /**
  16648. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16649. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16650. * 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)
  16651. */
  16652. this.onRenderingGroupObservable = new BABYLON.Observable();
  16653. // Animations
  16654. this.animations = [];
  16655. /**
  16656. * 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).
  16657. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16658. */
  16659. this.onPrePointerObservable = new BABYLON.Observable();
  16660. /**
  16661. * Observable event triggered each time an input event is received from the rendering canvas
  16662. */
  16663. this.onPointerObservable = new BABYLON.Observable();
  16664. this._meshPickProceed = false;
  16665. this._previousHasSwiped = false;
  16666. this._currentPickResult = null;
  16667. this._previousPickResult = null;
  16668. this._isButtonPressed = false;
  16669. this._doubleClickOccured = false;
  16670. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16671. this.cameraToUseForPointers = null;
  16672. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16673. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16674. this._startingPointerTime = 0;
  16675. this._previousStartingPointerTime = 0;
  16676. // Deterministic lockstep
  16677. this._timeAccumulator = 0;
  16678. this._currentStepId = 0;
  16679. this._currentInternalStep = 0;
  16680. // Keyboard
  16681. /**
  16682. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16683. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16684. */
  16685. this.onPreKeyboardObservable = new BABYLON.Observable();
  16686. /**
  16687. * Observable event triggered each time an keyboard event is received from the hosting window
  16688. */
  16689. this.onKeyboardObservable = new BABYLON.Observable();
  16690. // Coordinate system
  16691. /**
  16692. * use right-handed coordinate system on this scene.
  16693. * @type {boolean}
  16694. */
  16695. this._useRightHandedSystem = false;
  16696. // Fog
  16697. this._fogEnabled = true;
  16698. this._fogMode = Scene.FOGMODE_NONE;
  16699. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16700. this.fogDensity = 0.1;
  16701. this.fogStart = 0;
  16702. this.fogEnd = 1000.0;
  16703. // Lights
  16704. /**
  16705. * is shadow enabled on this scene.
  16706. * @type {boolean}
  16707. */
  16708. this._shadowsEnabled = true;
  16709. /**
  16710. * is light enabled on this scene.
  16711. * @type {boolean}
  16712. */
  16713. this._lightsEnabled = true;
  16714. /**
  16715. * All of the lights added to this scene.
  16716. * @see BABYLON.Light
  16717. * @type {BABYLON.Light[]}
  16718. */
  16719. this.lights = new Array();
  16720. // Cameras
  16721. /** All of the cameras added to this scene. */
  16722. this.cameras = new Array();
  16723. /** All of the active cameras added to this scene. */
  16724. this.activeCameras = new Array();
  16725. // Meshes
  16726. /**
  16727. * All of the (abstract) meshes added to this scene.
  16728. * @see BABYLON.AbstractMesh
  16729. * @type {BABYLON.AbstractMesh[]}
  16730. */
  16731. this.meshes = new Array();
  16732. // Geometries
  16733. this._geometries = new Array();
  16734. this.materials = new Array();
  16735. this.multiMaterials = new Array();
  16736. // Textures
  16737. this._texturesEnabled = true;
  16738. this.textures = new Array();
  16739. // Particles
  16740. this.particlesEnabled = true;
  16741. this.particleSystems = new Array();
  16742. // Sprites
  16743. this.spritesEnabled = true;
  16744. this.spriteManagers = new Array();
  16745. // Layers
  16746. this.layers = new Array();
  16747. this.highlightLayers = new Array();
  16748. // Skeletons
  16749. this._skeletonsEnabled = true;
  16750. this.skeletons = new Array();
  16751. // Morph targets
  16752. this.morphTargetManagers = new Array();
  16753. // Lens flares
  16754. this.lensFlaresEnabled = true;
  16755. this.lensFlareSystems = new Array();
  16756. // Collisions
  16757. this.collisionsEnabled = true;
  16758. /** Defines the gravity applied to this scene */
  16759. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16760. // Postprocesses
  16761. this.postProcesses = new Array();
  16762. this.postProcessesEnabled = true;
  16763. // Customs render targets
  16764. this.renderTargetsEnabled = true;
  16765. this.dumpNextRenderTargets = false;
  16766. this.customRenderTargets = new Array();
  16767. // Imported meshes
  16768. this.importedMeshesFiles = new Array();
  16769. // Probes
  16770. this.probesEnabled = true;
  16771. this.reflectionProbes = new Array();
  16772. this._actionManagers = new Array();
  16773. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16774. // Procedural textures
  16775. this.proceduralTexturesEnabled = true;
  16776. this._proceduralTextures = new Array();
  16777. this.soundTracks = new Array();
  16778. this._audioEnabled = true;
  16779. this._headphone = false;
  16780. // Performance counters
  16781. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16782. this._totalLightsCounter = new BABYLON.PerfCounter();
  16783. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16784. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16785. this._totalVertices = new BABYLON.PerfCounter();
  16786. this._activeIndices = new BABYLON.PerfCounter();
  16787. this._activeParticles = new BABYLON.PerfCounter();
  16788. this._interFrameDuration = new BABYLON.PerfCounter();
  16789. this._lastFrameDuration = new BABYLON.PerfCounter();
  16790. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16791. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16792. this._particlesDuration = new BABYLON.PerfCounter();
  16793. this._renderDuration = new BABYLON.PerfCounter();
  16794. this._spritesDuration = new BABYLON.PerfCounter();
  16795. this._activeBones = new BABYLON.PerfCounter();
  16796. this._animationTime = 0;
  16797. this.animationTimeScale = 1;
  16798. this._renderId = 0;
  16799. this._executeWhenReadyTimeoutId = -1;
  16800. this._intermediateRendering = false;
  16801. this._viewUpdateFlag = -1;
  16802. this._projectionUpdateFlag = -1;
  16803. this._alternateViewUpdateFlag = -1;
  16804. this._alternateProjectionUpdateFlag = -1;
  16805. this._toBeDisposed = new BABYLON.SmartArray(256);
  16806. this._pendingData = []; //ANY
  16807. this._activeMeshes = new BABYLON.SmartArray(256);
  16808. this._processedMaterials = new BABYLON.SmartArray(256);
  16809. this._renderTargets = new BABYLON.SmartArray(256);
  16810. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16811. this._activeSkeletons = new BABYLON.SmartArray(32);
  16812. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16813. this._activeAnimatables = new Array();
  16814. this._transformMatrix = BABYLON.Matrix.Zero();
  16815. this._useAlternateCameraConfiguration = false;
  16816. this._alternateRendering = false;
  16817. this.requireLightSorting = false;
  16818. this._activeMeshesFrozen = false;
  16819. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16820. this._engine.scenes.push(this);
  16821. this._uid = null;
  16822. this._renderingManager = new BABYLON.RenderingManager(this);
  16823. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16824. if (BABYLON.OutlineRenderer) {
  16825. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16826. }
  16827. this.attachControl();
  16828. //simplification queue
  16829. if (BABYLON.SimplificationQueue) {
  16830. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16831. }
  16832. //collision coordinator initialization. For now legacy per default.
  16833. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16834. // Uniform Buffer
  16835. this._createUbo();
  16836. // Default Image processing definition.
  16837. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16838. }
  16839. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16840. /** The fog is deactivated */
  16841. get: function () {
  16842. return Scene._FOGMODE_NONE;
  16843. },
  16844. enumerable: true,
  16845. configurable: true
  16846. });
  16847. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16848. /** The fog density is following an exponential function */
  16849. get: function () {
  16850. return Scene._FOGMODE_EXP;
  16851. },
  16852. enumerable: true,
  16853. configurable: true
  16854. });
  16855. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16856. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16857. get: function () {
  16858. return Scene._FOGMODE_EXP2;
  16859. },
  16860. enumerable: true,
  16861. configurable: true
  16862. });
  16863. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16864. /** The fog density is following a linear function. */
  16865. get: function () {
  16866. return Scene._FOGMODE_LINEAR;
  16867. },
  16868. enumerable: true,
  16869. configurable: true
  16870. });
  16871. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16872. /**
  16873. * Texture used in all pbr material as the reflection texture.
  16874. * As in the majority of the scene they are the same (exception for multi room and so on),
  16875. * this is easier to reference from here than from all the materials.
  16876. */
  16877. get: function () {
  16878. return this._environmentTexture;
  16879. },
  16880. /**
  16881. * Texture used in all pbr material as the reflection texture.
  16882. * As in the majority of the scene they are the same (exception for multi room and so on),
  16883. * this is easier to set here than in all the materials.
  16884. */
  16885. set: function (value) {
  16886. this._environmentTexture = value;
  16887. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16888. },
  16889. enumerable: true,
  16890. configurable: true
  16891. });
  16892. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16893. /**
  16894. * Default image processing configuration used either in the rendering
  16895. * Forward main pass or through the imageProcessingPostProcess if present.
  16896. * As in the majority of the scene they are the same (exception for multi camera),
  16897. * this is easier to reference from here than from all the materials and post process.
  16898. *
  16899. * No setter as we it is a shared configuration, you can set the values instead.
  16900. */
  16901. get: function () {
  16902. return this._imageProcessingConfiguration;
  16903. },
  16904. enumerable: true,
  16905. configurable: true
  16906. });
  16907. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16908. get: function () {
  16909. return this._forcePointsCloud;
  16910. },
  16911. set: function (value) {
  16912. if (this._forcePointsCloud === value) {
  16913. return;
  16914. }
  16915. this._forcePointsCloud = value;
  16916. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16917. },
  16918. enumerable: true,
  16919. configurable: true
  16920. });
  16921. Object.defineProperty(Scene.prototype, "onDispose", {
  16922. /** A function to be executed when this scene is disposed. */
  16923. set: function (callback) {
  16924. if (this._onDisposeObserver) {
  16925. this.onDisposeObservable.remove(this._onDisposeObserver);
  16926. }
  16927. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16928. },
  16929. enumerable: true,
  16930. configurable: true
  16931. });
  16932. Object.defineProperty(Scene.prototype, "beforeRender", {
  16933. /** A function to be executed before rendering this scene */
  16934. set: function (callback) {
  16935. if (this._onBeforeRenderObserver) {
  16936. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16937. }
  16938. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16939. },
  16940. enumerable: true,
  16941. configurable: true
  16942. });
  16943. Object.defineProperty(Scene.prototype, "afterRender", {
  16944. /** A function to be executed after rendering this scene */
  16945. set: function (callback) {
  16946. if (this._onAfterRenderObserver) {
  16947. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16948. }
  16949. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16950. },
  16951. enumerable: true,
  16952. configurable: true
  16953. });
  16954. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16955. set: function (callback) {
  16956. if (this._onBeforeCameraRenderObserver) {
  16957. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16958. }
  16959. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16965. set: function (callback) {
  16966. if (this._onAfterCameraRenderObserver) {
  16967. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16968. }
  16969. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16970. },
  16971. enumerable: true,
  16972. configurable: true
  16973. });
  16974. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16975. get: function () {
  16976. if (!this._gamepadManager) {
  16977. this._gamepadManager = new BABYLON.GamepadManager();
  16978. }
  16979. return this._gamepadManager;
  16980. },
  16981. enumerable: true,
  16982. configurable: true
  16983. });
  16984. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16985. get: function () {
  16986. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16987. },
  16988. enumerable: true,
  16989. configurable: true
  16990. });
  16991. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16992. get: function () {
  16993. return this._useRightHandedSystem;
  16994. },
  16995. set: function (value) {
  16996. if (this._useRightHandedSystem === value) {
  16997. return;
  16998. }
  16999. this._useRightHandedSystem = value;
  17000. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17001. },
  17002. enumerable: true,
  17003. configurable: true
  17004. });
  17005. Scene.prototype.setStepId = function (newStepId) {
  17006. this._currentStepId = newStepId;
  17007. };
  17008. ;
  17009. Scene.prototype.getStepId = function () {
  17010. return this._currentStepId;
  17011. };
  17012. ;
  17013. Scene.prototype.getInternalStep = function () {
  17014. return this._currentInternalStep;
  17015. };
  17016. ;
  17017. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17018. get: function () {
  17019. return this._fogEnabled;
  17020. },
  17021. /**
  17022. * is fog enabled on this scene.
  17023. */
  17024. set: function (value) {
  17025. if (this._fogEnabled === value) {
  17026. return;
  17027. }
  17028. this._fogEnabled = value;
  17029. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17030. },
  17031. enumerable: true,
  17032. configurable: true
  17033. });
  17034. Object.defineProperty(Scene.prototype, "fogMode", {
  17035. get: function () {
  17036. return this._fogMode;
  17037. },
  17038. set: function (value) {
  17039. if (this._fogMode === value) {
  17040. return;
  17041. }
  17042. this._fogMode = value;
  17043. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17044. },
  17045. enumerable: true,
  17046. configurable: true
  17047. });
  17048. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17049. get: function () {
  17050. return this._shadowsEnabled;
  17051. },
  17052. set: function (value) {
  17053. if (this._shadowsEnabled === value) {
  17054. return;
  17055. }
  17056. this._shadowsEnabled = value;
  17057. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17058. },
  17059. enumerable: true,
  17060. configurable: true
  17061. });
  17062. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17063. get: function () {
  17064. return this._lightsEnabled;
  17065. },
  17066. set: function (value) {
  17067. if (this._lightsEnabled === value) {
  17068. return;
  17069. }
  17070. this._lightsEnabled = value;
  17071. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17072. },
  17073. enumerable: true,
  17074. configurable: true
  17075. });
  17076. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17077. /** The default material used on meshes when no material is affected */
  17078. get: function () {
  17079. if (!this._defaultMaterial) {
  17080. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17081. }
  17082. return this._defaultMaterial;
  17083. },
  17084. /** The default material used on meshes when no material is affected */
  17085. set: function (value) {
  17086. this._defaultMaterial = value;
  17087. },
  17088. enumerable: true,
  17089. configurable: true
  17090. });
  17091. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17092. get: function () {
  17093. return this._texturesEnabled;
  17094. },
  17095. set: function (value) {
  17096. if (this._texturesEnabled === value) {
  17097. return;
  17098. }
  17099. this._texturesEnabled = value;
  17100. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17101. },
  17102. enumerable: true,
  17103. configurable: true
  17104. });
  17105. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17106. get: function () {
  17107. return this._skeletonsEnabled;
  17108. },
  17109. set: function (value) {
  17110. if (this._skeletonsEnabled === value) {
  17111. return;
  17112. }
  17113. this._skeletonsEnabled = value;
  17114. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17115. },
  17116. enumerable: true,
  17117. configurable: true
  17118. });
  17119. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17120. get: function () {
  17121. if (!this._postProcessRenderPipelineManager) {
  17122. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17123. }
  17124. return this._postProcessRenderPipelineManager;
  17125. },
  17126. enumerable: true,
  17127. configurable: true
  17128. });
  17129. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17130. get: function () {
  17131. if (!this._mainSoundTrack) {
  17132. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17133. }
  17134. return this._mainSoundTrack;
  17135. },
  17136. enumerable: true,
  17137. configurable: true
  17138. });
  17139. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17140. get: function () {
  17141. return this._alternateRendering;
  17142. },
  17143. enumerable: true,
  17144. configurable: true
  17145. });
  17146. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17147. get: function () {
  17148. return this._frustumPlanes;
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. Object.defineProperty(Scene.prototype, "debugLayer", {
  17154. // Properties
  17155. get: function () {
  17156. if (!this._debugLayer) {
  17157. this._debugLayer = new BABYLON.DebugLayer(this);
  17158. }
  17159. return this._debugLayer;
  17160. },
  17161. enumerable: true,
  17162. configurable: true
  17163. });
  17164. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17165. get: function () {
  17166. return this._workerCollisions;
  17167. },
  17168. set: function (enabled) {
  17169. if (!BABYLON.CollisionCoordinatorLegacy) {
  17170. return;
  17171. }
  17172. enabled = (enabled && !!Worker);
  17173. this._workerCollisions = enabled;
  17174. if (this.collisionCoordinator) {
  17175. this.collisionCoordinator.destroy();
  17176. }
  17177. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17178. this.collisionCoordinator.init(this);
  17179. },
  17180. enumerable: true,
  17181. configurable: true
  17182. });
  17183. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17184. get: function () {
  17185. return this._selectionOctree;
  17186. },
  17187. enumerable: true,
  17188. configurable: true
  17189. });
  17190. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17191. /**
  17192. * The mesh that is currently under the pointer.
  17193. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17194. */
  17195. get: function () {
  17196. return this._pointerOverMesh;
  17197. },
  17198. enumerable: true,
  17199. configurable: true
  17200. });
  17201. Object.defineProperty(Scene.prototype, "pointerX", {
  17202. /**
  17203. * Current on-screen X position of the pointer
  17204. * @return {number} X position of the pointer
  17205. */
  17206. get: function () {
  17207. return this._pointerX;
  17208. },
  17209. enumerable: true,
  17210. configurable: true
  17211. });
  17212. Object.defineProperty(Scene.prototype, "pointerY", {
  17213. /**
  17214. * Current on-screen Y position of the pointer
  17215. * @return {number} Y position of the pointer
  17216. */
  17217. get: function () {
  17218. return this._pointerY;
  17219. },
  17220. enumerable: true,
  17221. configurable: true
  17222. });
  17223. Scene.prototype.getCachedMaterial = function () {
  17224. return this._cachedMaterial;
  17225. };
  17226. Scene.prototype.getCachedEffect = function () {
  17227. return this._cachedEffect;
  17228. };
  17229. Scene.prototype.getCachedVisibility = function () {
  17230. return this._cachedVisibility;
  17231. };
  17232. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17233. if (visibility === void 0) { visibility = 1; }
  17234. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17235. };
  17236. Scene.prototype.getBoundingBoxRenderer = function () {
  17237. if (!this._boundingBoxRenderer) {
  17238. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17239. }
  17240. return this._boundingBoxRenderer;
  17241. };
  17242. Scene.prototype.getOutlineRenderer = function () {
  17243. return this._outlineRenderer;
  17244. };
  17245. Scene.prototype.getEngine = function () {
  17246. return this._engine;
  17247. };
  17248. Scene.prototype.getTotalVertices = function () {
  17249. return this._totalVertices.current;
  17250. };
  17251. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17252. get: function () {
  17253. return this._totalVertices;
  17254. },
  17255. enumerable: true,
  17256. configurable: true
  17257. });
  17258. Scene.prototype.getActiveIndices = function () {
  17259. return this._activeIndices.current;
  17260. };
  17261. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17262. get: function () {
  17263. return this._activeIndices;
  17264. },
  17265. enumerable: true,
  17266. configurable: true
  17267. });
  17268. Scene.prototype.getActiveParticles = function () {
  17269. return this._activeParticles.current;
  17270. };
  17271. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17272. get: function () {
  17273. return this._activeParticles;
  17274. },
  17275. enumerable: true,
  17276. configurable: true
  17277. });
  17278. Scene.prototype.getActiveBones = function () {
  17279. return this._activeBones.current;
  17280. };
  17281. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17282. get: function () {
  17283. return this._activeBones;
  17284. },
  17285. enumerable: true,
  17286. configurable: true
  17287. });
  17288. // Stats
  17289. Scene.prototype.getInterFramePerfCounter = function () {
  17290. return this._interFrameDuration.current;
  17291. };
  17292. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17293. get: function () {
  17294. return this._interFrameDuration;
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. Scene.prototype.getLastFrameDuration = function () {
  17300. return this._lastFrameDuration.current;
  17301. };
  17302. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17303. get: function () {
  17304. return this._lastFrameDuration;
  17305. },
  17306. enumerable: true,
  17307. configurable: true
  17308. });
  17309. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17310. return this._evaluateActiveMeshesDuration.current;
  17311. };
  17312. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17313. get: function () {
  17314. return this._evaluateActiveMeshesDuration;
  17315. },
  17316. enumerable: true,
  17317. configurable: true
  17318. });
  17319. Scene.prototype.getActiveMeshes = function () {
  17320. return this._activeMeshes;
  17321. };
  17322. Scene.prototype.getRenderTargetsDuration = function () {
  17323. return this._renderTargetsDuration.current;
  17324. };
  17325. Scene.prototype.getRenderDuration = function () {
  17326. return this._renderDuration.current;
  17327. };
  17328. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17329. get: function () {
  17330. return this._renderDuration;
  17331. },
  17332. enumerable: true,
  17333. configurable: true
  17334. });
  17335. Scene.prototype.getParticlesDuration = function () {
  17336. return this._particlesDuration.current;
  17337. };
  17338. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17339. get: function () {
  17340. return this._particlesDuration;
  17341. },
  17342. enumerable: true,
  17343. configurable: true
  17344. });
  17345. Scene.prototype.getSpritesDuration = function () {
  17346. return this._spritesDuration.current;
  17347. };
  17348. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17349. get: function () {
  17350. return this._spritesDuration;
  17351. },
  17352. enumerable: true,
  17353. configurable: true
  17354. });
  17355. Scene.prototype.getAnimationRatio = function () {
  17356. return this._animationRatio;
  17357. };
  17358. Scene.prototype.getRenderId = function () {
  17359. return this._renderId;
  17360. };
  17361. Scene.prototype.incrementRenderId = function () {
  17362. this._renderId++;
  17363. };
  17364. Scene.prototype._updatePointerPosition = function (evt) {
  17365. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17366. this._pointerX = evt.clientX - canvasRect.left;
  17367. this._pointerY = evt.clientY - canvasRect.top;
  17368. this._unTranslatedPointerX = this._pointerX;
  17369. this._unTranslatedPointerY = this._pointerY;
  17370. };
  17371. Scene.prototype._createUbo = function () {
  17372. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17373. this._sceneUbo.addUniform("viewProjection", 16);
  17374. this._sceneUbo.addUniform("view", 16);
  17375. };
  17376. Scene.prototype._createAlternateUbo = function () {
  17377. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17378. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17379. this._alternateSceneUbo.addUniform("view", 16);
  17380. };
  17381. // Pointers handling
  17382. /**
  17383. * Use this method to simulate a pointer move on a mesh
  17384. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17385. */
  17386. Scene.prototype.simulatePointerMove = function (pickResult) {
  17387. var evt = new PointerEvent("pointermove");
  17388. return this._processPointerMove(pickResult, evt);
  17389. };
  17390. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17391. var canvas = this._engine.getRenderingCanvas();
  17392. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17393. this.setPointerOverSprite(null);
  17394. this.setPointerOverMesh(pickResult.pickedMesh);
  17395. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17396. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17397. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17398. }
  17399. else {
  17400. canvas.style.cursor = this.hoverCursor;
  17401. }
  17402. }
  17403. else {
  17404. canvas.style.cursor = this.defaultCursor;
  17405. }
  17406. }
  17407. else {
  17408. this.setPointerOverMesh(null);
  17409. // Sprites
  17410. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17411. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17412. this.setPointerOverSprite(pickResult.pickedSprite);
  17413. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17414. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17415. }
  17416. else {
  17417. canvas.style.cursor = this.hoverCursor;
  17418. }
  17419. }
  17420. else {
  17421. this.setPointerOverSprite(null);
  17422. // Restore pointer
  17423. canvas.style.cursor = this.defaultCursor;
  17424. }
  17425. }
  17426. if (this.onPointerMove) {
  17427. this.onPointerMove(evt, pickResult);
  17428. }
  17429. if (this.onPointerObservable.hasObservers()) {
  17430. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17431. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17432. this.onPointerObservable.notifyObservers(pi, type);
  17433. }
  17434. return this;
  17435. };
  17436. /**
  17437. * Use this method to simulate a pointer down on a mesh
  17438. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17439. */
  17440. Scene.prototype.simulatePointerDown = function (pickResult) {
  17441. var evt = new PointerEvent("pointerdown");
  17442. return this._processPointerDown(pickResult, evt);
  17443. };
  17444. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17445. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17446. this._pickedDownMesh = pickResult.pickedMesh;
  17447. var actionManager = pickResult.pickedMesh.actionManager;
  17448. if (actionManager) {
  17449. if (actionManager.hasPickTriggers) {
  17450. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17451. switch (evt.button) {
  17452. case 0:
  17453. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17454. break;
  17455. case 1:
  17456. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17457. break;
  17458. case 2:
  17459. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17460. break;
  17461. }
  17462. }
  17463. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17464. window.setTimeout((function () {
  17465. var _this = this;
  17466. 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);
  17467. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17468. if (this._isButtonPressed &&
  17469. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17470. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17471. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17472. this._startingPointerTime = 0;
  17473. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17474. }
  17475. }
  17476. }).bind(this), Scene.LongPressDelay);
  17477. }
  17478. }
  17479. }
  17480. if (this.onPointerDown) {
  17481. this.onPointerDown(evt, pickResult);
  17482. }
  17483. if (this.onPointerObservable.hasObservers()) {
  17484. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17485. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17486. this.onPointerObservable.notifyObservers(pi, type);
  17487. }
  17488. return this;
  17489. };
  17490. /**
  17491. * Use this method to simulate a pointer up on a mesh
  17492. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17493. */
  17494. Scene.prototype.simulatePointerUp = function (pickResult) {
  17495. var evt = new PointerEvent("pointerup");
  17496. var clickInfo = new ClickInfo();
  17497. clickInfo.singleClick = true;
  17498. return this._processPointerUp(pickResult, evt, clickInfo);
  17499. };
  17500. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17501. if (pickResult && pickResult && pickResult.pickedMesh) {
  17502. this._pickedUpMesh = pickResult.pickedMesh;
  17503. if (this._pickedDownMesh === this._pickedUpMesh) {
  17504. if (this.onPointerPick) {
  17505. this.onPointerPick(evt, pickResult);
  17506. }
  17507. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17508. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17509. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17510. this.onPointerObservable.notifyObservers(pi, type);
  17511. }
  17512. }
  17513. if (pickResult.pickedMesh.actionManager) {
  17514. if (clickInfo.ignore) {
  17515. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17516. }
  17517. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17518. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17519. }
  17520. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17521. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17522. }
  17523. }
  17524. }
  17525. if (this._pickedDownMesh &&
  17526. this._pickedDownMesh.actionManager &&
  17527. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17528. this._pickedDownMesh !== this._pickedUpMesh) {
  17529. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17530. }
  17531. if (this.onPointerUp) {
  17532. this.onPointerUp(evt, pickResult);
  17533. }
  17534. if (this.onPointerObservable.hasObservers()) {
  17535. if (!clickInfo.ignore) {
  17536. if (!clickInfo.hasSwiped) {
  17537. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17538. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17539. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17540. this.onPointerObservable.notifyObservers(pi, type);
  17541. }
  17542. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17543. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17544. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17545. this.onPointerObservable.notifyObservers(pi, type);
  17546. }
  17547. }
  17548. }
  17549. else {
  17550. var type = BABYLON.PointerEventTypes.POINTERUP;
  17551. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17552. this.onPointerObservable.notifyObservers(pi, type);
  17553. }
  17554. }
  17555. return this;
  17556. };
  17557. /**
  17558. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17559. * @param attachUp defines if you want to attach events to pointerup
  17560. * @param attachDown defines if you want to attach events to pointerdown
  17561. * @param attachMove defines if you want to attach events to pointermove
  17562. */
  17563. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17564. var _this = this;
  17565. if (attachUp === void 0) { attachUp = true; }
  17566. if (attachDown === void 0) { attachDown = true; }
  17567. if (attachMove === void 0) { attachMove = true; }
  17568. this._initActionManager = function (act, clickInfo) {
  17569. if (!_this._meshPickProceed) {
  17570. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17571. _this._currentPickResult = pickResult;
  17572. if (pickResult) {
  17573. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17574. }
  17575. _this._meshPickProceed = true;
  17576. }
  17577. return act;
  17578. };
  17579. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17580. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17581. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17582. btn !== _this._previousButtonPressed) {
  17583. _this._doubleClickOccured = false;
  17584. clickInfo.singleClick = true;
  17585. clickInfo.ignore = false;
  17586. cb(clickInfo, _this._currentPickResult);
  17587. }
  17588. };
  17589. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17590. var clickInfo = new ClickInfo();
  17591. _this._currentPickResult = null;
  17592. var act;
  17593. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17594. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17595. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17596. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17597. act = _this._initActionManager(act, clickInfo);
  17598. if (act)
  17599. checkPicking = act.hasPickTriggers;
  17600. }
  17601. if (checkPicking) {
  17602. var btn = evt.button;
  17603. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17604. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17605. if (!clickInfo.hasSwiped) {
  17606. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17607. if (!checkSingleClickImmediately) {
  17608. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17609. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17610. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17611. act = _this._initActionManager(act, clickInfo);
  17612. if (act)
  17613. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17614. }
  17615. }
  17616. if (checkSingleClickImmediately) {
  17617. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17618. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17619. btn !== _this._previousButtonPressed) {
  17620. clickInfo.singleClick = true;
  17621. cb(clickInfo, _this._currentPickResult);
  17622. }
  17623. }
  17624. else {
  17625. // wait that no double click has been raised during the double click delay
  17626. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17627. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17628. }
  17629. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17630. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17631. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17632. act = _this._initActionManager(act, clickInfo);
  17633. if (act)
  17634. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17635. }
  17636. if (checkDoubleClick) {
  17637. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17638. if (btn === _this._previousButtonPressed &&
  17639. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17640. !_this._doubleClickOccured) {
  17641. // pointer has not moved for 2 clicks, it's a double click
  17642. if (!clickInfo.hasSwiped &&
  17643. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17644. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17645. _this._previousStartingPointerTime = 0;
  17646. _this._doubleClickOccured = true;
  17647. clickInfo.doubleClick = true;
  17648. clickInfo.ignore = false;
  17649. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17650. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17651. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17652. cb(clickInfo, _this._currentPickResult);
  17653. }
  17654. else {
  17655. _this._doubleClickOccured = false;
  17656. _this._previousStartingPointerTime = _this._startingPointerTime;
  17657. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17658. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17659. _this._previousButtonPressed = btn;
  17660. _this._previousHasSwiped = clickInfo.hasSwiped;
  17661. if (Scene.ExclusiveDoubleClickMode) {
  17662. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17663. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17664. }
  17665. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17666. cb(clickInfo, _this._previousPickResult);
  17667. }
  17668. else {
  17669. cb(clickInfo, _this._currentPickResult);
  17670. }
  17671. }
  17672. }
  17673. else {
  17674. _this._doubleClickOccured = false;
  17675. _this._previousStartingPointerTime = _this._startingPointerTime;
  17676. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17677. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17678. _this._previousButtonPressed = btn;
  17679. _this._previousHasSwiped = clickInfo.hasSwiped;
  17680. }
  17681. }
  17682. }
  17683. }
  17684. clickInfo.ignore = true;
  17685. cb(clickInfo, _this._currentPickResult);
  17686. };
  17687. this._spritePredicate = function (sprite) {
  17688. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17689. };
  17690. this._onPointerMove = function (evt) {
  17691. _this._updatePointerPosition(evt);
  17692. // PreObservable support
  17693. if (_this.onPrePointerObservable.hasObservers()) {
  17694. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17695. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17696. _this.onPrePointerObservable.notifyObservers(pi, type);
  17697. if (pi.skipOnPointerObservable) {
  17698. return;
  17699. }
  17700. }
  17701. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17702. return;
  17703. }
  17704. if (!_this.pointerMovePredicate) {
  17705. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17706. }
  17707. // Meshes
  17708. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17709. _this._processPointerMove(pickResult, evt);
  17710. };
  17711. this._onPointerDown = function (evt) {
  17712. _this._isButtonPressed = true;
  17713. _this._pickedDownMesh = null;
  17714. _this._meshPickProceed = false;
  17715. _this._updatePointerPosition(evt);
  17716. // PreObservable support
  17717. if (_this.onPrePointerObservable.hasObservers()) {
  17718. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17719. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17720. _this.onPrePointerObservable.notifyObservers(pi, type);
  17721. if (pi.skipOnPointerObservable) {
  17722. return;
  17723. }
  17724. }
  17725. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17726. return;
  17727. }
  17728. _this._startingPointerPosition.x = _this._pointerX;
  17729. _this._startingPointerPosition.y = _this._pointerY;
  17730. _this._startingPointerTime = new Date().getTime();
  17731. if (!_this.pointerDownPredicate) {
  17732. _this.pointerDownPredicate = function (mesh) {
  17733. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17734. };
  17735. }
  17736. // Meshes
  17737. _this._pickedDownMesh = null;
  17738. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17739. _this._processPointerDown(pickResult, evt);
  17740. // Sprites
  17741. _this._pickedDownSprite = null;
  17742. if (_this.spriteManagers.length > 0) {
  17743. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17744. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17745. if (pickResult.pickedSprite.actionManager) {
  17746. _this._pickedDownSprite = pickResult.pickedSprite;
  17747. switch (evt.button) {
  17748. case 0:
  17749. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17750. break;
  17751. case 1:
  17752. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17753. break;
  17754. case 2:
  17755. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17756. break;
  17757. }
  17758. if (pickResult.pickedSprite.actionManager) {
  17759. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17760. }
  17761. }
  17762. }
  17763. }
  17764. };
  17765. this._onPointerUp = function (evt) {
  17766. if (!_this._isButtonPressed) {
  17767. return; // So we need to test it the pointer down was pressed before.
  17768. }
  17769. _this._isButtonPressed = false;
  17770. _this._pickedUpMesh = null;
  17771. _this._meshPickProceed = false;
  17772. _this._updatePointerPosition(evt);
  17773. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17774. // PreObservable support
  17775. if (this.onPrePointerObservable.hasObservers()) {
  17776. if (!clickInfo.ignore) {
  17777. if (!clickInfo.hasSwiped) {
  17778. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17779. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17780. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17781. this.onPrePointerObservable.notifyObservers(pi, type);
  17782. if (pi.skipOnPointerObservable) {
  17783. return;
  17784. }
  17785. }
  17786. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17787. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17788. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17789. this.onPrePointerObservable.notifyObservers(pi, type);
  17790. if (pi.skipOnPointerObservable) {
  17791. return;
  17792. }
  17793. }
  17794. }
  17795. }
  17796. else {
  17797. var type = BABYLON.PointerEventTypes.POINTERUP;
  17798. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17799. this.onPrePointerObservable.notifyObservers(pi, type);
  17800. if (pi.skipOnPointerObservable) {
  17801. return;
  17802. }
  17803. }
  17804. }
  17805. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17806. return;
  17807. }
  17808. if (!this.pointerUpPredicate) {
  17809. this.pointerUpPredicate = function (mesh) {
  17810. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17811. };
  17812. }
  17813. // Meshes
  17814. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17815. this._initActionManager(null, clickInfo);
  17816. }
  17817. if (!pickResult) {
  17818. pickResult = this._currentPickResult;
  17819. }
  17820. this._processPointerUp(pickResult, evt, clickInfo);
  17821. // Sprites
  17822. if (this.spriteManagers.length > 0) {
  17823. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17824. if (pickResult.hit && pickResult.pickedSprite) {
  17825. if (pickResult.pickedSprite.actionManager) {
  17826. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17827. if (pickResult.pickedSprite.actionManager) {
  17828. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17829. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17830. }
  17831. }
  17832. }
  17833. }
  17834. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17835. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17836. }
  17837. }
  17838. this._previousPickResult = this._currentPickResult;
  17839. }).bind(_this));
  17840. };
  17841. this._onKeyDown = function (evt) {
  17842. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17843. if (_this.onPreKeyboardObservable.hasObservers()) {
  17844. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17845. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17846. if (pi.skipOnPointerObservable) {
  17847. return;
  17848. }
  17849. }
  17850. if (_this.onKeyboardObservable.hasObservers()) {
  17851. var pi = new BABYLON.KeyboardInfo(type, evt);
  17852. _this.onKeyboardObservable.notifyObservers(pi, type);
  17853. }
  17854. if (_this.actionManager) {
  17855. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17856. }
  17857. };
  17858. this._onKeyUp = function (evt) {
  17859. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17860. if (_this.onPreKeyboardObservable.hasObservers()) {
  17861. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17862. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17863. if (pi.skipOnPointerObservable) {
  17864. return;
  17865. }
  17866. }
  17867. if (_this.onKeyboardObservable.hasObservers()) {
  17868. var pi = new BABYLON.KeyboardInfo(type, evt);
  17869. _this.onKeyboardObservable.notifyObservers(pi, type);
  17870. }
  17871. if (_this.actionManager) {
  17872. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17873. }
  17874. };
  17875. var engine = this.getEngine();
  17876. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17877. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17878. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17879. });
  17880. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17881. canvas.removeEventListener("keydown", _this._onKeyDown);
  17882. canvas.removeEventListener("keyup", _this._onKeyUp);
  17883. });
  17884. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17885. var canvas = this._engine.getRenderingCanvas();
  17886. if (attachMove) {
  17887. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17888. // Wheel
  17889. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17890. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17891. }
  17892. if (attachDown) {
  17893. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17894. }
  17895. if (attachUp) {
  17896. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17897. }
  17898. canvas.tabIndex = 1;
  17899. };
  17900. Scene.prototype.detachControl = function () {
  17901. var engine = this.getEngine();
  17902. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17903. var canvas = engine.getRenderingCanvas();
  17904. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17905. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17906. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17907. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17908. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17909. // Wheel
  17910. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17911. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17912. // Keyboard
  17913. canvas.removeEventListener("keydown", this._onKeyDown);
  17914. canvas.removeEventListener("keyup", this._onKeyUp);
  17915. // Observables
  17916. this.onKeyboardObservable.clear();
  17917. this.onPreKeyboardObservable.clear();
  17918. this.onPointerObservable.clear();
  17919. this.onPrePointerObservable.clear();
  17920. };
  17921. // Ready
  17922. Scene.prototype.isReady = function () {
  17923. if (this._pendingData.length > 0) {
  17924. return false;
  17925. }
  17926. var index;
  17927. // Geometries
  17928. for (index = 0; index < this._geometries.length; index++) {
  17929. var geometry = this._geometries[index];
  17930. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17931. return false;
  17932. }
  17933. }
  17934. // Meshes
  17935. for (index = 0; index < this.meshes.length; index++) {
  17936. var mesh = this.meshes[index];
  17937. if (!mesh.isEnabled()) {
  17938. continue;
  17939. }
  17940. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17941. continue;
  17942. }
  17943. if (!mesh.isReady()) {
  17944. return false;
  17945. }
  17946. var mat = mesh.material;
  17947. if (mat) {
  17948. if (!mat.isReady(mesh)) {
  17949. return false;
  17950. }
  17951. }
  17952. }
  17953. return true;
  17954. };
  17955. Scene.prototype.resetCachedMaterial = function () {
  17956. this._cachedMaterial = null;
  17957. this._cachedEffect = null;
  17958. this._cachedVisibility = null;
  17959. };
  17960. Scene.prototype.registerBeforeRender = function (func) {
  17961. this.onBeforeRenderObservable.add(func);
  17962. };
  17963. Scene.prototype.unregisterBeforeRender = function (func) {
  17964. this.onBeforeRenderObservable.removeCallback(func);
  17965. };
  17966. Scene.prototype.registerAfterRender = function (func) {
  17967. this.onAfterRenderObservable.add(func);
  17968. };
  17969. Scene.prototype.unregisterAfterRender = function (func) {
  17970. this.onAfterRenderObservable.removeCallback(func);
  17971. };
  17972. Scene.prototype._addPendingData = function (data) {
  17973. this._pendingData.push(data);
  17974. };
  17975. Scene.prototype._removePendingData = function (data) {
  17976. var index = this._pendingData.indexOf(data);
  17977. if (index !== -1) {
  17978. this._pendingData.splice(index, 1);
  17979. }
  17980. };
  17981. Scene.prototype.getWaitingItemsCount = function () {
  17982. return this._pendingData.length;
  17983. };
  17984. /**
  17985. * Registers a function to be executed when the scene is ready.
  17986. * @param {Function} func - the function to be executed.
  17987. */
  17988. Scene.prototype.executeWhenReady = function (func) {
  17989. var _this = this;
  17990. this.onReadyObservable.add(func);
  17991. if (this._executeWhenReadyTimeoutId !== -1) {
  17992. return;
  17993. }
  17994. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17995. _this._checkIsReady();
  17996. }, 150);
  17997. };
  17998. Scene.prototype._checkIsReady = function () {
  17999. var _this = this;
  18000. if (this.isReady()) {
  18001. this.onReadyObservable.notifyObservers(this);
  18002. this.onReadyObservable.clear();
  18003. this._executeWhenReadyTimeoutId = -1;
  18004. return;
  18005. }
  18006. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18007. _this._checkIsReady();
  18008. }, 150);
  18009. };
  18010. // Animations
  18011. /**
  18012. * Will start the animation sequence of a given target
  18013. * @param target - the target
  18014. * @param {number} from - from which frame should animation start
  18015. * @param {number} to - till which frame should animation run.
  18016. * @param {boolean} [loop] - should the animation loop
  18017. * @param {number} [speedRatio] - the speed in which to run the animation
  18018. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18019. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18020. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18021. * See BABYLON.Animatable
  18022. */
  18023. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18024. if (speedRatio === void 0) { speedRatio = 1.0; }
  18025. if (from > to && speedRatio > 0) {
  18026. speedRatio *= -1;
  18027. }
  18028. this.stopAnimation(target);
  18029. if (!animatable) {
  18030. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18031. }
  18032. // Local animations
  18033. if (target.animations) {
  18034. animatable.appendAnimations(target, target.animations);
  18035. }
  18036. // Children animations
  18037. if (target.getAnimatables) {
  18038. var animatables = target.getAnimatables();
  18039. for (var index = 0; index < animatables.length; index++) {
  18040. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18041. }
  18042. }
  18043. animatable.reset();
  18044. return animatable;
  18045. };
  18046. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18047. if (speedRatio === undefined) {
  18048. speedRatio = 1.0;
  18049. }
  18050. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18051. return animatable;
  18052. };
  18053. Scene.prototype.getAnimatableByTarget = function (target) {
  18054. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18055. if (this._activeAnimatables[index].target === target) {
  18056. return this._activeAnimatables[index];
  18057. }
  18058. }
  18059. return null;
  18060. };
  18061. Object.defineProperty(Scene.prototype, "Animatables", {
  18062. get: function () {
  18063. return this._activeAnimatables;
  18064. },
  18065. enumerable: true,
  18066. configurable: true
  18067. });
  18068. /**
  18069. * Will stop the animation of the given target
  18070. * @param target - the target
  18071. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18072. * @see beginAnimation
  18073. */
  18074. Scene.prototype.stopAnimation = function (target, animationName) {
  18075. var animatable = this.getAnimatableByTarget(target);
  18076. if (animatable) {
  18077. animatable.stop(animationName);
  18078. }
  18079. };
  18080. Scene.prototype._animate = function () {
  18081. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18082. return;
  18083. }
  18084. // Getting time
  18085. var now = BABYLON.Tools.Now;
  18086. if (!this._animationTimeLast) {
  18087. if (this._pendingData.length > 0) {
  18088. return;
  18089. }
  18090. this._animationTimeLast = now;
  18091. }
  18092. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18093. this._animationTime += deltaTime;
  18094. this._animationTimeLast = now;
  18095. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18096. this._activeAnimatables[index]._animate(this._animationTime);
  18097. }
  18098. };
  18099. // Matrix
  18100. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18101. this._useAlternateCameraConfiguration = active;
  18102. };
  18103. Scene.prototype.getViewMatrix = function () {
  18104. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18105. };
  18106. Scene.prototype.getProjectionMatrix = function () {
  18107. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18108. };
  18109. Scene.prototype.getTransformMatrix = function () {
  18110. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18111. };
  18112. Scene.prototype.setTransformMatrix = function (view, projection) {
  18113. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18114. return;
  18115. }
  18116. this._viewUpdateFlag = view.updateFlag;
  18117. this._projectionUpdateFlag = projection.updateFlag;
  18118. this._viewMatrix = view;
  18119. this._projectionMatrix = projection;
  18120. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18121. // Update frustum
  18122. if (!this._frustumPlanes) {
  18123. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18124. }
  18125. else {
  18126. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18127. }
  18128. if (this._sceneUbo.useUbo) {
  18129. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18130. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18131. this._sceneUbo.update();
  18132. }
  18133. };
  18134. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18135. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18136. return;
  18137. }
  18138. this._alternateViewUpdateFlag = view.updateFlag;
  18139. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18140. this._alternateViewMatrix = view;
  18141. this._alternateProjectionMatrix = projection;
  18142. if (!this._alternateTransformMatrix) {
  18143. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18144. }
  18145. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18146. if (!this._alternateSceneUbo) {
  18147. this._createAlternateUbo();
  18148. }
  18149. if (this._alternateSceneUbo.useUbo) {
  18150. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18151. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18152. this._alternateSceneUbo.update();
  18153. }
  18154. };
  18155. Scene.prototype.getSceneUniformBuffer = function () {
  18156. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18157. };
  18158. // Methods
  18159. Scene.prototype.getUniqueId = function () {
  18160. var result = Scene._uniqueIdCounter;
  18161. Scene._uniqueIdCounter++;
  18162. return result;
  18163. };
  18164. Scene.prototype.addMesh = function (newMesh) {
  18165. var position = this.meshes.push(newMesh);
  18166. //notify the collision coordinator
  18167. if (this.collisionCoordinator) {
  18168. this.collisionCoordinator.onMeshAdded(newMesh);
  18169. }
  18170. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18171. };
  18172. Scene.prototype.removeMesh = function (toRemove) {
  18173. var index = this.meshes.indexOf(toRemove);
  18174. if (index !== -1) {
  18175. // Remove from the scene if mesh found
  18176. this.meshes.splice(index, 1);
  18177. }
  18178. //notify the collision coordinator
  18179. if (this.collisionCoordinator) {
  18180. this.collisionCoordinator.onMeshRemoved(toRemove);
  18181. }
  18182. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18183. return index;
  18184. };
  18185. Scene.prototype.removeSkeleton = function (toRemove) {
  18186. var index = this.skeletons.indexOf(toRemove);
  18187. if (index !== -1) {
  18188. // Remove from the scene if found
  18189. this.skeletons.splice(index, 1);
  18190. }
  18191. return index;
  18192. };
  18193. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18194. var index = this.morphTargetManagers.indexOf(toRemove);
  18195. if (index !== -1) {
  18196. // Remove from the scene if found
  18197. this.morphTargetManagers.splice(index, 1);
  18198. }
  18199. return index;
  18200. };
  18201. Scene.prototype.removeLight = function (toRemove) {
  18202. var index = this.lights.indexOf(toRemove);
  18203. if (index !== -1) {
  18204. // Remove from the scene if mesh found
  18205. this.lights.splice(index, 1);
  18206. this.sortLightsByPriority();
  18207. }
  18208. this.onLightRemovedObservable.notifyObservers(toRemove);
  18209. return index;
  18210. };
  18211. Scene.prototype.removeCamera = function (toRemove) {
  18212. var index = this.cameras.indexOf(toRemove);
  18213. if (index !== -1) {
  18214. // Remove from the scene if mesh found
  18215. this.cameras.splice(index, 1);
  18216. }
  18217. // Remove from activeCameras
  18218. var index2 = this.activeCameras.indexOf(toRemove);
  18219. if (index2 !== -1) {
  18220. // Remove from the scene if mesh found
  18221. this.activeCameras.splice(index2, 1);
  18222. }
  18223. // Reset the activeCamera
  18224. if (this.activeCamera === toRemove) {
  18225. if (this.cameras.length > 0) {
  18226. this.activeCamera = this.cameras[0];
  18227. }
  18228. else {
  18229. this.activeCamera = null;
  18230. }
  18231. }
  18232. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18233. return index;
  18234. };
  18235. Scene.prototype.addLight = function (newLight) {
  18236. this.lights.push(newLight);
  18237. this.sortLightsByPriority();
  18238. this.onNewLightAddedObservable.notifyObservers(newLight);
  18239. };
  18240. Scene.prototype.sortLightsByPriority = function () {
  18241. if (this.requireLightSorting) {
  18242. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18243. }
  18244. };
  18245. Scene.prototype.addCamera = function (newCamera) {
  18246. var position = this.cameras.push(newCamera);
  18247. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18248. };
  18249. /**
  18250. * Switch active camera
  18251. * @param {Camera} newCamera - new active camera
  18252. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18253. */
  18254. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18255. if (attachControl === void 0) { attachControl = true; }
  18256. var canvas = this._engine.getRenderingCanvas();
  18257. this.activeCamera.detachControl(canvas);
  18258. this.activeCamera = newCamera;
  18259. if (attachControl) {
  18260. newCamera.attachControl(canvas);
  18261. }
  18262. };
  18263. /**
  18264. * sets the active camera of the scene using its ID
  18265. * @param {string} id - the camera's ID
  18266. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18267. * @see activeCamera
  18268. */
  18269. Scene.prototype.setActiveCameraByID = function (id) {
  18270. var camera = this.getCameraByID(id);
  18271. if (camera) {
  18272. this.activeCamera = camera;
  18273. return camera;
  18274. }
  18275. return null;
  18276. };
  18277. /**
  18278. * sets the active camera of the scene using its name
  18279. * @param {string} name - the camera's name
  18280. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18281. * @see activeCamera
  18282. */
  18283. Scene.prototype.setActiveCameraByName = function (name) {
  18284. var camera = this.getCameraByName(name);
  18285. if (camera) {
  18286. this.activeCamera = camera;
  18287. return camera;
  18288. }
  18289. return null;
  18290. };
  18291. /**
  18292. * get a material using its id
  18293. * @param {string} the material's ID
  18294. * @return {BABYLON.Material|null} the material or null if none found.
  18295. */
  18296. Scene.prototype.getMaterialByID = function (id) {
  18297. for (var index = 0; index < this.materials.length; index++) {
  18298. if (this.materials[index].id === id) {
  18299. return this.materials[index];
  18300. }
  18301. }
  18302. return null;
  18303. };
  18304. /**
  18305. * get a material using its name
  18306. * @param {string} the material's name
  18307. * @return {BABYLON.Material|null} the material or null if none found.
  18308. */
  18309. Scene.prototype.getMaterialByName = function (name) {
  18310. for (var index = 0; index < this.materials.length; index++) {
  18311. if (this.materials[index].name === name) {
  18312. return this.materials[index];
  18313. }
  18314. }
  18315. return null;
  18316. };
  18317. Scene.prototype.getLensFlareSystemByName = function (name) {
  18318. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18319. if (this.lensFlareSystems[index].name === name) {
  18320. return this.lensFlareSystems[index];
  18321. }
  18322. }
  18323. return null;
  18324. };
  18325. Scene.prototype.getLensFlareSystemByID = function (id) {
  18326. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18327. if (this.lensFlareSystems[index].id === id) {
  18328. return this.lensFlareSystems[index];
  18329. }
  18330. }
  18331. return null;
  18332. };
  18333. Scene.prototype.getCameraByID = function (id) {
  18334. for (var index = 0; index < this.cameras.length; index++) {
  18335. if (this.cameras[index].id === id) {
  18336. return this.cameras[index];
  18337. }
  18338. }
  18339. return null;
  18340. };
  18341. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18342. for (var index = 0; index < this.cameras.length; index++) {
  18343. if (this.cameras[index].uniqueId === uniqueId) {
  18344. return this.cameras[index];
  18345. }
  18346. }
  18347. return null;
  18348. };
  18349. /**
  18350. * get a camera using its name
  18351. * @param {string} the camera's name
  18352. * @return {BABYLON.Camera|null} the camera or null if none found.
  18353. */
  18354. Scene.prototype.getCameraByName = function (name) {
  18355. for (var index = 0; index < this.cameras.length; index++) {
  18356. if (this.cameras[index].name === name) {
  18357. return this.cameras[index];
  18358. }
  18359. }
  18360. return null;
  18361. };
  18362. /**
  18363. * get a bone using its id
  18364. * @param {string} the bone's id
  18365. * @return {BABYLON.Bone|null} the bone or null if not found
  18366. */
  18367. Scene.prototype.getBoneByID = function (id) {
  18368. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18369. var skeleton = this.skeletons[skeletonIndex];
  18370. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18371. if (skeleton.bones[boneIndex].id === id) {
  18372. return skeleton.bones[boneIndex];
  18373. }
  18374. }
  18375. }
  18376. return null;
  18377. };
  18378. /**
  18379. * get a bone using its id
  18380. * @param {string} the bone's name
  18381. * @return {BABYLON.Bone|null} the bone or null if not found
  18382. */
  18383. Scene.prototype.getBoneByName = function (name) {
  18384. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18385. var skeleton = this.skeletons[skeletonIndex];
  18386. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18387. if (skeleton.bones[boneIndex].name === name) {
  18388. return skeleton.bones[boneIndex];
  18389. }
  18390. }
  18391. }
  18392. return null;
  18393. };
  18394. /**
  18395. * get a light node using its name
  18396. * @param {string} the light's name
  18397. * @return {BABYLON.Light|null} the light or null if none found.
  18398. */
  18399. Scene.prototype.getLightByName = function (name) {
  18400. for (var index = 0; index < this.lights.length; index++) {
  18401. if (this.lights[index].name === name) {
  18402. return this.lights[index];
  18403. }
  18404. }
  18405. return null;
  18406. };
  18407. /**
  18408. * get a light node using its ID
  18409. * @param {string} the light's id
  18410. * @return {BABYLON.Light|null} the light or null if none found.
  18411. */
  18412. Scene.prototype.getLightByID = function (id) {
  18413. for (var index = 0; index < this.lights.length; index++) {
  18414. if (this.lights[index].id === id) {
  18415. return this.lights[index];
  18416. }
  18417. }
  18418. return null;
  18419. };
  18420. /**
  18421. * get a light node using its scene-generated unique ID
  18422. * @param {number} the light's unique id
  18423. * @return {BABYLON.Light|null} the light or null if none found.
  18424. */
  18425. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18426. for (var index = 0; index < this.lights.length; index++) {
  18427. if (this.lights[index].uniqueId === uniqueId) {
  18428. return this.lights[index];
  18429. }
  18430. }
  18431. return null;
  18432. };
  18433. /**
  18434. * get a particle system by id
  18435. * @param id {number} the particle system id
  18436. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18437. */
  18438. Scene.prototype.getParticleSystemByID = function (id) {
  18439. for (var index = 0; index < this.particleSystems.length; index++) {
  18440. if (this.particleSystems[index].id === id) {
  18441. return this.particleSystems[index];
  18442. }
  18443. }
  18444. return null;
  18445. };
  18446. /**
  18447. * get a geometry using its ID
  18448. * @param {string} the geometry's id
  18449. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18450. */
  18451. Scene.prototype.getGeometryByID = function (id) {
  18452. for (var index = 0; index < this._geometries.length; index++) {
  18453. if (this._geometries[index].id === id) {
  18454. return this._geometries[index];
  18455. }
  18456. }
  18457. return null;
  18458. };
  18459. /**
  18460. * add a new geometry to this scene.
  18461. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18462. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18463. * @return {boolean} was the geometry added or not
  18464. */
  18465. Scene.prototype.pushGeometry = function (geometry, force) {
  18466. if (!force && this.getGeometryByID(geometry.id)) {
  18467. return false;
  18468. }
  18469. this._geometries.push(geometry);
  18470. //notify the collision coordinator
  18471. if (this.collisionCoordinator) {
  18472. this.collisionCoordinator.onGeometryAdded(geometry);
  18473. }
  18474. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18475. return true;
  18476. };
  18477. /**
  18478. * Removes an existing geometry
  18479. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18480. * @return {boolean} was the geometry removed or not
  18481. */
  18482. Scene.prototype.removeGeometry = function (geometry) {
  18483. var index = this._geometries.indexOf(geometry);
  18484. if (index > -1) {
  18485. this._geometries.splice(index, 1);
  18486. //notify the collision coordinator
  18487. if (this.collisionCoordinator) {
  18488. this.collisionCoordinator.onGeometryDeleted(geometry);
  18489. }
  18490. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18491. return true;
  18492. }
  18493. return false;
  18494. };
  18495. Scene.prototype.getGeometries = function () {
  18496. return this._geometries;
  18497. };
  18498. /**
  18499. * Get the first added mesh found of a given ID
  18500. * @param {string} id - the id to search for
  18501. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18502. */
  18503. Scene.prototype.getMeshByID = function (id) {
  18504. for (var index = 0; index < this.meshes.length; index++) {
  18505. if (this.meshes[index].id === id) {
  18506. return this.meshes[index];
  18507. }
  18508. }
  18509. return null;
  18510. };
  18511. Scene.prototype.getMeshesByID = function (id) {
  18512. return this.meshes.filter(function (m) {
  18513. return m.id === id;
  18514. });
  18515. };
  18516. /**
  18517. * Get a mesh with its auto-generated unique id
  18518. * @param {number} uniqueId - the unique id to search for
  18519. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18520. */
  18521. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18522. for (var index = 0; index < this.meshes.length; index++) {
  18523. if (this.meshes[index].uniqueId === uniqueId) {
  18524. return this.meshes[index];
  18525. }
  18526. }
  18527. return null;
  18528. };
  18529. /**
  18530. * Get a the last added mesh found of a given ID
  18531. * @param {string} id - the id to search for
  18532. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18533. */
  18534. Scene.prototype.getLastMeshByID = function (id) {
  18535. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18536. if (this.meshes[index].id === id) {
  18537. return this.meshes[index];
  18538. }
  18539. }
  18540. return null;
  18541. };
  18542. /**
  18543. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18544. * @param {string} id - the id to search for
  18545. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18546. */
  18547. Scene.prototype.getLastEntryByID = function (id) {
  18548. var index;
  18549. for (index = this.meshes.length - 1; index >= 0; index--) {
  18550. if (this.meshes[index].id === id) {
  18551. return this.meshes[index];
  18552. }
  18553. }
  18554. for (index = this.cameras.length - 1; index >= 0; index--) {
  18555. if (this.cameras[index].id === id) {
  18556. return this.cameras[index];
  18557. }
  18558. }
  18559. for (index = this.lights.length - 1; index >= 0; index--) {
  18560. if (this.lights[index].id === id) {
  18561. return this.lights[index];
  18562. }
  18563. }
  18564. return null;
  18565. };
  18566. Scene.prototype.getNodeByID = function (id) {
  18567. var mesh = this.getMeshByID(id);
  18568. if (mesh) {
  18569. return mesh;
  18570. }
  18571. var light = this.getLightByID(id);
  18572. if (light) {
  18573. return light;
  18574. }
  18575. var camera = this.getCameraByID(id);
  18576. if (camera) {
  18577. return camera;
  18578. }
  18579. var bone = this.getBoneByID(id);
  18580. return bone;
  18581. };
  18582. Scene.prototype.getNodeByName = function (name) {
  18583. var mesh = this.getMeshByName(name);
  18584. if (mesh) {
  18585. return mesh;
  18586. }
  18587. var light = this.getLightByName(name);
  18588. if (light) {
  18589. return light;
  18590. }
  18591. var camera = this.getCameraByName(name);
  18592. if (camera) {
  18593. return camera;
  18594. }
  18595. var bone = this.getBoneByName(name);
  18596. return bone;
  18597. };
  18598. Scene.prototype.getMeshByName = function (name) {
  18599. for (var index = 0; index < this.meshes.length; index++) {
  18600. if (this.meshes[index].name === name) {
  18601. return this.meshes[index];
  18602. }
  18603. }
  18604. return null;
  18605. };
  18606. Scene.prototype.getSoundByName = function (name) {
  18607. var index;
  18608. if (BABYLON.AudioEngine) {
  18609. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18610. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18611. return this.mainSoundTrack.soundCollection[index];
  18612. }
  18613. }
  18614. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18615. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18616. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18617. return this.soundTracks[sdIndex].soundCollection[index];
  18618. }
  18619. }
  18620. }
  18621. }
  18622. return null;
  18623. };
  18624. Scene.prototype.getLastSkeletonByID = function (id) {
  18625. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18626. if (this.skeletons[index].id === id) {
  18627. return this.skeletons[index];
  18628. }
  18629. }
  18630. return null;
  18631. };
  18632. Scene.prototype.getSkeletonById = function (id) {
  18633. for (var index = 0; index < this.skeletons.length; index++) {
  18634. if (this.skeletons[index].id === id) {
  18635. return this.skeletons[index];
  18636. }
  18637. }
  18638. return null;
  18639. };
  18640. Scene.prototype.getSkeletonByName = function (name) {
  18641. for (var index = 0; index < this.skeletons.length; index++) {
  18642. if (this.skeletons[index].name === name) {
  18643. return this.skeletons[index];
  18644. }
  18645. }
  18646. return null;
  18647. };
  18648. Scene.prototype.getMorphTargetManagerById = function (id) {
  18649. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18650. if (this.morphTargetManagers[index].uniqueId === id) {
  18651. return this.morphTargetManagers[index];
  18652. }
  18653. }
  18654. return null;
  18655. };
  18656. Scene.prototype.isActiveMesh = function (mesh) {
  18657. return (this._activeMeshes.indexOf(mesh) !== -1);
  18658. };
  18659. /**
  18660. * Return a the first highlight layer of the scene with a given name.
  18661. * @param name The name of the highlight layer to look for.
  18662. * @return The highlight layer if found otherwise null.
  18663. */
  18664. Scene.prototype.getHighlightLayerByName = function (name) {
  18665. for (var index = 0; index < this.highlightLayers.length; index++) {
  18666. if (this.highlightLayers[index].name === name) {
  18667. return this.highlightLayers[index];
  18668. }
  18669. }
  18670. return null;
  18671. };
  18672. Object.defineProperty(Scene.prototype, "uid", {
  18673. /**
  18674. * Return a unique id as a string which can serve as an identifier for the scene
  18675. */
  18676. get: function () {
  18677. if (!this._uid) {
  18678. this._uid = BABYLON.Tools.RandomId();
  18679. }
  18680. return this._uid;
  18681. },
  18682. enumerable: true,
  18683. configurable: true
  18684. });
  18685. /**
  18686. * Add an externaly attached data from its key.
  18687. * This method call will fail and return false, if such key already exists.
  18688. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18689. * @param key the unique key that identifies the data
  18690. * @param data the data object to associate to the key for this Engine instance
  18691. * @return true if no such key were already present and the data was added successfully, false otherwise
  18692. */
  18693. Scene.prototype.addExternalData = function (key, data) {
  18694. if (!this._externalData) {
  18695. this._externalData = new BABYLON.StringDictionary();
  18696. }
  18697. return this._externalData.add(key, data);
  18698. };
  18699. /**
  18700. * Get an externaly attached data from its key
  18701. * @param key the unique key that identifies the data
  18702. * @return the associated data, if present (can be null), or undefined if not present
  18703. */
  18704. Scene.prototype.getExternalData = function (key) {
  18705. if (!this._externalData) {
  18706. return null;
  18707. }
  18708. return this._externalData.get(key);
  18709. };
  18710. /**
  18711. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18712. * @param key the unique key that identifies the data
  18713. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18714. * @return the associated data, can be null if the factory returned null.
  18715. */
  18716. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18717. if (!this._externalData) {
  18718. this._externalData = new BABYLON.StringDictionary();
  18719. }
  18720. return this._externalData.getOrAddWithFactory(key, factory);
  18721. };
  18722. /**
  18723. * Remove an externaly attached data from the Engine instance
  18724. * @param key the unique key that identifies the data
  18725. * @return true if the data was successfully removed, false if it doesn't exist
  18726. */
  18727. Scene.prototype.removeExternalData = function (key) {
  18728. return this._externalData.remove(key);
  18729. };
  18730. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18731. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18732. var material = subMesh.getMaterial();
  18733. if (mesh.showSubMeshesBoundingBox) {
  18734. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18735. }
  18736. if (material) {
  18737. // Render targets
  18738. if (material.getRenderTargetTextures) {
  18739. if (this._processedMaterials.indexOf(material) === -1) {
  18740. this._processedMaterials.push(material);
  18741. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18742. }
  18743. }
  18744. // Dispatch
  18745. this._activeIndices.addCount(subMesh.indexCount, false);
  18746. this._renderingManager.dispatch(subMesh);
  18747. }
  18748. }
  18749. };
  18750. Scene.prototype._isInIntermediateRendering = function () {
  18751. return this._intermediateRendering;
  18752. };
  18753. /**
  18754. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  18755. */
  18756. Scene.prototype.freezeActiveMeshes = function () {
  18757. this._evaluateActiveMeshes();
  18758. this._activeMeshesFrozen = true;
  18759. return this;
  18760. };
  18761. /**
  18762. * Use this function to restart evaluating active meshes on every frame
  18763. */
  18764. Scene.prototype.unfreezeActiveMeshes = function () {
  18765. this._activeMeshesFrozen = false;
  18766. return this;
  18767. };
  18768. Scene.prototype._evaluateActiveMeshes = function () {
  18769. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  18770. return;
  18771. }
  18772. this.activeCamera._activeMeshes.reset();
  18773. this._activeMeshes.reset();
  18774. this._renderingManager.reset();
  18775. this._processedMaterials.reset();
  18776. this._activeParticleSystems.reset();
  18777. this._activeSkeletons.reset();
  18778. this._softwareSkinnedMeshes.reset();
  18779. if (this._boundingBoxRenderer) {
  18780. this._boundingBoxRenderer.reset();
  18781. }
  18782. // Meshes
  18783. var meshes;
  18784. var len;
  18785. if (this._selectionOctree) {
  18786. var selection = this._selectionOctree.select(this._frustumPlanes);
  18787. meshes = selection.data;
  18788. len = selection.length;
  18789. }
  18790. else {
  18791. len = this.meshes.length;
  18792. meshes = this.meshes;
  18793. }
  18794. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18795. var mesh = meshes[meshIndex];
  18796. if (mesh.isBlocked) {
  18797. continue;
  18798. }
  18799. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18800. if (!mesh.isReady() || !mesh.isEnabled()) {
  18801. continue;
  18802. }
  18803. mesh.computeWorldMatrix();
  18804. // Intersections
  18805. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18806. this._meshesForIntersections.pushNoDuplicate(mesh);
  18807. }
  18808. // Switch to current LOD
  18809. var meshLOD = mesh.getLOD(this.activeCamera);
  18810. if (!meshLOD) {
  18811. continue;
  18812. }
  18813. mesh._preActivate();
  18814. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18815. this._activeMeshes.push(mesh);
  18816. this.activeCamera._activeMeshes.push(mesh);
  18817. mesh._activate(this._renderId);
  18818. if (meshLOD !== mesh) {
  18819. meshLOD._activate(this._renderId);
  18820. }
  18821. this._activeMesh(mesh, meshLOD);
  18822. }
  18823. }
  18824. // Particle systems
  18825. this._particlesDuration.beginMonitoring();
  18826. var beforeParticlesDate = BABYLON.Tools.Now;
  18827. if (this.particlesEnabled) {
  18828. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18829. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18830. var particleSystem = this.particleSystems[particleIndex];
  18831. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18832. continue;
  18833. }
  18834. var emitter = particleSystem.emitter;
  18835. if (!emitter.position || emitter.isEnabled()) {
  18836. this._activeParticleSystems.push(particleSystem);
  18837. particleSystem.animate();
  18838. this._renderingManager.dispatchParticles(particleSystem);
  18839. }
  18840. }
  18841. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18842. }
  18843. this._particlesDuration.endMonitoring(false);
  18844. };
  18845. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18846. if (mesh.skeleton && this.skeletonsEnabled) {
  18847. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18848. mesh.skeleton.prepare();
  18849. }
  18850. if (!mesh.computeBonesUsingShaders) {
  18851. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18852. }
  18853. }
  18854. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18855. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18856. }
  18857. if (mesh && mesh.subMeshes) {
  18858. // Submeshes Octrees
  18859. var len;
  18860. var subMeshes;
  18861. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18862. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18863. len = intersections.length;
  18864. subMeshes = intersections.data;
  18865. }
  18866. else {
  18867. subMeshes = mesh.subMeshes;
  18868. len = subMeshes.length;
  18869. }
  18870. for (var subIndex = 0; subIndex < len; subIndex++) {
  18871. var subMesh = subMeshes[subIndex];
  18872. this._evaluateSubMesh(subMesh, mesh);
  18873. }
  18874. }
  18875. };
  18876. Scene.prototype.updateTransformMatrix = function (force) {
  18877. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18878. };
  18879. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  18880. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  18881. };
  18882. Scene.prototype._renderForCamera = function (camera) {
  18883. if (camera && camera._skipRendering) {
  18884. return;
  18885. }
  18886. var engine = this._engine;
  18887. var startTime = BABYLON.Tools.Now;
  18888. this.activeCamera = camera;
  18889. if (!this.activeCamera)
  18890. throw new Error("Active camera not set");
  18891. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18892. // Viewport
  18893. engine.setViewport(this.activeCamera.viewport);
  18894. // Camera
  18895. this.resetCachedMaterial();
  18896. this._renderId++;
  18897. this.activeCamera.update();
  18898. this.updateTransformMatrix();
  18899. if (camera._alternateCamera) {
  18900. this.updateAlternateTransformMatrix(camera._alternateCamera);
  18901. this._alternateRendering = true;
  18902. }
  18903. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18904. // Meshes
  18905. this._evaluateActiveMeshesDuration.beginMonitoring();
  18906. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18907. this._evaluateActiveMeshes();
  18908. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18909. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18910. // Software skinning
  18911. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18912. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18913. mesh.applySkeleton(mesh.skeleton);
  18914. }
  18915. // Render targets
  18916. this._renderTargetsDuration.beginMonitoring();
  18917. var needsRestoreFrameBuffer = false;
  18918. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18919. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18920. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18921. }
  18922. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18923. this._intermediateRendering = true;
  18924. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18925. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18926. var renderTarget = this._renderTargets.data[renderIndex];
  18927. if (renderTarget._shouldRender()) {
  18928. this._renderId++;
  18929. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18930. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18931. }
  18932. }
  18933. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18934. this._intermediateRendering = false;
  18935. this._renderId++;
  18936. needsRestoreFrameBuffer = true; // Restore back buffer
  18937. }
  18938. // Render HighlightLayer Texture
  18939. var stencilState = this._engine.getStencilBuffer();
  18940. var renderhighlights = false;
  18941. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18942. this._intermediateRendering = true;
  18943. for (var i = 0; i < this.highlightLayers.length; i++) {
  18944. var highlightLayer = this.highlightLayers[i];
  18945. if (highlightLayer.shouldRender() &&
  18946. (!highlightLayer.camera ||
  18947. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18948. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18949. renderhighlights = true;
  18950. var renderTarget = highlightLayer._mainTexture;
  18951. if (renderTarget._shouldRender()) {
  18952. this._renderId++;
  18953. renderTarget.render(false, false);
  18954. needsRestoreFrameBuffer = true;
  18955. }
  18956. }
  18957. }
  18958. this._intermediateRendering = false;
  18959. this._renderId++;
  18960. }
  18961. if (needsRestoreFrameBuffer) {
  18962. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18963. }
  18964. this._renderTargetsDuration.endMonitoring(false);
  18965. // Prepare Frame
  18966. this.postProcessManager._prepareFrame();
  18967. this._renderDuration.beginMonitoring();
  18968. // Backgrounds
  18969. var layerIndex;
  18970. var layer;
  18971. if (this.layers.length) {
  18972. engine.setDepthBuffer(false);
  18973. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18974. layer = this.layers[layerIndex];
  18975. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18976. layer.render();
  18977. }
  18978. }
  18979. engine.setDepthBuffer(true);
  18980. }
  18981. // Render
  18982. BABYLON.Tools.StartPerformanceCounter("Main render");
  18983. // Activate HighlightLayer stencil
  18984. if (renderhighlights) {
  18985. this._engine.setStencilBuffer(true);
  18986. }
  18987. this._renderingManager.render(null, null, true, true);
  18988. // Restore HighlightLayer stencil
  18989. if (renderhighlights) {
  18990. this._engine.setStencilBuffer(stencilState);
  18991. }
  18992. BABYLON.Tools.EndPerformanceCounter("Main render");
  18993. // Bounding boxes
  18994. if (this._boundingBoxRenderer) {
  18995. this._boundingBoxRenderer.render();
  18996. }
  18997. // Lens flares
  18998. if (this.lensFlaresEnabled) {
  18999. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19000. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19001. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19002. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19003. lensFlareSystem.render();
  19004. }
  19005. }
  19006. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19007. }
  19008. // Foregrounds
  19009. if (this.layers.length) {
  19010. engine.setDepthBuffer(false);
  19011. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19012. layer = this.layers[layerIndex];
  19013. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19014. layer.render();
  19015. }
  19016. }
  19017. engine.setDepthBuffer(true);
  19018. }
  19019. // Highlight Layer
  19020. if (renderhighlights) {
  19021. engine.setDepthBuffer(false);
  19022. for (var i = 0; i < this.highlightLayers.length; i++) {
  19023. if (this.highlightLayers[i].shouldRender()) {
  19024. this.highlightLayers[i].render();
  19025. }
  19026. }
  19027. engine.setDepthBuffer(true);
  19028. }
  19029. this._renderDuration.endMonitoring(false);
  19030. // Finalize frame
  19031. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19032. // Reset some special arrays
  19033. this._renderTargets.reset();
  19034. this._alternateRendering = false;
  19035. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19036. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19037. };
  19038. Scene.prototype._processSubCameras = function (camera) {
  19039. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19040. this._renderForCamera(camera);
  19041. return;
  19042. }
  19043. // Update camera
  19044. this.activeCamera.update();
  19045. // rig cameras
  19046. for (var index = 0; index < camera._rigCameras.length; index++) {
  19047. this._renderForCamera(camera._rigCameras[index]);
  19048. }
  19049. this.activeCamera = camera;
  19050. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19051. };
  19052. Scene.prototype._checkIntersections = function () {
  19053. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19054. var sourceMesh = this._meshesForIntersections.data[index];
  19055. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19056. var action = sourceMesh.actionManager.actions[actionIndex];
  19057. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19058. var parameters = action.getTriggerParameter();
  19059. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19060. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19061. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19062. if (areIntersecting && currentIntersectionInProgress === -1) {
  19063. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19064. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19065. sourceMesh._intersectionsInProgress.push(otherMesh);
  19066. }
  19067. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19068. sourceMesh._intersectionsInProgress.push(otherMesh);
  19069. }
  19070. }
  19071. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19072. //They intersected, and now they don't.
  19073. //is this trigger an exit trigger? execute an event.
  19074. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19075. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19076. }
  19077. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19078. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19079. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19080. }
  19081. }
  19082. }
  19083. }
  19084. }
  19085. };
  19086. Scene.prototype.render = function () {
  19087. if (this.isDisposed) {
  19088. return;
  19089. }
  19090. this._interFrameDuration.endMonitoring();
  19091. this._lastFrameDuration.beginMonitoring();
  19092. this._particlesDuration.fetchNewFrame();
  19093. this._spritesDuration.fetchNewFrame();
  19094. this._activeParticles.fetchNewFrame();
  19095. this._renderDuration.fetchNewFrame();
  19096. this._renderTargetsDuration.fetchNewFrame();
  19097. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19098. this._totalVertices.fetchNewFrame();
  19099. this._activeIndices.fetchNewFrame();
  19100. this._activeBones.fetchNewFrame();
  19101. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19102. this._meshesForIntersections.reset();
  19103. this.resetCachedMaterial();
  19104. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19105. // Actions
  19106. if (this.actionManager) {
  19107. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19108. }
  19109. //Simplification Queue
  19110. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19111. this.simplificationQueue.executeNext();
  19112. }
  19113. if (this._engine.isDeterministicLockStep()) {
  19114. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19115. var defaultTimeStep = (60.0 / 1000.0);
  19116. if (this._physicsEngine) {
  19117. defaultTimeStep = this._physicsEngine.getTimeStep();
  19118. }
  19119. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19120. this._timeAccumulator += deltaTime;
  19121. // compute the amount of fixed steps we should have taken since the last step
  19122. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19123. internalSteps = Math.min(internalSteps, maxSubSteps);
  19124. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19125. this.onBeforeStepObservable.notifyObservers(this);
  19126. // Animations
  19127. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19128. this._animate();
  19129. // Physics
  19130. if (this._physicsEngine) {
  19131. BABYLON.Tools.StartPerformanceCounter("Physics");
  19132. this._physicsEngine._step(defaultTimeStep);
  19133. BABYLON.Tools.EndPerformanceCounter("Physics");
  19134. }
  19135. this._timeAccumulator -= defaultTimeStep;
  19136. this.onAfterStepObservable.notifyObservers(this);
  19137. this._currentStepId++;
  19138. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19139. this._evaluateActiveMeshes();
  19140. }
  19141. }
  19142. }
  19143. else {
  19144. // Animations
  19145. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19146. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19147. this._animate();
  19148. // Physics
  19149. if (this._physicsEngine) {
  19150. BABYLON.Tools.StartPerformanceCounter("Physics");
  19151. this._physicsEngine._step(deltaTime / 1000.0);
  19152. BABYLON.Tools.EndPerformanceCounter("Physics");
  19153. }
  19154. }
  19155. // Before render
  19156. this.onBeforeRenderObservable.notifyObservers(this);
  19157. // Customs render targets
  19158. this._renderTargetsDuration.beginMonitoring();
  19159. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19160. var engine = this.getEngine();
  19161. var currentActiveCamera = this.activeCamera;
  19162. if (this.renderTargetsEnabled) {
  19163. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19164. this._intermediateRendering = true;
  19165. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19166. var renderTarget = this.customRenderTargets[customIndex];
  19167. if (renderTarget._shouldRender()) {
  19168. this._renderId++;
  19169. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19170. if (!this.activeCamera)
  19171. throw new Error("Active camera not set");
  19172. // Viewport
  19173. engine.setViewport(this.activeCamera.viewport);
  19174. // Camera
  19175. this.updateTransformMatrix();
  19176. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19177. }
  19178. }
  19179. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19180. this._intermediateRendering = false;
  19181. this._renderId++;
  19182. }
  19183. // Restore back buffer
  19184. if (this.customRenderTargets.length > 0) {
  19185. engine.restoreDefaultFramebuffer();
  19186. }
  19187. this._renderTargetsDuration.endMonitoring();
  19188. this.activeCamera = currentActiveCamera;
  19189. // Procedural textures
  19190. if (this.proceduralTexturesEnabled) {
  19191. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19192. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19193. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19194. if (proceduralTexture._shouldRender()) {
  19195. proceduralTexture.render();
  19196. }
  19197. }
  19198. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19199. }
  19200. // Clear
  19201. if (this.autoClearDepthAndStencil || this.autoClear) {
  19202. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19203. }
  19204. // Shadows
  19205. if (this.shadowsEnabled) {
  19206. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19207. var light = this.lights[lightIndex];
  19208. var shadowGenerator = light.getShadowGenerator();
  19209. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19210. var shadowMap = shadowGenerator.getShadowMap();
  19211. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  19212. this._renderTargets.push(shadowMap);
  19213. }
  19214. }
  19215. }
  19216. }
  19217. // Depth renderer
  19218. if (this._depthRenderer) {
  19219. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19220. }
  19221. // Geometry renderer
  19222. if (this._geometryBufferRenderer) {
  19223. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19224. }
  19225. // RenderPipeline
  19226. if (this._postProcessRenderPipelineManager) {
  19227. this._postProcessRenderPipelineManager.update();
  19228. }
  19229. // Multi-cameras?
  19230. if (this.activeCameras.length > 0) {
  19231. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19232. if (cameraIndex > 0) {
  19233. this._engine.clear(null, false, true, true);
  19234. }
  19235. this._processSubCameras(this.activeCameras[cameraIndex]);
  19236. }
  19237. }
  19238. else {
  19239. if (!this.activeCamera) {
  19240. throw new Error("No camera defined");
  19241. }
  19242. this._processSubCameras(this.activeCamera);
  19243. }
  19244. // Intersection checks
  19245. this._checkIntersections();
  19246. // Update the audio listener attached to the camera
  19247. if (BABYLON.AudioEngine) {
  19248. this._updateAudioParameters();
  19249. }
  19250. // After render
  19251. if (this.afterRender) {
  19252. this.afterRender();
  19253. }
  19254. this.onAfterRenderObservable.notifyObservers(this);
  19255. // Cleaning
  19256. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19257. this._toBeDisposed.data[index].dispose();
  19258. this._toBeDisposed[index] = null;
  19259. }
  19260. this._toBeDisposed.reset();
  19261. if (this.dumpNextRenderTargets) {
  19262. this.dumpNextRenderTargets = false;
  19263. }
  19264. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19265. this._interFrameDuration.beginMonitoring();
  19266. this._lastFrameDuration.endMonitoring();
  19267. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19268. this._totalLightsCounter.addCount(this.lights.length, true);
  19269. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19270. this._totalTexturesCounter.addCount(this.textures.length, true);
  19271. this._activeBones.addCount(0, true);
  19272. this._activeIndices.addCount(0, true);
  19273. this._activeParticles.addCount(0, true);
  19274. };
  19275. Scene.prototype._updateAudioParameters = function () {
  19276. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19277. return;
  19278. }
  19279. var listeningCamera;
  19280. var audioEngine = BABYLON.Engine.audioEngine;
  19281. if (this.activeCameras.length > 0) {
  19282. listeningCamera = this.activeCameras[0];
  19283. }
  19284. else {
  19285. listeningCamera = this.activeCamera;
  19286. }
  19287. if (listeningCamera && audioEngine.canUseWebAudio) {
  19288. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19289. // for VR cameras
  19290. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19291. listeningCamera = listeningCamera.rigCameras[0];
  19292. }
  19293. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19294. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19295. cameraDirection.normalize();
  19296. // To avoid some errors on GearVR
  19297. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19298. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19299. }
  19300. var i;
  19301. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19302. var sound = this.mainSoundTrack.soundCollection[i];
  19303. if (sound.useCustomAttenuation) {
  19304. sound.updateDistanceFromListener();
  19305. }
  19306. }
  19307. for (i = 0; i < this.soundTracks.length; i++) {
  19308. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19309. sound = this.soundTracks[i].soundCollection[j];
  19310. if (sound.useCustomAttenuation) {
  19311. sound.updateDistanceFromListener();
  19312. }
  19313. }
  19314. }
  19315. }
  19316. };
  19317. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19318. // Audio
  19319. get: function () {
  19320. return this._audioEnabled;
  19321. },
  19322. set: function (value) {
  19323. this._audioEnabled = value;
  19324. if (BABYLON.AudioEngine) {
  19325. if (this._audioEnabled) {
  19326. this._enableAudio();
  19327. }
  19328. else {
  19329. this._disableAudio();
  19330. }
  19331. }
  19332. },
  19333. enumerable: true,
  19334. configurable: true
  19335. });
  19336. Scene.prototype._disableAudio = function () {
  19337. var i;
  19338. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19339. this.mainSoundTrack.soundCollection[i].pause();
  19340. }
  19341. for (i = 0; i < this.soundTracks.length; i++) {
  19342. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19343. this.soundTracks[i].soundCollection[j].pause();
  19344. }
  19345. }
  19346. };
  19347. Scene.prototype._enableAudio = function () {
  19348. var i;
  19349. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19350. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19351. this.mainSoundTrack.soundCollection[i].play();
  19352. }
  19353. }
  19354. for (i = 0; i < this.soundTracks.length; i++) {
  19355. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19356. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19357. this.soundTracks[i].soundCollection[j].play();
  19358. }
  19359. }
  19360. }
  19361. };
  19362. Object.defineProperty(Scene.prototype, "headphone", {
  19363. get: function () {
  19364. return this._headphone;
  19365. },
  19366. set: function (value) {
  19367. this._headphone = value;
  19368. if (BABYLON.AudioEngine) {
  19369. if (this._headphone) {
  19370. this._switchAudioModeForHeadphones();
  19371. }
  19372. else {
  19373. this._switchAudioModeForNormalSpeakers();
  19374. }
  19375. }
  19376. },
  19377. enumerable: true,
  19378. configurable: true
  19379. });
  19380. Scene.prototype._switchAudioModeForHeadphones = function () {
  19381. this.mainSoundTrack.switchPanningModelToHRTF();
  19382. for (var i = 0; i < this.soundTracks.length; i++) {
  19383. this.soundTracks[i].switchPanningModelToHRTF();
  19384. }
  19385. };
  19386. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19387. this.mainSoundTrack.switchPanningModelToEqualPower();
  19388. for (var i = 0; i < this.soundTracks.length; i++) {
  19389. this.soundTracks[i].switchPanningModelToEqualPower();
  19390. }
  19391. };
  19392. Scene.prototype.enableDepthRenderer = function () {
  19393. if (this._depthRenderer) {
  19394. return this._depthRenderer;
  19395. }
  19396. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19397. return this._depthRenderer;
  19398. };
  19399. Scene.prototype.disableDepthRenderer = function () {
  19400. if (!this._depthRenderer) {
  19401. return;
  19402. }
  19403. this._depthRenderer.dispose();
  19404. this._depthRenderer = null;
  19405. };
  19406. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19407. if (ratio === void 0) { ratio = 1; }
  19408. if (this._geometryBufferRenderer) {
  19409. return this._geometryBufferRenderer;
  19410. }
  19411. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19412. if (!this._geometryBufferRenderer.isSupported) {
  19413. this._geometryBufferRenderer = null;
  19414. }
  19415. return this._geometryBufferRenderer;
  19416. };
  19417. Scene.prototype.disableGeometryBufferRenderer = function () {
  19418. if (!this._geometryBufferRenderer) {
  19419. return;
  19420. }
  19421. this._geometryBufferRenderer.dispose();
  19422. this._geometryBufferRenderer = null;
  19423. };
  19424. Scene.prototype.freezeMaterials = function () {
  19425. for (var i = 0; i < this.materials.length; i++) {
  19426. this.materials[i].freeze();
  19427. }
  19428. };
  19429. Scene.prototype.unfreezeMaterials = function () {
  19430. for (var i = 0; i < this.materials.length; i++) {
  19431. this.materials[i].unfreeze();
  19432. }
  19433. };
  19434. Scene.prototype.dispose = function () {
  19435. this.beforeRender = null;
  19436. this.afterRender = null;
  19437. this.skeletons = [];
  19438. this.morphTargetManagers = [];
  19439. this.importedMeshesFiles = new Array();
  19440. this.resetCachedMaterial();
  19441. if (this._depthRenderer) {
  19442. this._depthRenderer.dispose();
  19443. }
  19444. if (this._gamepadManager) {
  19445. this._gamepadManager.dispose();
  19446. this._gamepadManager = null;
  19447. }
  19448. // Smart arrays
  19449. if (this.activeCamera) {
  19450. this.activeCamera._activeMeshes.dispose();
  19451. this.activeCamera = null;
  19452. }
  19453. this._activeMeshes.dispose();
  19454. this._renderingManager.dispose();
  19455. this._processedMaterials.dispose();
  19456. this._activeParticleSystems.dispose();
  19457. this._activeSkeletons.dispose();
  19458. this._softwareSkinnedMeshes.dispose();
  19459. this._renderTargets.dispose();
  19460. if (this._boundingBoxRenderer) {
  19461. this._boundingBoxRenderer.dispose();
  19462. }
  19463. this._meshesForIntersections.dispose();
  19464. this._toBeDisposed.dispose();
  19465. // Debug layer
  19466. if (this._debugLayer) {
  19467. this._debugLayer.hide();
  19468. }
  19469. // Events
  19470. this.onDisposeObservable.notifyObservers(this);
  19471. this.onDisposeObservable.clear();
  19472. this.onBeforeRenderObservable.clear();
  19473. this.onAfterRenderObservable.clear();
  19474. this.detachControl();
  19475. // Release sounds & sounds tracks
  19476. if (BABYLON.AudioEngine) {
  19477. this.disposeSounds();
  19478. }
  19479. // VR Helper
  19480. if (this.VRHelper) {
  19481. this.VRHelper.dispose();
  19482. }
  19483. // Detach cameras
  19484. var canvas = this._engine.getRenderingCanvas();
  19485. var index;
  19486. for (index = 0; index < this.cameras.length; index++) {
  19487. this.cameras[index].detachControl(canvas);
  19488. }
  19489. // Release lights
  19490. while (this.lights.length) {
  19491. this.lights[0].dispose();
  19492. }
  19493. // Release meshes
  19494. while (this.meshes.length) {
  19495. this.meshes[0].dispose(true);
  19496. }
  19497. // Release cameras
  19498. while (this.cameras.length) {
  19499. this.cameras[0].dispose();
  19500. }
  19501. // Release materials
  19502. if (this.defaultMaterial) {
  19503. this.defaultMaterial.dispose();
  19504. }
  19505. while (this.multiMaterials.length) {
  19506. this.multiMaterials[0].dispose();
  19507. }
  19508. while (this.materials.length) {
  19509. this.materials[0].dispose();
  19510. }
  19511. // Release particles
  19512. while (this.particleSystems.length) {
  19513. this.particleSystems[0].dispose();
  19514. }
  19515. // Release sprites
  19516. while (this.spriteManagers.length) {
  19517. this.spriteManagers[0].dispose();
  19518. }
  19519. // Release postProcesses
  19520. while (this.postProcesses.length) {
  19521. this.postProcesses[0].dispose();
  19522. }
  19523. // Release layers
  19524. while (this.layers.length) {
  19525. this.layers[0].dispose();
  19526. }
  19527. while (this.highlightLayers.length) {
  19528. this.highlightLayers[0].dispose();
  19529. }
  19530. // Release textures
  19531. while (this.textures.length) {
  19532. this.textures[0].dispose();
  19533. }
  19534. // Release UBO
  19535. this._sceneUbo.dispose();
  19536. if (this._alternateSceneUbo) {
  19537. this._alternateSceneUbo.dispose();
  19538. }
  19539. // Post-processes
  19540. this.postProcessManager.dispose();
  19541. if (this._postProcessRenderPipelineManager) {
  19542. this._postProcessRenderPipelineManager.dispose();
  19543. }
  19544. // Physics
  19545. if (this._physicsEngine) {
  19546. this.disablePhysicsEngine();
  19547. }
  19548. // Remove from engine
  19549. index = this._engine.scenes.indexOf(this);
  19550. if (index > -1) {
  19551. this._engine.scenes.splice(index, 1);
  19552. }
  19553. this._engine.wipeCaches();
  19554. this._engine = null;
  19555. this.defaultMaterial = null;
  19556. this.multiMaterials = null;
  19557. this.materials = null;
  19558. };
  19559. Object.defineProperty(Scene.prototype, "isDisposed", {
  19560. get: function () {
  19561. return !this._engine;
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. // Release sounds & sounds tracks
  19567. Scene.prototype.disposeSounds = function () {
  19568. if (!this._mainSoundTrack) {
  19569. return;
  19570. }
  19571. this.mainSoundTrack.dispose();
  19572. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19573. this.soundTracks[scIndex].dispose();
  19574. }
  19575. };
  19576. // Octrees
  19577. Scene.prototype.getWorldExtends = function () {
  19578. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19579. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19580. for (var index = 0; index < this.meshes.length; index++) {
  19581. var mesh = this.meshes[index];
  19582. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19583. continue;
  19584. }
  19585. mesh.computeWorldMatrix(true);
  19586. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19587. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19588. BABYLON.Tools.CheckExtends(minBox, min, max);
  19589. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19590. }
  19591. return {
  19592. min: min,
  19593. max: max
  19594. };
  19595. };
  19596. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19597. if (maxCapacity === void 0) { maxCapacity = 64; }
  19598. if (maxDepth === void 0) { maxDepth = 2; }
  19599. if (!this._selectionOctree) {
  19600. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19601. }
  19602. var worldExtends = this.getWorldExtends();
  19603. // Update octree
  19604. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19605. return this._selectionOctree;
  19606. };
  19607. // Picking
  19608. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19609. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19610. var engine = this._engine;
  19611. if (!camera) {
  19612. if (!this.activeCamera)
  19613. throw new Error("Active camera not set");
  19614. camera = this.activeCamera;
  19615. }
  19616. var cameraViewport = camera.viewport;
  19617. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19618. // Moving coordinates to local viewport world
  19619. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19620. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19621. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19622. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19623. };
  19624. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19625. if (!BABYLON.PickingInfo) {
  19626. return null;
  19627. }
  19628. var engine = this._engine;
  19629. if (!camera) {
  19630. if (!this.activeCamera)
  19631. throw new Error("Active camera not set");
  19632. camera = this.activeCamera;
  19633. }
  19634. var cameraViewport = camera.viewport;
  19635. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19636. var identity = BABYLON.Matrix.Identity();
  19637. // Moving coordinates to local viewport world
  19638. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19639. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19640. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19641. };
  19642. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19643. if (!BABYLON.PickingInfo) {
  19644. return null;
  19645. }
  19646. var pickingInfo = null;
  19647. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19648. var mesh = this.meshes[meshIndex];
  19649. if (predicate) {
  19650. if (!predicate(mesh)) {
  19651. continue;
  19652. }
  19653. }
  19654. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19655. continue;
  19656. }
  19657. var world = mesh.getWorldMatrix();
  19658. var ray = rayFunction(world);
  19659. var result = mesh.intersects(ray, fastCheck);
  19660. if (!result || !result.hit)
  19661. continue;
  19662. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19663. continue;
  19664. pickingInfo = result;
  19665. if (fastCheck) {
  19666. break;
  19667. }
  19668. }
  19669. return pickingInfo || new BABYLON.PickingInfo();
  19670. };
  19671. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19672. if (!BABYLON.PickingInfo) {
  19673. return null;
  19674. }
  19675. var pickingInfos = new Array();
  19676. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19677. var mesh = this.meshes[meshIndex];
  19678. if (predicate) {
  19679. if (!predicate(mesh)) {
  19680. continue;
  19681. }
  19682. }
  19683. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19684. continue;
  19685. }
  19686. var world = mesh.getWorldMatrix();
  19687. var ray = rayFunction(world);
  19688. var result = mesh.intersects(ray, false);
  19689. if (!result || !result.hit)
  19690. continue;
  19691. pickingInfos.push(result);
  19692. }
  19693. return pickingInfos;
  19694. };
  19695. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19696. if (!BABYLON.PickingInfo) {
  19697. return null;
  19698. }
  19699. var pickingInfo = null;
  19700. camera = camera || this.activeCamera;
  19701. if (this.spriteManagers.length > 0) {
  19702. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19703. var spriteManager = this.spriteManagers[spriteIndex];
  19704. if (!spriteManager.isPickable) {
  19705. continue;
  19706. }
  19707. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19708. if (!result || !result.hit)
  19709. continue;
  19710. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19711. continue;
  19712. pickingInfo = result;
  19713. if (fastCheck) {
  19714. break;
  19715. }
  19716. }
  19717. }
  19718. return pickingInfo || new BABYLON.PickingInfo();
  19719. };
  19720. /** Launch a ray to try to pick a mesh in the scene
  19721. * @param x position on screen
  19722. * @param y position on screen
  19723. * @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
  19724. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19725. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19726. */
  19727. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19728. var _this = this;
  19729. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19730. };
  19731. /** Launch a ray to try to pick a sprite in the scene
  19732. * @param x position on screen
  19733. * @param y position on screen
  19734. * @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
  19735. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19736. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19737. */
  19738. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19739. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19740. };
  19741. /** Use the given ray to pick a mesh in the scene
  19742. * @param ray The ray to use to pick meshes
  19743. * @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
  19744. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19745. */
  19746. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19747. var _this = this;
  19748. return this._internalPick(function (world) {
  19749. if (!_this._pickWithRayInverseMatrix) {
  19750. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19751. }
  19752. world.invertToRef(_this._pickWithRayInverseMatrix);
  19753. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19754. }, predicate, fastCheck);
  19755. };
  19756. /**
  19757. * Launch a ray to try to pick a mesh in the scene
  19758. * @param x X position on screen
  19759. * @param y Y position on screen
  19760. * @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
  19761. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19762. */
  19763. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19764. var _this = this;
  19765. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19766. };
  19767. /**
  19768. * Launch a ray to try to pick a mesh in the scene
  19769. * @param ray Ray to use
  19770. * @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
  19771. */
  19772. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19773. var _this = this;
  19774. return this._internalMultiPick(function (world) {
  19775. if (!_this._pickWithRayInverseMatrix) {
  19776. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19777. }
  19778. world.invertToRef(_this._pickWithRayInverseMatrix);
  19779. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19780. }, predicate);
  19781. };
  19782. Scene.prototype.setPointerOverMesh = function (mesh) {
  19783. if (this._pointerOverMesh === mesh) {
  19784. return;
  19785. }
  19786. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19787. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19788. }
  19789. this._pointerOverMesh = mesh;
  19790. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19791. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19792. }
  19793. };
  19794. Scene.prototype.getPointerOverMesh = function () {
  19795. return this._pointerOverMesh;
  19796. };
  19797. Scene.prototype.setPointerOverSprite = function (sprite) {
  19798. if (this._pointerOverSprite === sprite) {
  19799. return;
  19800. }
  19801. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19802. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19803. }
  19804. this._pointerOverSprite = sprite;
  19805. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19806. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19807. }
  19808. };
  19809. Scene.prototype.getPointerOverSprite = function () {
  19810. return this._pointerOverSprite;
  19811. };
  19812. // Physics
  19813. Scene.prototype.getPhysicsEngine = function () {
  19814. return this._physicsEngine;
  19815. };
  19816. /**
  19817. * Enables physics to the current scene
  19818. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19819. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19820. * @return {boolean} was the physics engine initialized
  19821. */
  19822. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19823. if (this._physicsEngine) {
  19824. return true;
  19825. }
  19826. try {
  19827. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19828. return true;
  19829. }
  19830. catch (e) {
  19831. BABYLON.Tools.Error(e.message);
  19832. return false;
  19833. }
  19834. };
  19835. Scene.prototype.disablePhysicsEngine = function () {
  19836. if (!this._physicsEngine) {
  19837. return;
  19838. }
  19839. this._physicsEngine.dispose();
  19840. this._physicsEngine = undefined;
  19841. };
  19842. Scene.prototype.isPhysicsEnabled = function () {
  19843. return this._physicsEngine !== undefined;
  19844. };
  19845. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19846. var mesh = compound.parts[0].mesh;
  19847. mesh.physicsImpostor.dispose();
  19848. mesh.physicsImpostor = null;
  19849. };
  19850. // Misc.
  19851. Scene.prototype._rebuildGeometries = function () {
  19852. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19853. var geometry = _a[_i];
  19854. geometry._rebuild();
  19855. }
  19856. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19857. var mesh = _c[_b];
  19858. mesh._rebuild();
  19859. }
  19860. if (this.postProcessManager) {
  19861. this.postProcessManager._rebuild();
  19862. }
  19863. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19864. var layer = _e[_d];
  19865. layer._rebuild();
  19866. }
  19867. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19868. var highlightLayer = _g[_f];
  19869. highlightLayer._rebuild();
  19870. }
  19871. if (this._boundingBoxRenderer) {
  19872. this._boundingBoxRenderer._rebuild();
  19873. }
  19874. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19875. var system = _j[_h];
  19876. system.rebuild();
  19877. }
  19878. if (this._postProcessRenderPipelineManager) {
  19879. this._postProcessRenderPipelineManager._rebuild();
  19880. }
  19881. };
  19882. Scene.prototype._rebuildTextures = function () {
  19883. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19884. var texture = _a[_i];
  19885. texture._rebuild();
  19886. }
  19887. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19888. };
  19889. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19890. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19891. if (replace === void 0) { replace = false; }
  19892. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19893. // Dispose existing camera or light in replace mode.
  19894. if (replace) {
  19895. if (this.activeCamera) {
  19896. this.activeCamera.dispose();
  19897. this.activeCamera = null;
  19898. }
  19899. if (this.lights) {
  19900. for (var i = 0; i < this.lights.length; i++) {
  19901. this.lights[i].dispose();
  19902. }
  19903. }
  19904. }
  19905. // Light
  19906. if (this.lights.length === 0) {
  19907. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19908. }
  19909. // Camera
  19910. if (!this.activeCamera) {
  19911. var worldExtends = this.getWorldExtends();
  19912. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19913. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19914. var camera;
  19915. var radius = worldSize.length() * 1.5;
  19916. if (createArcRotateCamera) {
  19917. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19918. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19919. arcRotateCamera.wheelPrecision = 100 / radius;
  19920. camera = arcRotateCamera;
  19921. }
  19922. else {
  19923. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19924. freeCamera.setTarget(worldCenter);
  19925. camera = freeCamera;
  19926. }
  19927. camera.minZ = radius * 0.01;
  19928. camera.maxZ = radius * 100;
  19929. camera.speed = radius * 0.2;
  19930. this.activeCamera = camera;
  19931. if (attachCameraControls) {
  19932. camera.attachControl(this.getEngine().getRenderingCanvas());
  19933. }
  19934. }
  19935. };
  19936. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19937. if (pbr === void 0) { pbr = false; }
  19938. if (scale === void 0) { scale = 1000; }
  19939. if (blur === void 0) { blur = 0; }
  19940. if (environmentTexture) {
  19941. this.environmentTexture = environmentTexture;
  19942. }
  19943. if (!this.environmentTexture) {
  19944. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19945. return;
  19946. }
  19947. // Skybox
  19948. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19949. if (pbr) {
  19950. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19951. hdrSkyboxMaterial.backFaceCulling = false;
  19952. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19953. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19954. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19955. hdrSkyboxMaterial.disableLighting = true;
  19956. hdrSkyboxMaterial.twoSidedLighting = true;
  19957. hdrSkybox.infiniteDistance = true;
  19958. hdrSkybox.material = hdrSkyboxMaterial;
  19959. }
  19960. else {
  19961. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19962. skyboxMaterial.backFaceCulling = false;
  19963. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19964. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19965. skyboxMaterial.disableLighting = true;
  19966. hdrSkybox.infiniteDistance = true;
  19967. hdrSkybox.material = skyboxMaterial;
  19968. }
  19969. return hdrSkybox;
  19970. };
  19971. Scene.prototype.createDefaultVRExperience = function () {
  19972. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19973. };
  19974. // Tags
  19975. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19976. if (tagsQuery === undefined) {
  19977. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19978. return list;
  19979. }
  19980. var listByTags = [];
  19981. forEach = forEach || (function (item) { return; });
  19982. for (var i in list) {
  19983. var item = list[i];
  19984. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19985. listByTags.push(item);
  19986. forEach(item);
  19987. }
  19988. }
  19989. return listByTags;
  19990. };
  19991. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19992. return this._getByTags(this.meshes, tagsQuery, forEach);
  19993. };
  19994. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19995. return this._getByTags(this.cameras, tagsQuery, forEach);
  19996. };
  19997. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19998. return this._getByTags(this.lights, tagsQuery, forEach);
  19999. };
  20000. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20001. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20002. };
  20003. /**
  20004. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20005. * This allowed control for front to back rendering or reversly depending of the special needs.
  20006. *
  20007. * @param renderingGroupId The rendering group id corresponding to its index
  20008. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20009. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20010. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20011. */
  20012. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20013. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20014. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20015. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20016. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20017. };
  20018. /**
  20019. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20020. *
  20021. * @param renderingGroupId The rendering group id corresponding to its index
  20022. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20023. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20024. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20025. */
  20026. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20027. if (depth === void 0) { depth = true; }
  20028. if (stencil === void 0) { stencil = true; }
  20029. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20030. };
  20031. /**
  20032. * Will flag all materials as dirty to trigger new shader compilation
  20033. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20034. */
  20035. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20036. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20037. var material = _a[_i];
  20038. if (predicate && !predicate(material)) {
  20039. continue;
  20040. }
  20041. material.markAsDirty(flag);
  20042. }
  20043. };
  20044. // Statics
  20045. Scene._FOGMODE_NONE = 0;
  20046. Scene._FOGMODE_EXP = 1;
  20047. Scene._FOGMODE_EXP2 = 2;
  20048. Scene._FOGMODE_LINEAR = 3;
  20049. Scene._uniqueIdCounter = 0;
  20050. Scene.MinDeltaTime = 1.0;
  20051. Scene.MaxDeltaTime = 1000.0;
  20052. /** The distance in pixel that you have to move to prevent some events */
  20053. Scene.DragMovementThreshold = 10; // in pixels
  20054. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20055. Scene.LongPressDelay = 500; // in milliseconds
  20056. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20057. Scene.DoubleClickDelay = 300; // in milliseconds
  20058. /** If you need to check double click without raising a single click at first click, enable this flag */
  20059. Scene.ExclusiveDoubleClickMode = false;
  20060. return Scene;
  20061. }());
  20062. BABYLON.Scene = Scene;
  20063. })(BABYLON || (BABYLON = {}));
  20064. //# sourceMappingURL=babylon.scene.js.map
  20065. var BABYLON;
  20066. (function (BABYLON) {
  20067. var Buffer = (function () {
  20068. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20069. if (engine instanceof BABYLON.Mesh) {
  20070. this._engine = engine.getScene().getEngine();
  20071. }
  20072. else {
  20073. this._engine = engine;
  20074. }
  20075. this._updatable = updatable;
  20076. this._data = data;
  20077. this._strideSize = stride;
  20078. if (!postponeInternalCreation) {
  20079. this.create();
  20080. }
  20081. this._instanced = instanced;
  20082. this._instanceDivisor = instanced ? 1 : 0;
  20083. }
  20084. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20085. // a lot of these parameters are ignored as they are overriden by the buffer
  20086. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20087. };
  20088. // Properties
  20089. Buffer.prototype.isUpdatable = function () {
  20090. return this._updatable;
  20091. };
  20092. Buffer.prototype.getData = function () {
  20093. return this._data;
  20094. };
  20095. Buffer.prototype.getBuffer = function () {
  20096. return this._buffer;
  20097. };
  20098. Buffer.prototype.getStrideSize = function () {
  20099. return this._strideSize;
  20100. };
  20101. Buffer.prototype.getIsInstanced = function () {
  20102. return this._instanced;
  20103. };
  20104. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20105. get: function () {
  20106. return this._instanceDivisor;
  20107. },
  20108. set: function (value) {
  20109. this._instanceDivisor = value;
  20110. if (value == 0) {
  20111. this._instanced = false;
  20112. }
  20113. else {
  20114. this._instanced = true;
  20115. }
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. // Methods
  20121. Buffer.prototype.create = function (data) {
  20122. if (!data && this._buffer) {
  20123. return; // nothing to do
  20124. }
  20125. data = data || this._data;
  20126. if (!this._buffer) {
  20127. if (this._updatable) {
  20128. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20129. this._data = data;
  20130. }
  20131. else {
  20132. this._buffer = this._engine.createVertexBuffer(data);
  20133. }
  20134. }
  20135. else if (this._updatable) {
  20136. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20137. this._data = data;
  20138. }
  20139. };
  20140. Buffer.prototype._rebuild = function () {
  20141. this._buffer = null;
  20142. this.create(this._data);
  20143. };
  20144. Buffer.prototype.update = function (data) {
  20145. this.create(data);
  20146. };
  20147. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20148. if (!this._buffer) {
  20149. return;
  20150. }
  20151. if (this._updatable) {
  20152. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20153. this._data = null;
  20154. }
  20155. };
  20156. Buffer.prototype.dispose = function () {
  20157. if (!this._buffer) {
  20158. return;
  20159. }
  20160. if (this._engine._releaseBuffer(this._buffer)) {
  20161. this._buffer = null;
  20162. }
  20163. };
  20164. return Buffer;
  20165. }());
  20166. BABYLON.Buffer = Buffer;
  20167. })(BABYLON || (BABYLON = {}));
  20168. //# sourceMappingURL=babylon.buffer.js.map
  20169. var BABYLON;
  20170. (function (BABYLON) {
  20171. var VertexBuffer = (function () {
  20172. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20173. if (!stride) {
  20174. // Deduce stride from kind
  20175. switch (kind) {
  20176. case VertexBuffer.PositionKind:
  20177. stride = 3;
  20178. break;
  20179. case VertexBuffer.NormalKind:
  20180. stride = 3;
  20181. break;
  20182. case VertexBuffer.UVKind:
  20183. case VertexBuffer.UV2Kind:
  20184. case VertexBuffer.UV3Kind:
  20185. case VertexBuffer.UV4Kind:
  20186. case VertexBuffer.UV5Kind:
  20187. case VertexBuffer.UV6Kind:
  20188. stride = 2;
  20189. break;
  20190. case VertexBuffer.TangentKind:
  20191. case VertexBuffer.ColorKind:
  20192. stride = 4;
  20193. break;
  20194. case VertexBuffer.MatricesIndicesKind:
  20195. case VertexBuffer.MatricesIndicesExtraKind:
  20196. stride = 4;
  20197. break;
  20198. case VertexBuffer.MatricesWeightsKind:
  20199. case VertexBuffer.MatricesWeightsExtraKind:
  20200. stride = 4;
  20201. break;
  20202. }
  20203. }
  20204. if (data instanceof BABYLON.Buffer) {
  20205. if (!stride) {
  20206. stride = data.getStrideSize();
  20207. }
  20208. this._buffer = data;
  20209. this._ownsBuffer = false;
  20210. }
  20211. else {
  20212. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20213. this._ownsBuffer = true;
  20214. }
  20215. this._stride = stride;
  20216. this._offset = offset ? offset : 0;
  20217. this._size = size ? size : stride;
  20218. this._kind = kind;
  20219. }
  20220. VertexBuffer.prototype._rebuild = function () {
  20221. if (!this._buffer) {
  20222. return;
  20223. }
  20224. this._buffer._rebuild();
  20225. };
  20226. /**
  20227. * Returns the kind of the VertexBuffer (string).
  20228. */
  20229. VertexBuffer.prototype.getKind = function () {
  20230. return this._kind;
  20231. };
  20232. // Properties
  20233. /**
  20234. * Boolean : is the VertexBuffer updatable ?
  20235. */
  20236. VertexBuffer.prototype.isUpdatable = function () {
  20237. return this._buffer.isUpdatable();
  20238. };
  20239. /**
  20240. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20241. */
  20242. VertexBuffer.prototype.getData = function () {
  20243. return this._buffer.getData();
  20244. };
  20245. /**
  20246. * Returns the WebGLBuffer associated to the VertexBuffer.
  20247. */
  20248. VertexBuffer.prototype.getBuffer = function () {
  20249. return this._buffer.getBuffer();
  20250. };
  20251. /**
  20252. * Returns the stride of the VertexBuffer (integer).
  20253. */
  20254. VertexBuffer.prototype.getStrideSize = function () {
  20255. return this._stride;
  20256. };
  20257. /**
  20258. * Returns the offset (integer).
  20259. */
  20260. VertexBuffer.prototype.getOffset = function () {
  20261. return this._offset;
  20262. };
  20263. /**
  20264. * Returns the VertexBuffer total size (integer).
  20265. */
  20266. VertexBuffer.prototype.getSize = function () {
  20267. return this._size;
  20268. };
  20269. /**
  20270. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20271. */
  20272. VertexBuffer.prototype.getIsInstanced = function () {
  20273. return this._buffer.getIsInstanced();
  20274. };
  20275. /**
  20276. * Returns the instancing divisor, zero for non-instanced (integer).
  20277. */
  20278. VertexBuffer.prototype.getInstanceDivisor = function () {
  20279. return this._buffer.instanceDivisor;
  20280. };
  20281. // Methods
  20282. /**
  20283. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20284. * Returns the created WebGLBuffer.
  20285. */
  20286. VertexBuffer.prototype.create = function (data) {
  20287. return this._buffer.create(data);
  20288. };
  20289. /**
  20290. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20291. * Returns the updated WebGLBuffer.
  20292. */
  20293. VertexBuffer.prototype.update = function (data) {
  20294. return this._buffer.update(data);
  20295. };
  20296. /**
  20297. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20298. * Returns the directly updated WebGLBuffer.
  20299. */
  20300. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20301. return this._buffer.updateDirectly(data, offset);
  20302. };
  20303. /**
  20304. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20305. */
  20306. VertexBuffer.prototype.dispose = function () {
  20307. if (this._ownsBuffer) {
  20308. this._buffer.dispose();
  20309. }
  20310. };
  20311. Object.defineProperty(VertexBuffer, "PositionKind", {
  20312. get: function () {
  20313. return VertexBuffer._PositionKind;
  20314. },
  20315. enumerable: true,
  20316. configurable: true
  20317. });
  20318. Object.defineProperty(VertexBuffer, "NormalKind", {
  20319. get: function () {
  20320. return VertexBuffer._NormalKind;
  20321. },
  20322. enumerable: true,
  20323. configurable: true
  20324. });
  20325. Object.defineProperty(VertexBuffer, "TangentKind", {
  20326. get: function () {
  20327. return VertexBuffer._TangentKind;
  20328. },
  20329. enumerable: true,
  20330. configurable: true
  20331. });
  20332. Object.defineProperty(VertexBuffer, "UVKind", {
  20333. get: function () {
  20334. return VertexBuffer._UVKind;
  20335. },
  20336. enumerable: true,
  20337. configurable: true
  20338. });
  20339. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20340. get: function () {
  20341. return VertexBuffer._UV2Kind;
  20342. },
  20343. enumerable: true,
  20344. configurable: true
  20345. });
  20346. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20347. get: function () {
  20348. return VertexBuffer._UV3Kind;
  20349. },
  20350. enumerable: true,
  20351. configurable: true
  20352. });
  20353. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20354. get: function () {
  20355. return VertexBuffer._UV4Kind;
  20356. },
  20357. enumerable: true,
  20358. configurable: true
  20359. });
  20360. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20361. get: function () {
  20362. return VertexBuffer._UV5Kind;
  20363. },
  20364. enumerable: true,
  20365. configurable: true
  20366. });
  20367. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20368. get: function () {
  20369. return VertexBuffer._UV6Kind;
  20370. },
  20371. enumerable: true,
  20372. configurable: true
  20373. });
  20374. Object.defineProperty(VertexBuffer, "ColorKind", {
  20375. get: function () {
  20376. return VertexBuffer._ColorKind;
  20377. },
  20378. enumerable: true,
  20379. configurable: true
  20380. });
  20381. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20382. get: function () {
  20383. return VertexBuffer._MatricesIndicesKind;
  20384. },
  20385. enumerable: true,
  20386. configurable: true
  20387. });
  20388. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20389. get: function () {
  20390. return VertexBuffer._MatricesWeightsKind;
  20391. },
  20392. enumerable: true,
  20393. configurable: true
  20394. });
  20395. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20396. get: function () {
  20397. return VertexBuffer._MatricesIndicesExtraKind;
  20398. },
  20399. enumerable: true,
  20400. configurable: true
  20401. });
  20402. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20403. get: function () {
  20404. return VertexBuffer._MatricesWeightsExtraKind;
  20405. },
  20406. enumerable: true,
  20407. configurable: true
  20408. });
  20409. // Enums
  20410. VertexBuffer._PositionKind = "position";
  20411. VertexBuffer._NormalKind = "normal";
  20412. VertexBuffer._TangentKind = "tangent";
  20413. VertexBuffer._UVKind = "uv";
  20414. VertexBuffer._UV2Kind = "uv2";
  20415. VertexBuffer._UV3Kind = "uv3";
  20416. VertexBuffer._UV4Kind = "uv4";
  20417. VertexBuffer._UV5Kind = "uv5";
  20418. VertexBuffer._UV6Kind = "uv6";
  20419. VertexBuffer._ColorKind = "color";
  20420. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20421. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20422. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20423. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20424. return VertexBuffer;
  20425. }());
  20426. BABYLON.VertexBuffer = VertexBuffer;
  20427. })(BABYLON || (BABYLON = {}));
  20428. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20429. var BABYLON;
  20430. (function (BABYLON) {
  20431. var InternalTexture = (function () {
  20432. function InternalTexture(engine, dataSource) {
  20433. this.onLoadedObservable = new BABYLON.Observable();
  20434. // Private
  20435. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20436. this._references = 1;
  20437. this._engine = engine;
  20438. this._dataSource = dataSource;
  20439. this._webGLTexture = engine._createTexture();
  20440. }
  20441. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20442. get: function () {
  20443. return this._dataSource;
  20444. },
  20445. enumerable: true,
  20446. configurable: true
  20447. });
  20448. InternalTexture.prototype.incrementReferences = function () {
  20449. this._references++;
  20450. };
  20451. InternalTexture.prototype.updateSize = function (width, height) {
  20452. this.width = width;
  20453. this.height = height;
  20454. this._size = width * height;
  20455. this.baseWidth = width;
  20456. this.baseHeight = height;
  20457. };
  20458. InternalTexture.prototype._rebuild = function () {
  20459. var _this = this;
  20460. var proxy;
  20461. this.isReady = false;
  20462. this._cachedCoordinatesMode = null;
  20463. this._cachedWrapU = null;
  20464. this._cachedWrapV = null;
  20465. this._cachedAnisotropicFilteringLevel = null;
  20466. switch (this._dataSource) {
  20467. case InternalTexture.DATASOURCE_TEMP:
  20468. return;
  20469. case InternalTexture.DATASOURCE_URL:
  20470. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20471. _this.isReady = true;
  20472. }, null, this._buffer, null, this.format);
  20473. proxy._swapAndDie(this);
  20474. return;
  20475. case InternalTexture.DATASOURCE_RAW:
  20476. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20477. proxy._swapAndDie(this);
  20478. this.isReady = true;
  20479. return;
  20480. case InternalTexture.DATASOURCE_DYNAMIC:
  20481. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20482. proxy._swapAndDie(this);
  20483. // The engine will make sure to update content so no need to flag it as isReady = true
  20484. return;
  20485. case InternalTexture.DATASOURCE_RENDERTARGET:
  20486. var options = new BABYLON.RenderTargetCreationOptions();
  20487. options.generateDepthBuffer = this._generateDepthBuffer;
  20488. options.generateMipMaps = this.generateMipMaps;
  20489. options.generateStencilBuffer = this._generateStencilBuffer;
  20490. options.samplingMode = this.samplingMode;
  20491. options.type = this.type;
  20492. if (this.isCube) {
  20493. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20494. }
  20495. else {
  20496. var size = {
  20497. width: this.width,
  20498. height: this.height
  20499. };
  20500. proxy = this._engine.createRenderTargetTexture(size, options);
  20501. }
  20502. proxy._swapAndDie(this);
  20503. this.isReady = true;
  20504. return;
  20505. case InternalTexture.DATASOURCE_CUBE:
  20506. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20507. _this.isReady = true;
  20508. }, null, this.format, this._extension);
  20509. proxy._swapAndDie(this);
  20510. return;
  20511. case InternalTexture.DATASOURCE_CUBERAW:
  20512. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20513. proxy._swapAndDie(this);
  20514. this.isReady = true;
  20515. return;
  20516. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20517. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20518. proxy._swapAndDie(_this);
  20519. _this.isReady = true;
  20520. }, null, this.format, this._extension);
  20521. return;
  20522. }
  20523. };
  20524. InternalTexture.prototype._swapAndDie = function (target) {
  20525. target._webGLTexture = this._webGLTexture;
  20526. if (this._framebuffer) {
  20527. target._framebuffer = this._framebuffer;
  20528. }
  20529. if (this._depthStencilBuffer) {
  20530. target._depthStencilBuffer = this._depthStencilBuffer;
  20531. }
  20532. if (this._lodTextureHigh) {
  20533. if (target._lodTextureHigh) {
  20534. target._lodTextureHigh.dispose();
  20535. }
  20536. target._lodTextureHigh = this._lodTextureHigh;
  20537. }
  20538. if (this._lodTextureMid) {
  20539. if (target._lodTextureMid) {
  20540. target._lodTextureMid.dispose();
  20541. }
  20542. target._lodTextureMid = this._lodTextureMid;
  20543. }
  20544. if (this._lodTextureLow) {
  20545. if (target._lodTextureLow) {
  20546. target._lodTextureLow.dispose();
  20547. }
  20548. target._lodTextureLow = this._lodTextureLow;
  20549. }
  20550. var cache = this._engine.getLoadedTexturesCache();
  20551. var index = cache.indexOf(this);
  20552. if (index !== -1) {
  20553. cache.splice(index, 1);
  20554. }
  20555. };
  20556. InternalTexture.prototype.dispose = function () {
  20557. if (!this._webGLTexture) {
  20558. return;
  20559. }
  20560. this._references--;
  20561. if (this._references === 0) {
  20562. this._engine._releaseTexture(this);
  20563. this._webGLTexture = null;
  20564. }
  20565. };
  20566. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20567. InternalTexture.DATASOURCE_URL = 1;
  20568. InternalTexture.DATASOURCE_TEMP = 2;
  20569. InternalTexture.DATASOURCE_RAW = 3;
  20570. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20571. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20572. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20573. InternalTexture.DATASOURCE_CUBE = 7;
  20574. InternalTexture.DATASOURCE_CUBERAW = 8;
  20575. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20576. return InternalTexture;
  20577. }());
  20578. BABYLON.InternalTexture = InternalTexture;
  20579. })(BABYLON || (BABYLON = {}));
  20580. //# sourceMappingURL=babylon.internalTexture.js.map
  20581. var BABYLON;
  20582. (function (BABYLON) {
  20583. var BaseTexture = (function () {
  20584. function BaseTexture(scene) {
  20585. this._hasAlpha = false;
  20586. this.getAlphaFromRGB = false;
  20587. this.level = 1;
  20588. this.coordinatesIndex = 0;
  20589. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20590. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20591. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20592. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20593. this.isCube = false;
  20594. this.gammaSpace = true;
  20595. this.invertZ = false;
  20596. this.lodLevelInAlpha = false;
  20597. this.lodGenerationOffset = 0.0;
  20598. this.lodGenerationScale = 0.8;
  20599. this.isRenderTarget = false;
  20600. this.animations = new Array();
  20601. /**
  20602. * An event triggered when the texture is disposed.
  20603. * @type {BABYLON.Observable}
  20604. */
  20605. this.onDisposeObservable = new BABYLON.Observable();
  20606. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20607. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20608. this._scene.textures.push(this);
  20609. this._uid = null;
  20610. }
  20611. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20612. get: function () {
  20613. return this._hasAlpha;
  20614. },
  20615. set: function (value) {
  20616. if (this._hasAlpha === value) {
  20617. return;
  20618. }
  20619. this._hasAlpha = value;
  20620. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20621. },
  20622. enumerable: true,
  20623. configurable: true
  20624. });
  20625. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20626. get: function () {
  20627. return this._coordinatesMode;
  20628. },
  20629. set: function (value) {
  20630. if (this._coordinatesMode === value) {
  20631. return;
  20632. }
  20633. this._coordinatesMode = value;
  20634. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20635. },
  20636. enumerable: true,
  20637. configurable: true
  20638. });
  20639. Object.defineProperty(BaseTexture.prototype, "uid", {
  20640. get: function () {
  20641. if (!this._uid) {
  20642. this._uid = BABYLON.Tools.RandomId();
  20643. }
  20644. return this._uid;
  20645. },
  20646. enumerable: true,
  20647. configurable: true
  20648. });
  20649. BaseTexture.prototype.toString = function () {
  20650. return this.name;
  20651. };
  20652. BaseTexture.prototype.getClassName = function () {
  20653. return "BaseTexture";
  20654. };
  20655. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20656. set: function (callback) {
  20657. if (this._onDisposeObserver) {
  20658. this.onDisposeObservable.remove(this._onDisposeObserver);
  20659. }
  20660. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20661. },
  20662. enumerable: true,
  20663. configurable: true
  20664. });
  20665. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20666. get: function () {
  20667. return true;
  20668. },
  20669. enumerable: true,
  20670. configurable: true
  20671. });
  20672. BaseTexture.prototype.getScene = function () {
  20673. return this._scene;
  20674. };
  20675. BaseTexture.prototype.getTextureMatrix = function () {
  20676. return null;
  20677. };
  20678. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20679. return null;
  20680. };
  20681. BaseTexture.prototype.getInternalTexture = function () {
  20682. return this._texture;
  20683. };
  20684. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20685. return !this.isBlocking || this.isReady();
  20686. };
  20687. BaseTexture.prototype.isReady = function () {
  20688. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20689. this.delayLoad();
  20690. return false;
  20691. }
  20692. if (this._texture) {
  20693. return this._texture.isReady;
  20694. }
  20695. return false;
  20696. };
  20697. BaseTexture.prototype.getSize = function () {
  20698. if (this._texture.width) {
  20699. return new BABYLON.Size(this._texture.width, this._texture.height);
  20700. }
  20701. if (this._texture._size) {
  20702. return new BABYLON.Size(this._texture._size, this._texture._size);
  20703. }
  20704. return BABYLON.Size.Zero();
  20705. };
  20706. BaseTexture.prototype.getBaseSize = function () {
  20707. if (!this.isReady() || !this._texture)
  20708. return BABYLON.Size.Zero();
  20709. if (this._texture._size) {
  20710. return new BABYLON.Size(this._texture._size, this._texture._size);
  20711. }
  20712. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20713. };
  20714. BaseTexture.prototype.scale = function (ratio) {
  20715. };
  20716. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20717. get: function () {
  20718. return false;
  20719. },
  20720. enumerable: true,
  20721. configurable: true
  20722. });
  20723. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20724. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20725. for (var index = 0; index < texturesCache.length; index++) {
  20726. var texturesCacheEntry = texturesCache[index];
  20727. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20728. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20729. texturesCacheEntry.incrementReferences();
  20730. return texturesCacheEntry;
  20731. }
  20732. }
  20733. }
  20734. return null;
  20735. };
  20736. BaseTexture.prototype._rebuild = function () {
  20737. };
  20738. BaseTexture.prototype.delayLoad = function () {
  20739. };
  20740. BaseTexture.prototype.clone = function () {
  20741. return null;
  20742. };
  20743. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20744. get: function () {
  20745. if (!this._texture) {
  20746. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20747. }
  20748. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20749. },
  20750. enumerable: true,
  20751. configurable: true
  20752. });
  20753. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20754. get: function () {
  20755. if (!this._texture) {
  20756. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20757. }
  20758. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20759. },
  20760. enumerable: true,
  20761. configurable: true
  20762. });
  20763. BaseTexture.prototype.readPixels = function (faceIndex) {
  20764. if (faceIndex === void 0) { faceIndex = 0; }
  20765. if (!this._texture) {
  20766. return null;
  20767. }
  20768. var size = this.getSize();
  20769. var engine = this.getScene().getEngine();
  20770. if (this._texture.isCube) {
  20771. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20772. }
  20773. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20774. };
  20775. BaseTexture.prototype.releaseInternalTexture = function () {
  20776. if (this._texture) {
  20777. this._texture.dispose();
  20778. this._texture = null;
  20779. }
  20780. };
  20781. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20782. get: function () {
  20783. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20784. return null;
  20785. }
  20786. if (!this._texture._sphericalPolynomial) {
  20787. this._texture._sphericalPolynomial =
  20788. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20789. }
  20790. return this._texture._sphericalPolynomial;
  20791. },
  20792. set: function (value) {
  20793. if (this._texture) {
  20794. this._texture._sphericalPolynomial = value;
  20795. }
  20796. },
  20797. enumerable: true,
  20798. configurable: true
  20799. });
  20800. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20801. get: function () {
  20802. if (this._texture) {
  20803. return this._texture._lodTextureHigh;
  20804. }
  20805. return null;
  20806. },
  20807. enumerable: true,
  20808. configurable: true
  20809. });
  20810. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20811. get: function () {
  20812. if (this._texture) {
  20813. return this._texture._lodTextureMid;
  20814. }
  20815. return null;
  20816. },
  20817. enumerable: true,
  20818. configurable: true
  20819. });
  20820. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20821. get: function () {
  20822. if (this._texture) {
  20823. return this._texture._lodTextureLow;
  20824. }
  20825. return null;
  20826. },
  20827. enumerable: true,
  20828. configurable: true
  20829. });
  20830. BaseTexture.prototype.dispose = function () {
  20831. // Animations
  20832. this.getScene().stopAnimation(this);
  20833. // Remove from scene
  20834. this._scene._removePendingData(this);
  20835. var index = this._scene.textures.indexOf(this);
  20836. if (index >= 0) {
  20837. this._scene.textures.splice(index, 1);
  20838. }
  20839. if (this._texture === undefined) {
  20840. return;
  20841. }
  20842. // Release
  20843. this.releaseInternalTexture();
  20844. // Callback
  20845. this.onDisposeObservable.notifyObservers(this);
  20846. this.onDisposeObservable.clear();
  20847. };
  20848. BaseTexture.prototype.serialize = function () {
  20849. if (!this.name) {
  20850. return null;
  20851. }
  20852. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20853. // Animations
  20854. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20855. return serializationObject;
  20856. };
  20857. BaseTexture.WhenAllReady = function (textures, callback) {
  20858. var numRemaining = textures.length;
  20859. if (numRemaining === 0) {
  20860. callback();
  20861. return;
  20862. }
  20863. var _loop_1 = function () {
  20864. texture = textures[i];
  20865. if (texture.isReady()) {
  20866. if (--numRemaining === 0) {
  20867. callback();
  20868. }
  20869. }
  20870. else {
  20871. onLoadObservable = texture.onLoadObservable;
  20872. var onLoadCallback_1 = function () {
  20873. onLoadObservable.removeCallback(onLoadCallback_1);
  20874. if (--numRemaining === 0) {
  20875. callback();
  20876. }
  20877. };
  20878. onLoadObservable.add(onLoadCallback_1);
  20879. }
  20880. };
  20881. var texture, onLoadObservable;
  20882. for (var i = 0; i < textures.length; i++) {
  20883. _loop_1();
  20884. }
  20885. };
  20886. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20887. __decorate([
  20888. BABYLON.serialize()
  20889. ], BaseTexture.prototype, "name", void 0);
  20890. __decorate([
  20891. BABYLON.serialize("hasAlpha")
  20892. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20893. __decorate([
  20894. BABYLON.serialize()
  20895. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20896. __decorate([
  20897. BABYLON.serialize()
  20898. ], BaseTexture.prototype, "level", void 0);
  20899. __decorate([
  20900. BABYLON.serialize()
  20901. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20902. __decorate([
  20903. BABYLON.serialize("coordinatesMode")
  20904. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20905. __decorate([
  20906. BABYLON.serialize()
  20907. ], BaseTexture.prototype, "wrapU", void 0);
  20908. __decorate([
  20909. BABYLON.serialize()
  20910. ], BaseTexture.prototype, "wrapV", void 0);
  20911. __decorate([
  20912. BABYLON.serialize()
  20913. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20914. __decorate([
  20915. BABYLON.serialize()
  20916. ], BaseTexture.prototype, "isCube", void 0);
  20917. __decorate([
  20918. BABYLON.serialize()
  20919. ], BaseTexture.prototype, "gammaSpace", void 0);
  20920. __decorate([
  20921. BABYLON.serialize()
  20922. ], BaseTexture.prototype, "invertZ", void 0);
  20923. __decorate([
  20924. BABYLON.serialize()
  20925. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20926. __decorate([
  20927. BABYLON.serialize()
  20928. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20929. __decorate([
  20930. BABYLON.serialize()
  20931. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20932. __decorate([
  20933. BABYLON.serialize()
  20934. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20935. return BaseTexture;
  20936. }());
  20937. BABYLON.BaseTexture = BaseTexture;
  20938. })(BABYLON || (BABYLON = {}));
  20939. //# sourceMappingURL=babylon.baseTexture.js.map
  20940. var BABYLON;
  20941. (function (BABYLON) {
  20942. var Texture = (function (_super) {
  20943. __extends(Texture, _super);
  20944. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20945. if (noMipmap === void 0) { noMipmap = false; }
  20946. if (invertY === void 0) { invertY = true; }
  20947. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20948. if (onLoad === void 0) { onLoad = null; }
  20949. if (onError === void 0) { onError = null; }
  20950. if (buffer === void 0) { buffer = null; }
  20951. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20952. var _this = _super.call(this, scene) || this;
  20953. _this.uOffset = 0;
  20954. _this.vOffset = 0;
  20955. _this.uScale = 1.0;
  20956. _this.vScale = 1.0;
  20957. _this.uAng = 0;
  20958. _this.vAng = 0;
  20959. _this.wAng = 0;
  20960. _this._isBlocking = true;
  20961. _this.name = url;
  20962. _this.url = url;
  20963. _this._noMipmap = noMipmap;
  20964. _this._invertY = invertY;
  20965. _this._samplingMode = samplingMode;
  20966. _this._buffer = buffer;
  20967. _this._deleteBuffer = deleteBuffer;
  20968. _this._format = format;
  20969. scene = _this.getScene();
  20970. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  20971. var load = function () {
  20972. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20973. _this.onLoadObservable.notifyObservers(_this);
  20974. }
  20975. if (onLoad) {
  20976. onLoad();
  20977. }
  20978. if (!_this.isBlocking) {
  20979. scene.resetCachedMaterial();
  20980. }
  20981. };
  20982. if (!_this.url) {
  20983. _this._delayedOnLoad = load;
  20984. _this._delayedOnError = onError;
  20985. return _this;
  20986. }
  20987. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  20988. if (!_this._texture) {
  20989. if (!scene.useDelayedTextureLoading) {
  20990. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20991. if (deleteBuffer) {
  20992. delete _this._buffer;
  20993. }
  20994. }
  20995. else {
  20996. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20997. _this._delayedOnLoad = load;
  20998. _this._delayedOnError = onError;
  20999. }
  21000. }
  21001. else {
  21002. if (_this._texture.isReady) {
  21003. BABYLON.Tools.SetImmediate(function () { return load(); });
  21004. }
  21005. else {
  21006. _this._texture.onLoadedObservable.add(load);
  21007. }
  21008. }
  21009. return _this;
  21010. }
  21011. Object.defineProperty(Texture.prototype, "noMipmap", {
  21012. get: function () {
  21013. return this._noMipmap;
  21014. },
  21015. enumerable: true,
  21016. configurable: true
  21017. });
  21018. Object.defineProperty(Texture.prototype, "isBlocking", {
  21019. get: function () {
  21020. return this._isBlocking;
  21021. },
  21022. set: function (value) {
  21023. this._isBlocking = value;
  21024. },
  21025. enumerable: true,
  21026. configurable: true
  21027. });
  21028. Object.defineProperty(Texture.prototype, "samplingMode", {
  21029. get: function () {
  21030. return this._samplingMode;
  21031. },
  21032. enumerable: true,
  21033. configurable: true
  21034. });
  21035. Texture.prototype.updateURL = function (url) {
  21036. this.url = url;
  21037. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21038. this.delayLoad();
  21039. };
  21040. Texture.prototype.delayLoad = function () {
  21041. var _this = this;
  21042. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21043. return;
  21044. }
  21045. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21046. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21047. if (!this._texture) {
  21048. 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);
  21049. if (this._deleteBuffer) {
  21050. delete this._buffer;
  21051. }
  21052. }
  21053. else {
  21054. if (this._texture.isReady) {
  21055. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  21056. }
  21057. else {
  21058. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21059. }
  21060. }
  21061. };
  21062. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21063. if (!this._texture) {
  21064. return;
  21065. }
  21066. this._samplingMode = samplingMode;
  21067. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21068. };
  21069. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21070. x *= this.uScale;
  21071. y *= this.vScale;
  21072. x -= 0.5 * this.uScale;
  21073. y -= 0.5 * this.vScale;
  21074. z -= 0.5;
  21075. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21076. t.x += 0.5 * this.uScale + this.uOffset;
  21077. t.y += 0.5 * this.vScale + this.vOffset;
  21078. t.z += 0.5;
  21079. };
  21080. Texture.prototype.getTextureMatrix = function () {
  21081. var _this = this;
  21082. if (this.uOffset === this._cachedUOffset &&
  21083. this.vOffset === this._cachedVOffset &&
  21084. this.uScale === this._cachedUScale &&
  21085. this.vScale === this._cachedVScale &&
  21086. this.uAng === this._cachedUAng &&
  21087. this.vAng === this._cachedVAng &&
  21088. this.wAng === this._cachedWAng) {
  21089. return this._cachedTextureMatrix;
  21090. }
  21091. this._cachedUOffset = this.uOffset;
  21092. this._cachedVOffset = this.vOffset;
  21093. this._cachedUScale = this.uScale;
  21094. this._cachedVScale = this.vScale;
  21095. this._cachedUAng = this.uAng;
  21096. this._cachedVAng = this.vAng;
  21097. this._cachedWAng = this.wAng;
  21098. if (!this._cachedTextureMatrix) {
  21099. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21100. this._rowGenerationMatrix = new BABYLON.Matrix();
  21101. this._t0 = BABYLON.Vector3.Zero();
  21102. this._t1 = BABYLON.Vector3.Zero();
  21103. this._t2 = BABYLON.Vector3.Zero();
  21104. }
  21105. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21106. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21107. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21108. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21109. this._t1.subtractInPlace(this._t0);
  21110. this._t2.subtractInPlace(this._t0);
  21111. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21112. this._cachedTextureMatrix.m[0] = this._t1.x;
  21113. this._cachedTextureMatrix.m[1] = this._t1.y;
  21114. this._cachedTextureMatrix.m[2] = this._t1.z;
  21115. this._cachedTextureMatrix.m[4] = this._t2.x;
  21116. this._cachedTextureMatrix.m[5] = this._t2.y;
  21117. this._cachedTextureMatrix.m[6] = this._t2.z;
  21118. this._cachedTextureMatrix.m[8] = this._t0.x;
  21119. this._cachedTextureMatrix.m[9] = this._t0.y;
  21120. this._cachedTextureMatrix.m[10] = this._t0.z;
  21121. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21122. return mat.hasTexture(_this);
  21123. });
  21124. return this._cachedTextureMatrix;
  21125. };
  21126. Texture.prototype.getReflectionTextureMatrix = function () {
  21127. var _this = this;
  21128. var scene = this.getScene();
  21129. if (this.uOffset === this._cachedUOffset &&
  21130. this.vOffset === this._cachedVOffset &&
  21131. this.uScale === this._cachedUScale &&
  21132. this.vScale === this._cachedVScale &&
  21133. this.coordinatesMode === this._cachedCoordinatesMode) {
  21134. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21135. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21136. return this._cachedTextureMatrix;
  21137. }
  21138. }
  21139. else {
  21140. return this._cachedTextureMatrix;
  21141. }
  21142. }
  21143. if (!this._cachedTextureMatrix) {
  21144. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21145. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21146. }
  21147. this._cachedUOffset = this.uOffset;
  21148. this._cachedVOffset = this.vOffset;
  21149. this._cachedUScale = this.uScale;
  21150. this._cachedVScale = this.vScale;
  21151. this._cachedCoordinatesMode = this.coordinatesMode;
  21152. switch (this.coordinatesMode) {
  21153. case Texture.PLANAR_MODE:
  21154. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21155. this._cachedTextureMatrix[0] = this.uScale;
  21156. this._cachedTextureMatrix[5] = this.vScale;
  21157. this._cachedTextureMatrix[12] = this.uOffset;
  21158. this._cachedTextureMatrix[13] = this.vOffset;
  21159. break;
  21160. case Texture.PROJECTION_MODE:
  21161. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21162. this._projectionModeMatrix.m[0] = 0.5;
  21163. this._projectionModeMatrix.m[5] = -0.5;
  21164. this._projectionModeMatrix.m[10] = 0.0;
  21165. this._projectionModeMatrix.m[12] = 0.5;
  21166. this._projectionModeMatrix.m[13] = 0.5;
  21167. this._projectionModeMatrix.m[14] = 1.0;
  21168. this._projectionModeMatrix.m[15] = 1.0;
  21169. var projectionMatrix = scene.getProjectionMatrix();
  21170. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21171. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21172. break;
  21173. default:
  21174. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21175. break;
  21176. }
  21177. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21178. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21179. });
  21180. return this._cachedTextureMatrix;
  21181. };
  21182. Texture.prototype.clone = function () {
  21183. var _this = this;
  21184. return BABYLON.SerializationHelper.Clone(function () {
  21185. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21186. }, this);
  21187. };
  21188. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21189. get: function () {
  21190. if (!this._onLoadObservable) {
  21191. this._onLoadObservable = new BABYLON.Observable();
  21192. }
  21193. return this._onLoadObservable;
  21194. },
  21195. enumerable: true,
  21196. configurable: true
  21197. });
  21198. Texture.prototype.serialize = function () {
  21199. var serializationObject = _super.prototype.serialize.call(this);
  21200. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21201. serializationObject.base64String = this._buffer;
  21202. serializationObject.name = serializationObject.name.replace("data:", "");
  21203. }
  21204. return serializationObject;
  21205. };
  21206. Texture.prototype.getClassName = function () {
  21207. return "Texture";
  21208. };
  21209. Texture.prototype.dispose = function () {
  21210. _super.prototype.dispose.call(this);
  21211. if (this.onLoadObservable) {
  21212. this.onLoadObservable.clear();
  21213. this._onLoadObservable = null;
  21214. }
  21215. this._delayedOnLoad = null;
  21216. this._delayedOnError = null;
  21217. };
  21218. // Statics
  21219. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21220. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21221. if (onLoad === void 0) { onLoad = null; }
  21222. if (onError === void 0) { onError = null; }
  21223. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21224. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21225. };
  21226. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21227. if (parsedTexture.customType) {
  21228. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21229. // Update Sampling Mode
  21230. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21231. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21232. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21233. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21234. }
  21235. }
  21236. return parsedCustomTexture;
  21237. }
  21238. if (parsedTexture.isCube) {
  21239. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21240. }
  21241. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21242. return null;
  21243. }
  21244. var texture = BABYLON.SerializationHelper.Parse(function () {
  21245. if (parsedTexture.mirrorPlane) {
  21246. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21247. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21248. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21249. return mirrorTexture;
  21250. }
  21251. else if (parsedTexture.isRenderTarget) {
  21252. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21253. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21254. return renderTargetTexture;
  21255. }
  21256. else {
  21257. var texture;
  21258. if (parsedTexture.base64String) {
  21259. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21260. }
  21261. else {
  21262. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21263. }
  21264. return texture;
  21265. }
  21266. }, parsedTexture, scene);
  21267. // Update Sampling Mode
  21268. if (parsedTexture.samplingMode) {
  21269. var sampling = parsedTexture.samplingMode;
  21270. if (texture._samplingMode !== sampling) {
  21271. texture.updateSamplingMode(sampling);
  21272. }
  21273. }
  21274. // Animations
  21275. if (parsedTexture.animations) {
  21276. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21277. var parsedAnimation = parsedTexture.animations[animationIndex];
  21278. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21279. }
  21280. }
  21281. return texture;
  21282. };
  21283. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21284. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21285. if (noMipmap === void 0) { noMipmap = false; }
  21286. if (invertY === void 0) { invertY = true; }
  21287. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21288. if (onLoad === void 0) { onLoad = null; }
  21289. if (onError === void 0) { onError = null; }
  21290. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21291. if (name.substr(0, 5) !== "data:") {
  21292. name = "data:" + name;
  21293. }
  21294. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21295. };
  21296. // Constants
  21297. Texture.NEAREST_SAMPLINGMODE = 1;
  21298. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21299. Texture.BILINEAR_SAMPLINGMODE = 2;
  21300. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21301. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21302. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21303. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21304. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21305. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21306. Texture.NEAREST_LINEAR = 7;
  21307. Texture.NEAREST_NEAREST = 8;
  21308. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21309. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21310. Texture.LINEAR_LINEAR = 11;
  21311. Texture.LINEAR_NEAREST = 12;
  21312. Texture.EXPLICIT_MODE = 0;
  21313. Texture.SPHERICAL_MODE = 1;
  21314. Texture.PLANAR_MODE = 2;
  21315. Texture.CUBIC_MODE = 3;
  21316. Texture.PROJECTION_MODE = 4;
  21317. Texture.SKYBOX_MODE = 5;
  21318. Texture.INVCUBIC_MODE = 6;
  21319. Texture.EQUIRECTANGULAR_MODE = 7;
  21320. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21321. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21322. Texture.CLAMP_ADDRESSMODE = 0;
  21323. Texture.WRAP_ADDRESSMODE = 1;
  21324. Texture.MIRROR_ADDRESSMODE = 2;
  21325. __decorate([
  21326. BABYLON.serialize()
  21327. ], Texture.prototype, "url", void 0);
  21328. __decorate([
  21329. BABYLON.serialize()
  21330. ], Texture.prototype, "uOffset", void 0);
  21331. __decorate([
  21332. BABYLON.serialize()
  21333. ], Texture.prototype, "vOffset", void 0);
  21334. __decorate([
  21335. BABYLON.serialize()
  21336. ], Texture.prototype, "uScale", void 0);
  21337. __decorate([
  21338. BABYLON.serialize()
  21339. ], Texture.prototype, "vScale", void 0);
  21340. __decorate([
  21341. BABYLON.serialize()
  21342. ], Texture.prototype, "uAng", void 0);
  21343. __decorate([
  21344. BABYLON.serialize()
  21345. ], Texture.prototype, "vAng", void 0);
  21346. __decorate([
  21347. BABYLON.serialize()
  21348. ], Texture.prototype, "wAng", void 0);
  21349. __decorate([
  21350. BABYLON.serialize()
  21351. ], Texture.prototype, "isBlocking", null);
  21352. return Texture;
  21353. }(BABYLON.BaseTexture));
  21354. BABYLON.Texture = Texture;
  21355. })(BABYLON || (BABYLON = {}));
  21356. //# sourceMappingURL=babylon.texture.js.map
  21357. var BABYLON;
  21358. (function (BABYLON) {
  21359. var _InstancesBatch = (function () {
  21360. function _InstancesBatch() {
  21361. this.mustReturn = false;
  21362. this.visibleInstances = new Array();
  21363. this.renderSelf = new Array();
  21364. }
  21365. return _InstancesBatch;
  21366. }());
  21367. BABYLON._InstancesBatch = _InstancesBatch;
  21368. var Mesh = (function (_super) {
  21369. __extends(Mesh, _super);
  21370. /**
  21371. * @constructor
  21372. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21373. * @param {Scene} scene The scene to add this mesh to.
  21374. * @param {Node} parent The parent of this mesh, if it has one
  21375. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21376. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21377. * When false, achieved by calling a clone(), also passing False.
  21378. * This will make creation of children, recursive.
  21379. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21380. */
  21381. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21382. if (parent === void 0) { parent = null; }
  21383. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21384. var _this = _super.call(this, name, scene) || this;
  21385. // Events
  21386. /**
  21387. * An event triggered before rendering the mesh
  21388. * @type {BABYLON.Observable}
  21389. */
  21390. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21391. /**
  21392. * An event triggered after rendering the mesh
  21393. * @type {BABYLON.Observable}
  21394. */
  21395. _this.onAfterRenderObservable = new BABYLON.Observable();
  21396. /**
  21397. * An event triggered before drawing the mesh
  21398. * @type {BABYLON.Observable}
  21399. */
  21400. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21401. // Members
  21402. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21403. _this.instances = new Array();
  21404. _this._LODLevels = new Array();
  21405. _this._visibleInstances = {};
  21406. _this._renderIdForInstances = new Array();
  21407. _this._batchCache = new _InstancesBatch();
  21408. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21409. // Use by builder only to know what orientation were the mesh build in.
  21410. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  21411. _this.overrideMaterialSideOrientation = null;
  21412. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21413. // Will be used to save a source mesh reference, If any
  21414. _this._source = null;
  21415. if (source) {
  21416. // Source mesh
  21417. _this._source = source;
  21418. // Geometry
  21419. if (source._geometry) {
  21420. source._geometry.applyToMesh(_this);
  21421. }
  21422. // Deep copy
  21423. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21424. // Parent
  21425. _this.parent = source.parent;
  21426. // Pivot
  21427. _this.setPivotMatrix(source.getPivotMatrix());
  21428. _this.id = name + "." + source.id;
  21429. // Material
  21430. _this.material = source.material;
  21431. var index;
  21432. if (!doNotCloneChildren) {
  21433. // Children
  21434. for (index = 0; index < scene.meshes.length; index++) {
  21435. var mesh = scene.meshes[index];
  21436. if (mesh.parent === source) {
  21437. // doNotCloneChildren is always going to be False
  21438. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21439. }
  21440. }
  21441. }
  21442. // Physics clone
  21443. var physicsEngine = _this.getScene().getPhysicsEngine();
  21444. if (clonePhysicsImpostor && physicsEngine) {
  21445. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21446. if (impostor) {
  21447. _this.physicsImpostor = impostor.clone(_this);
  21448. }
  21449. }
  21450. // Particles
  21451. for (index = 0; index < scene.particleSystems.length; index++) {
  21452. var system = scene.particleSystems[index];
  21453. if (system.emitter === source) {
  21454. system.clone(system.name, _this);
  21455. }
  21456. }
  21457. _this.computeWorldMatrix(true);
  21458. }
  21459. // Parent
  21460. if (parent !== null) {
  21461. _this.parent = parent;
  21462. }
  21463. return _this;
  21464. }
  21465. Object.defineProperty(Mesh, "FRONTSIDE", {
  21466. /**
  21467. * Mesh side orientation : usually the external or front surface
  21468. */
  21469. get: function () {
  21470. return Mesh._FRONTSIDE;
  21471. },
  21472. enumerable: true,
  21473. configurable: true
  21474. });
  21475. Object.defineProperty(Mesh, "BACKSIDE", {
  21476. /**
  21477. * Mesh side orientation : usually the internal or back surface
  21478. */
  21479. get: function () {
  21480. return Mesh._BACKSIDE;
  21481. },
  21482. enumerable: true,
  21483. configurable: true
  21484. });
  21485. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21486. /**
  21487. * Mesh side orientation : both internal and external or front and back surfaces
  21488. */
  21489. get: function () {
  21490. return Mesh._DOUBLESIDE;
  21491. },
  21492. enumerable: true,
  21493. configurable: true
  21494. });
  21495. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21496. /**
  21497. * Mesh side orientation : by default, `FRONTSIDE`
  21498. */
  21499. get: function () {
  21500. return Mesh._DEFAULTSIDE;
  21501. },
  21502. enumerable: true,
  21503. configurable: true
  21504. });
  21505. Object.defineProperty(Mesh, "NO_CAP", {
  21506. /**
  21507. * Mesh cap setting : no cap
  21508. */
  21509. get: function () {
  21510. return Mesh._NO_CAP;
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. Object.defineProperty(Mesh, "CAP_START", {
  21516. /**
  21517. * Mesh cap setting : one cap at the beginning of the mesh
  21518. */
  21519. get: function () {
  21520. return Mesh._CAP_START;
  21521. },
  21522. enumerable: true,
  21523. configurable: true
  21524. });
  21525. Object.defineProperty(Mesh, "CAP_END", {
  21526. /**
  21527. * Mesh cap setting : one cap at the end of the mesh
  21528. */
  21529. get: function () {
  21530. return Mesh._CAP_END;
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. Object.defineProperty(Mesh, "CAP_ALL", {
  21536. /**
  21537. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21538. */
  21539. get: function () {
  21540. return Mesh._CAP_ALL;
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21546. set: function (callback) {
  21547. if (this._onBeforeDrawObserver) {
  21548. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21549. }
  21550. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21551. },
  21552. enumerable: true,
  21553. configurable: true
  21554. });
  21555. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21556. get: function () {
  21557. return this._morphTargetManager;
  21558. },
  21559. set: function (value) {
  21560. if (this._morphTargetManager === value) {
  21561. return;
  21562. }
  21563. this._morphTargetManager = value;
  21564. this._syncGeometryWithMorphTargetManager();
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. Object.defineProperty(Mesh.prototype, "source", {
  21570. get: function () {
  21571. return this._source;
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. // Methods
  21577. /**
  21578. * Returns the string "Mesh".
  21579. */
  21580. Mesh.prototype.getClassName = function () {
  21581. return "Mesh";
  21582. };
  21583. /**
  21584. * Returns a string.
  21585. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21586. */
  21587. Mesh.prototype.toString = function (fullDetails) {
  21588. var ret = _super.prototype.toString.call(this, fullDetails);
  21589. ret += ", n vertices: " + this.getTotalVertices();
  21590. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21591. if (this.animations) {
  21592. for (var i = 0; i < this.animations.length; i++) {
  21593. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21594. }
  21595. }
  21596. if (fullDetails) {
  21597. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21598. }
  21599. return ret;
  21600. };
  21601. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21602. /**
  21603. * True if the mesh has some Levels Of Details (LOD).
  21604. * Returns a boolean.
  21605. */
  21606. get: function () {
  21607. return this._LODLevels.length > 0;
  21608. },
  21609. enumerable: true,
  21610. configurable: true
  21611. });
  21612. Mesh.prototype._sortLODLevels = function () {
  21613. this._LODLevels.sort(function (a, b) {
  21614. if (a.distance < b.distance) {
  21615. return 1;
  21616. }
  21617. if (a.distance > b.distance) {
  21618. return -1;
  21619. }
  21620. return 0;
  21621. });
  21622. };
  21623. /**
  21624. * Add a mesh as LOD level triggered at the given distance.
  21625. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21626. * @param {number} distance The distance from the center of the object to show this level
  21627. * @param {Mesh} mesh The mesh to be added as LOD level
  21628. * @return {Mesh} This mesh (for chaining)
  21629. */
  21630. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21631. if (mesh && mesh._masterMesh) {
  21632. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21633. return this;
  21634. }
  21635. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21636. this._LODLevels.push(level);
  21637. if (mesh) {
  21638. mesh._masterMesh = this;
  21639. }
  21640. this._sortLODLevels();
  21641. return this;
  21642. };
  21643. /**
  21644. * Returns the LOD level mesh at the passed distance or null if not found.
  21645. * It is related to the method `addLODLevel(distance, mesh)`.
  21646. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21647. * Returns an object Mesh or `null`.
  21648. */
  21649. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21650. for (var index = 0; index < this._LODLevels.length; index++) {
  21651. var level = this._LODLevels[index];
  21652. if (level.distance === distance) {
  21653. return level.mesh;
  21654. }
  21655. }
  21656. return null;
  21657. };
  21658. /**
  21659. * Remove a mesh from the LOD array
  21660. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21661. * @param {Mesh} mesh The mesh to be removed.
  21662. * @return {Mesh} This mesh (for chaining)
  21663. */
  21664. Mesh.prototype.removeLODLevel = function (mesh) {
  21665. for (var index = 0; index < this._LODLevels.length; index++) {
  21666. if (this._LODLevels[index].mesh === mesh) {
  21667. this._LODLevels.splice(index, 1);
  21668. if (mesh) {
  21669. mesh._masterMesh = null;
  21670. }
  21671. }
  21672. }
  21673. this._sortLODLevels();
  21674. return this;
  21675. };
  21676. /**
  21677. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21678. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21679. */
  21680. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21681. if (!this._LODLevels || this._LODLevels.length === 0) {
  21682. return this;
  21683. }
  21684. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21685. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21686. if (this.onLODLevelSelection) {
  21687. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21688. }
  21689. return this;
  21690. }
  21691. for (var index = 0; index < this._LODLevels.length; index++) {
  21692. var level = this._LODLevels[index];
  21693. if (level.distance < distanceToCamera) {
  21694. if (level.mesh) {
  21695. level.mesh._preActivate();
  21696. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21697. }
  21698. if (this.onLODLevelSelection) {
  21699. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21700. }
  21701. return level.mesh;
  21702. }
  21703. }
  21704. if (this.onLODLevelSelection) {
  21705. this.onLODLevelSelection(distanceToCamera, this, this);
  21706. }
  21707. return this;
  21708. };
  21709. Object.defineProperty(Mesh.prototype, "geometry", {
  21710. /**
  21711. * Returns the mesh internal Geometry object.
  21712. */
  21713. get: function () {
  21714. return this._geometry;
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. /**
  21720. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21721. */
  21722. Mesh.prototype.getTotalVertices = function () {
  21723. if (!this._geometry) {
  21724. return 0;
  21725. }
  21726. return this._geometry.getTotalVertices();
  21727. };
  21728. /**
  21729. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21730. * 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.
  21731. * You can force the copy with forceCopy === true
  21732. * Returns null if the mesh has no geometry or no vertex buffer.
  21733. * Possible `kind` values :
  21734. * - BABYLON.VertexBuffer.PositionKind
  21735. * - BABYLON.VertexBuffer.UVKind
  21736. * - BABYLON.VertexBuffer.UV2Kind
  21737. * - BABYLON.VertexBuffer.UV3Kind
  21738. * - BABYLON.VertexBuffer.UV4Kind
  21739. * - BABYLON.VertexBuffer.UV5Kind
  21740. * - BABYLON.VertexBuffer.UV6Kind
  21741. * - BABYLON.VertexBuffer.ColorKind
  21742. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21743. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21744. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21745. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21746. */
  21747. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21748. if (!this._geometry) {
  21749. return null;
  21750. }
  21751. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21752. };
  21753. /**
  21754. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21755. * Returns `undefined` if the mesh has no geometry.
  21756. * Possible `kind` values :
  21757. * - BABYLON.VertexBuffer.PositionKind
  21758. * - BABYLON.VertexBuffer.UVKind
  21759. * - BABYLON.VertexBuffer.UV2Kind
  21760. * - BABYLON.VertexBuffer.UV3Kind
  21761. * - BABYLON.VertexBuffer.UV4Kind
  21762. * - BABYLON.VertexBuffer.UV5Kind
  21763. * - BABYLON.VertexBuffer.UV6Kind
  21764. * - BABYLON.VertexBuffer.ColorKind
  21765. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21766. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21767. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21768. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21769. */
  21770. Mesh.prototype.getVertexBuffer = function (kind) {
  21771. if (!this._geometry) {
  21772. return undefined;
  21773. }
  21774. return this._geometry.getVertexBuffer(kind);
  21775. };
  21776. /**
  21777. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21778. * Possible `kind` values :
  21779. * - BABYLON.VertexBuffer.PositionKind
  21780. * - BABYLON.VertexBuffer.UVKind
  21781. * - BABYLON.VertexBuffer.UV2Kind
  21782. * - BABYLON.VertexBuffer.UV3Kind
  21783. * - BABYLON.VertexBuffer.UV4Kind
  21784. * - BABYLON.VertexBuffer.UV5Kind
  21785. * - BABYLON.VertexBuffer.UV6Kind
  21786. * - BABYLON.VertexBuffer.ColorKind
  21787. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21788. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21789. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21790. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21791. */
  21792. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21793. if (!this._geometry) {
  21794. if (this._delayInfo) {
  21795. return this._delayInfo.indexOf(kind) !== -1;
  21796. }
  21797. return false;
  21798. }
  21799. return this._geometry.isVerticesDataPresent(kind);
  21800. };
  21801. /**
  21802. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21803. * Possible `kind` values :
  21804. * - BABYLON.VertexBuffer.PositionKind
  21805. * - BABYLON.VertexBuffer.UVKind
  21806. * - BABYLON.VertexBuffer.UV2Kind
  21807. * - BABYLON.VertexBuffer.UV3Kind
  21808. * - BABYLON.VertexBuffer.UV4Kind
  21809. * - BABYLON.VertexBuffer.UV5Kind
  21810. * - BABYLON.VertexBuffer.UV6Kind
  21811. * - BABYLON.VertexBuffer.ColorKind
  21812. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21813. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21814. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21815. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21816. */
  21817. Mesh.prototype.getVerticesDataKinds = function () {
  21818. if (!this._geometry) {
  21819. var result = [];
  21820. if (this._delayInfo) {
  21821. this._delayInfo.forEach(function (kind, index, array) {
  21822. result.push(kind);
  21823. });
  21824. }
  21825. return result;
  21826. }
  21827. return this._geometry.getVerticesDataKinds();
  21828. };
  21829. /**
  21830. * Returns a positive integer : the total number of indices in this mesh geometry.
  21831. * Returns zero if the mesh has no geometry.
  21832. */
  21833. Mesh.prototype.getTotalIndices = function () {
  21834. if (!this._geometry) {
  21835. return 0;
  21836. }
  21837. return this._geometry.getTotalIndices();
  21838. };
  21839. /**
  21840. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21841. * 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.
  21842. * Returns an empty array if the mesh has no geometry.
  21843. */
  21844. Mesh.prototype.getIndices = function (copyWhenShared) {
  21845. if (!this._geometry) {
  21846. return [];
  21847. }
  21848. return this._geometry.getIndices(copyWhenShared);
  21849. };
  21850. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21851. get: function () {
  21852. return this._masterMesh !== null && this._masterMesh !== undefined;
  21853. },
  21854. enumerable: true,
  21855. configurable: true
  21856. });
  21857. /**
  21858. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21859. */
  21860. Mesh.prototype.isReady = function () {
  21861. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21862. return false;
  21863. }
  21864. return _super.prototype.isReady.call(this);
  21865. };
  21866. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21867. /**
  21868. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21869. * This property is pertinent only for updatable parametric shapes.
  21870. */
  21871. get: function () {
  21872. return this._areNormalsFrozen;
  21873. },
  21874. enumerable: true,
  21875. configurable: true
  21876. });
  21877. /**
  21878. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21879. * It has no effect at all on other shapes.
  21880. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21881. * Returns the Mesh.
  21882. */
  21883. Mesh.prototype.freezeNormals = function () {
  21884. this._areNormalsFrozen = true;
  21885. return this;
  21886. };
  21887. /**
  21888. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21889. * It has no effect at all on other shapes.
  21890. * It reactivates the mesh normals computation if it was previously frozen.
  21891. * Returns the Mesh.
  21892. */
  21893. Mesh.prototype.unfreezeNormals = function () {
  21894. this._areNormalsFrozen = false;
  21895. return this;
  21896. };
  21897. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21898. /**
  21899. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21900. */
  21901. set: function (count) {
  21902. this._overridenInstanceCount = count;
  21903. },
  21904. enumerable: true,
  21905. configurable: true
  21906. });
  21907. // Methods
  21908. Mesh.prototype._preActivate = function () {
  21909. var sceneRenderId = this.getScene().getRenderId();
  21910. if (this._preActivateId === sceneRenderId) {
  21911. return this;
  21912. }
  21913. this._preActivateId = sceneRenderId;
  21914. this._visibleInstances = null;
  21915. return this;
  21916. };
  21917. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21918. if (this._visibleInstances) {
  21919. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21920. }
  21921. return this;
  21922. };
  21923. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21924. if (!this._visibleInstances) {
  21925. this._visibleInstances = {};
  21926. this._visibleInstances.defaultRenderId = renderId;
  21927. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21928. }
  21929. if (!this._visibleInstances[renderId]) {
  21930. this._visibleInstances[renderId] = new Array();
  21931. }
  21932. this._visibleInstances[renderId].push(instance);
  21933. return this;
  21934. };
  21935. /**
  21936. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21937. * This means the mesh underlying bounding box and sphere are recomputed.
  21938. * Returns the Mesh.
  21939. */
  21940. Mesh.prototype.refreshBoundingInfo = function () {
  21941. if (this._boundingInfo.isLocked) {
  21942. return;
  21943. }
  21944. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21945. if (data) {
  21946. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21947. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21948. }
  21949. if (this.subMeshes) {
  21950. for (var index = 0; index < this.subMeshes.length; index++) {
  21951. this.subMeshes[index].refreshBoundingInfo();
  21952. }
  21953. }
  21954. this._updateBoundingInfo();
  21955. return this;
  21956. };
  21957. Mesh.prototype._createGlobalSubMesh = function (force) {
  21958. var totalVertices = this.getTotalVertices();
  21959. if (!totalVertices || !this.getIndices()) {
  21960. return null;
  21961. }
  21962. // Check if we need to recreate the submeshes
  21963. if (this.subMeshes && this.subMeshes.length > 0) {
  21964. var totalIndices = this.getIndices().length;
  21965. var needToRecreate = false;
  21966. if (force) {
  21967. needToRecreate = true;
  21968. }
  21969. else {
  21970. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21971. var submesh = _a[_i];
  21972. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21973. needToRecreate = true;
  21974. break;
  21975. }
  21976. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21977. needToRecreate = true;
  21978. break;
  21979. }
  21980. }
  21981. }
  21982. if (!needToRecreate) {
  21983. return;
  21984. }
  21985. }
  21986. this.releaseSubMeshes();
  21987. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21988. };
  21989. Mesh.prototype.subdivide = function (count) {
  21990. if (count < 1) {
  21991. return;
  21992. }
  21993. var totalIndices = this.getTotalIndices();
  21994. var subdivisionSize = (totalIndices / count) | 0;
  21995. var offset = 0;
  21996. // Ensure that subdivisionSize is a multiple of 3
  21997. while (subdivisionSize % 3 !== 0) {
  21998. subdivisionSize++;
  21999. }
  22000. this.releaseSubMeshes();
  22001. for (var index = 0; index < count; index++) {
  22002. if (offset >= totalIndices) {
  22003. break;
  22004. }
  22005. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22006. offset += subdivisionSize;
  22007. }
  22008. this.synchronizeInstances();
  22009. };
  22010. /**
  22011. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22012. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22013. * The `data` are either a numeric array either a Float32Array.
  22014. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22015. * 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).
  22016. * Note that a new underlying VertexBuffer object is created each call.
  22017. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22018. *
  22019. * Possible `kind` values :
  22020. * - BABYLON.VertexBuffer.PositionKind
  22021. * - BABYLON.VertexBuffer.UVKind
  22022. * - BABYLON.VertexBuffer.UV2Kind
  22023. * - BABYLON.VertexBuffer.UV3Kind
  22024. * - BABYLON.VertexBuffer.UV4Kind
  22025. * - BABYLON.VertexBuffer.UV5Kind
  22026. * - BABYLON.VertexBuffer.UV6Kind
  22027. * - BABYLON.VertexBuffer.ColorKind
  22028. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22029. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22030. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22031. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22032. *
  22033. * Returns the Mesh.
  22034. */
  22035. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22036. if (!this._geometry) {
  22037. var vertexData = new BABYLON.VertexData();
  22038. vertexData.set(data, kind);
  22039. var scene = this.getScene();
  22040. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22041. }
  22042. else {
  22043. this._geometry.setVerticesData(kind, data, updatable, stride);
  22044. }
  22045. return this;
  22046. };
  22047. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22048. if (updatable === void 0) { updatable = true; }
  22049. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  22050. return;
  22051. }
  22052. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22053. };
  22054. /**
  22055. * Sets the mesh VertexBuffer.
  22056. * Returns the Mesh.
  22057. */
  22058. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22059. if (!this._geometry) {
  22060. var scene = this.getScene();
  22061. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22062. }
  22063. this._geometry.setVerticesBuffer(buffer);
  22064. return this;
  22065. };
  22066. /**
  22067. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22068. * If the mesh has no geometry, it is simply returned as it is.
  22069. * The `data` are either a numeric array either a Float32Array.
  22070. * No new underlying VertexBuffer object is created.
  22071. * 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.
  22072. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22073. *
  22074. * Possible `kind` values :
  22075. * - BABYLON.VertexBuffer.PositionKind
  22076. * - BABYLON.VertexBuffer.UVKind
  22077. * - BABYLON.VertexBuffer.UV2Kind
  22078. * - BABYLON.VertexBuffer.UV3Kind
  22079. * - BABYLON.VertexBuffer.UV4Kind
  22080. * - BABYLON.VertexBuffer.UV5Kind
  22081. * - BABYLON.VertexBuffer.UV6Kind
  22082. * - BABYLON.VertexBuffer.ColorKind
  22083. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22084. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22085. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22086. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22087. *
  22088. * Returns the Mesh.
  22089. */
  22090. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22091. if (!this._geometry) {
  22092. return;
  22093. }
  22094. if (!makeItUnique) {
  22095. this._geometry.updateVerticesData(kind, data, updateExtends);
  22096. }
  22097. else {
  22098. this.makeGeometryUnique();
  22099. this.updateVerticesData(kind, data, updateExtends, false);
  22100. }
  22101. return this;
  22102. };
  22103. /**
  22104. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22105. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22106. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22107. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22108. * Returns the Mesh.
  22109. */
  22110. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22111. if (computeNormals === void 0) { computeNormals = true; }
  22112. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22113. positionFunction(positions);
  22114. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22115. if (computeNormals) {
  22116. var indices = this.getIndices();
  22117. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22118. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22119. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22120. }
  22121. return this;
  22122. };
  22123. /**
  22124. * Creates a un-shared specific occurence of the geometry for the mesh.
  22125. * Returns the Mesh.
  22126. */
  22127. Mesh.prototype.makeGeometryUnique = function () {
  22128. if (!this._geometry) {
  22129. return;
  22130. }
  22131. var oldGeometry = this._geometry;
  22132. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22133. oldGeometry.releaseForMesh(this, true);
  22134. geometry.applyToMesh(this);
  22135. return this;
  22136. };
  22137. /**
  22138. * Sets the mesh indices.
  22139. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22140. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22141. * This method creates a new index buffer each call.
  22142. * Returns the Mesh.
  22143. */
  22144. Mesh.prototype.setIndices = function (indices, totalVertices) {
  22145. if (!this._geometry) {
  22146. var vertexData = new BABYLON.VertexData();
  22147. vertexData.indices = indices;
  22148. var scene = this.getScene();
  22149. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  22150. }
  22151. else {
  22152. this._geometry.setIndices(indices, totalVertices);
  22153. }
  22154. return this;
  22155. };
  22156. /**
  22157. * Invert the geometry to move from a right handed system to a left handed one.
  22158. * Returns the Mesh.
  22159. */
  22160. Mesh.prototype.toLeftHanded = function () {
  22161. if (!this._geometry) {
  22162. return;
  22163. }
  22164. this._geometry.toLeftHanded();
  22165. return this;
  22166. };
  22167. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22168. var engine = this.getScene().getEngine();
  22169. // Wireframe
  22170. var indexToBind;
  22171. if (this._unIndexed) {
  22172. indexToBind = null;
  22173. }
  22174. else {
  22175. switch (fillMode) {
  22176. case BABYLON.Material.PointFillMode:
  22177. indexToBind = null;
  22178. break;
  22179. case BABYLON.Material.WireFrameFillMode:
  22180. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22181. break;
  22182. default:
  22183. case BABYLON.Material.TriangleFillMode:
  22184. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22185. break;
  22186. }
  22187. }
  22188. // VBOs
  22189. this._geometry._bind(effect, indexToBind);
  22190. return this;
  22191. };
  22192. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22193. if (alternate === void 0) { alternate = false; }
  22194. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22195. return this;
  22196. }
  22197. this.onBeforeDrawObservable.notifyObservers(this);
  22198. var scene = this.getScene();
  22199. var engine = scene.getEngine();
  22200. // Draw order
  22201. switch (fillMode) {
  22202. case BABYLON.Material.PointFillMode:
  22203. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22204. break;
  22205. case BABYLON.Material.WireFrameFillMode:
  22206. if (this._unIndexed) {
  22207. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22208. }
  22209. else {
  22210. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22211. }
  22212. break;
  22213. default:
  22214. if (this._unIndexed) {
  22215. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22216. }
  22217. else {
  22218. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22219. }
  22220. }
  22221. if (scene._isAlternateRenderingEnabled && !alternate) {
  22222. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22223. scene._switchToAlternateCameraConfiguration(true);
  22224. this._effectiveMaterial.bindView(effect);
  22225. this._effectiveMaterial.bindViewProjection(effect);
  22226. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22227. this._draw(subMesh, fillMode, instancesCount, true);
  22228. engine.setViewport(scene.activeCamera.viewport);
  22229. scene._switchToAlternateCameraConfiguration(false);
  22230. this._effectiveMaterial.bindView(effect);
  22231. this._effectiveMaterial.bindViewProjection(effect);
  22232. }
  22233. return this;
  22234. };
  22235. /**
  22236. * Registers for this mesh a javascript function called just before the rendering process.
  22237. * This function is passed the current mesh.
  22238. * Return the Mesh.
  22239. */
  22240. Mesh.prototype.registerBeforeRender = function (func) {
  22241. this.onBeforeRenderObservable.add(func);
  22242. return this;
  22243. };
  22244. /**
  22245. * Disposes a previously registered javascript function called before the rendering.
  22246. * This function is passed the current mesh.
  22247. * Returns the Mesh.
  22248. */
  22249. Mesh.prototype.unregisterBeforeRender = function (func) {
  22250. this.onBeforeRenderObservable.removeCallback(func);
  22251. return this;
  22252. };
  22253. /**
  22254. * Registers for this mesh a javascript function called just after the rendering is complete.
  22255. * This function is passed the current mesh.
  22256. * Returns the Mesh.
  22257. */
  22258. Mesh.prototype.registerAfterRender = function (func) {
  22259. this.onAfterRenderObservable.add(func);
  22260. return this;
  22261. };
  22262. /**
  22263. * Disposes a previously registered javascript function called after the rendering.
  22264. * This function is passed the current mesh.
  22265. * Return the Mesh.
  22266. */
  22267. Mesh.prototype.unregisterAfterRender = function (func) {
  22268. this.onAfterRenderObservable.removeCallback(func);
  22269. return this;
  22270. };
  22271. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22272. var scene = this.getScene();
  22273. this._batchCache.mustReturn = false;
  22274. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22275. this._batchCache.visibleInstances[subMeshId] = null;
  22276. if (this._visibleInstances) {
  22277. var currentRenderId = scene.getRenderId();
  22278. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22279. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22280. var selfRenderId = this._renderId;
  22281. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22282. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22283. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22284. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22285. }
  22286. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22287. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22288. this._batchCache.mustReturn = true;
  22289. return this._batchCache;
  22290. }
  22291. if (currentRenderId !== selfRenderId) {
  22292. this._batchCache.renderSelf[subMeshId] = false;
  22293. }
  22294. }
  22295. this._renderIdForInstances[subMeshId] = currentRenderId;
  22296. }
  22297. return this._batchCache;
  22298. };
  22299. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22300. var visibleInstances = batch.visibleInstances[subMesh._id];
  22301. var matricesCount = visibleInstances.length + 1;
  22302. var bufferSize = matricesCount * 16 * 4;
  22303. var currentInstancesBufferSize = this._instancesBufferSize;
  22304. var instancesBuffer = this._instancesBuffer;
  22305. while (this._instancesBufferSize < bufferSize) {
  22306. this._instancesBufferSize *= 2;
  22307. }
  22308. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22309. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22310. }
  22311. var offset = 0;
  22312. var instancesCount = 0;
  22313. var world = this.getWorldMatrix();
  22314. if (batch.renderSelf[subMesh._id]) {
  22315. world.copyToArray(this._instancesData, offset);
  22316. offset += 16;
  22317. instancesCount++;
  22318. }
  22319. if (visibleInstances) {
  22320. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22321. var instance = visibleInstances[instanceIndex];
  22322. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22323. offset += 16;
  22324. instancesCount++;
  22325. }
  22326. }
  22327. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22328. if (instancesBuffer) {
  22329. instancesBuffer.dispose();
  22330. }
  22331. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22332. this._instancesBuffer = instancesBuffer;
  22333. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22334. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22335. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22336. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22337. }
  22338. else {
  22339. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22340. }
  22341. this._bind(subMesh, effect, fillMode);
  22342. this._draw(subMesh, fillMode, instancesCount);
  22343. engine.unbindInstanceAttributes();
  22344. return this;
  22345. };
  22346. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22347. var scene = this.getScene();
  22348. var engine = scene.getEngine();
  22349. if (hardwareInstancedRendering) {
  22350. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22351. }
  22352. else {
  22353. if (batch.renderSelf[subMesh._id]) {
  22354. // Draw
  22355. if (onBeforeDraw) {
  22356. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22357. }
  22358. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22359. }
  22360. if (batch.visibleInstances[subMesh._id]) {
  22361. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22362. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22363. // World
  22364. var world = instance.getWorldMatrix();
  22365. if (onBeforeDraw) {
  22366. onBeforeDraw(true, world, effectiveMaterial);
  22367. }
  22368. // Draw
  22369. this._draw(subMesh, fillMode);
  22370. }
  22371. }
  22372. }
  22373. return this;
  22374. };
  22375. /**
  22376. * Triggers the draw call for the mesh.
  22377. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22378. * Returns the Mesh.
  22379. */
  22380. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22381. this.checkOcclusionQuery();
  22382. if (this._isOccluded) {
  22383. return;
  22384. }
  22385. var scene = this.getScene();
  22386. // Managing instances
  22387. var batch = this._getInstancesRenderList(subMesh._id);
  22388. if (batch.mustReturn) {
  22389. return this;
  22390. }
  22391. // Checking geometry state
  22392. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22393. return this;
  22394. }
  22395. var callbackIndex;
  22396. this.onBeforeRenderObservable.notifyObservers(this);
  22397. var engine = scene.getEngine();
  22398. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22399. // Material
  22400. this._effectiveMaterial = subMesh.getMaterial();
  22401. if (!this._effectiveMaterial) {
  22402. return this;
  22403. }
  22404. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22405. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22406. return this;
  22407. }
  22408. }
  22409. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22410. return this;
  22411. }
  22412. // Alpha mode
  22413. if (enableAlphaMode) {
  22414. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  22415. }
  22416. // Outline - step 1
  22417. var savedDepthWrite = engine.getDepthWrite();
  22418. if (this.renderOutline) {
  22419. engine.setDepthWrite(false);
  22420. scene.getOutlineRenderer().render(subMesh, batch);
  22421. engine.setDepthWrite(savedDepthWrite);
  22422. }
  22423. var effect;
  22424. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22425. effect = subMesh.effect;
  22426. }
  22427. else {
  22428. effect = this._effectiveMaterial.getEffect();
  22429. }
  22430. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  22431. if (this._effectiveMaterial.forceDepthWrite) {
  22432. engine.setDepthWrite(true);
  22433. }
  22434. // Bind
  22435. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  22436. if (!hardwareInstancedRendering) {
  22437. this._bind(subMesh, effect, fillMode);
  22438. }
  22439. var world = this.getWorldMatrix();
  22440. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22441. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22442. }
  22443. else {
  22444. this._effectiveMaterial.bind(world, this);
  22445. }
  22446. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  22447. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  22448. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22449. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  22450. }
  22451. // Draw
  22452. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22453. // Unbind
  22454. this._effectiveMaterial.unbind();
  22455. // Outline - step 2
  22456. if (this.renderOutline && savedDepthWrite) {
  22457. engine.setDepthWrite(true);
  22458. engine.setColorWrite(false);
  22459. scene.getOutlineRenderer().render(subMesh, batch);
  22460. engine.setColorWrite(true);
  22461. }
  22462. // Overlay
  22463. if (this.renderOverlay) {
  22464. var currentMode = engine.getAlphaMode();
  22465. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22466. scene.getOutlineRenderer().render(subMesh, batch, true);
  22467. engine.setAlphaMode(currentMode);
  22468. }
  22469. this.onAfterRenderObservable.notifyObservers(this);
  22470. return this;
  22471. };
  22472. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22473. if (isInstance) {
  22474. effectiveMaterial.bindOnlyWorldMatrix(world);
  22475. }
  22476. return this;
  22477. };
  22478. /**
  22479. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22480. */
  22481. Mesh.prototype.getEmittedParticleSystems = function () {
  22482. var results = new Array();
  22483. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22484. var particleSystem = this.getScene().particleSystems[index];
  22485. if (particleSystem.emitter === this) {
  22486. results.push(particleSystem);
  22487. }
  22488. }
  22489. return results;
  22490. };
  22491. /**
  22492. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22493. */
  22494. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22495. var results = new Array();
  22496. var descendants = this.getDescendants();
  22497. descendants.push(this);
  22498. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22499. var particleSystem = this.getScene().particleSystems[index];
  22500. var emitter = particleSystem.emitter;
  22501. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22502. results.push(particleSystem);
  22503. }
  22504. }
  22505. return results;
  22506. };
  22507. Mesh.prototype._checkDelayState = function () {
  22508. var scene = this.getScene();
  22509. if (this._geometry) {
  22510. this._geometry.load(scene);
  22511. }
  22512. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22513. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22514. this._queueLoad(this, scene);
  22515. }
  22516. return this;
  22517. };
  22518. Mesh.prototype._queueLoad = function (mesh, scene) {
  22519. var _this = this;
  22520. scene._addPendingData(mesh);
  22521. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22522. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22523. if (data instanceof ArrayBuffer) {
  22524. _this._delayLoadingFunction(data, _this);
  22525. }
  22526. else {
  22527. _this._delayLoadingFunction(JSON.parse(data), _this);
  22528. }
  22529. _this.instances.forEach(function (instance) {
  22530. instance._syncSubMeshes();
  22531. });
  22532. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22533. scene._removePendingData(_this);
  22534. }, function () { }, scene.database, getBinaryData);
  22535. return this;
  22536. };
  22537. /**
  22538. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22539. */
  22540. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22541. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22542. return false;
  22543. }
  22544. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22545. return false;
  22546. }
  22547. this._checkDelayState();
  22548. return true;
  22549. };
  22550. /**
  22551. * Sets the mesh material by the material or multiMaterial `id` property.
  22552. * The material `id` is a string identifying the material or the multiMaterial.
  22553. * This method returns the Mesh.
  22554. */
  22555. Mesh.prototype.setMaterialByID = function (id) {
  22556. var materials = this.getScene().materials;
  22557. var index;
  22558. for (index = materials.length - 1; index > -1; index--) {
  22559. if (materials[index].id === id) {
  22560. this.material = materials[index];
  22561. return this;
  22562. }
  22563. }
  22564. // Multi
  22565. var multiMaterials = this.getScene().multiMaterials;
  22566. for (index = multiMaterials.length - 1; index > -1; index--) {
  22567. if (multiMaterials[index].id === id) {
  22568. this.material = multiMaterials[index];
  22569. return this;
  22570. }
  22571. }
  22572. return this;
  22573. };
  22574. /**
  22575. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22576. */
  22577. Mesh.prototype.getAnimatables = function () {
  22578. var results = [];
  22579. if (this.material) {
  22580. results.push(this.material);
  22581. }
  22582. if (this.skeleton) {
  22583. results.push(this.skeleton);
  22584. }
  22585. return results;
  22586. };
  22587. /**
  22588. * Modifies the mesh geometry according to the passed transformation matrix.
  22589. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22590. * The mesh normals are modified accordingly the same transformation.
  22591. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22592. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22593. * Returns the Mesh.
  22594. */
  22595. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22596. // Position
  22597. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22598. return this;
  22599. }
  22600. var submeshes = this.subMeshes.splice(0);
  22601. this._resetPointsArrayCache();
  22602. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22603. var temp = [];
  22604. var index;
  22605. for (index = 0; index < data.length; index += 3) {
  22606. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22607. }
  22608. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22609. // Normals
  22610. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22611. return this;
  22612. }
  22613. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22614. temp = [];
  22615. for (index = 0; index < data.length; index += 3) {
  22616. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22617. }
  22618. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22619. // flip faces?
  22620. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22621. this.flipFaces();
  22622. }
  22623. // Restore submeshes
  22624. this.releaseSubMeshes();
  22625. this.subMeshes = submeshes;
  22626. return this;
  22627. };
  22628. /**
  22629. * Modifies the mesh geometry according to its own current World Matrix.
  22630. * The mesh World Matrix is then reset.
  22631. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22632. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22633. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22634. * Returns the Mesh.
  22635. */
  22636. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22637. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22638. this.scaling.copyFromFloats(1, 1, 1);
  22639. this.position.copyFromFloats(0, 0, 0);
  22640. this.rotation.copyFromFloats(0, 0, 0);
  22641. //only if quaternion is already set
  22642. if (this.rotationQuaternion) {
  22643. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22644. }
  22645. this._worldMatrix = BABYLON.Matrix.Identity();
  22646. return this;
  22647. };
  22648. Object.defineProperty(Mesh.prototype, "_positions", {
  22649. // Cache
  22650. get: function () {
  22651. if (this._geometry) {
  22652. return this._geometry._positions;
  22653. }
  22654. return null;
  22655. },
  22656. enumerable: true,
  22657. configurable: true
  22658. });
  22659. Mesh.prototype._resetPointsArrayCache = function () {
  22660. if (this._geometry) {
  22661. this._geometry._resetPointsArrayCache();
  22662. }
  22663. return this;
  22664. };
  22665. Mesh.prototype._generatePointsArray = function () {
  22666. if (this._geometry) {
  22667. return this._geometry._generatePointsArray();
  22668. }
  22669. return false;
  22670. };
  22671. /**
  22672. * Returns a new Mesh object generated from the current mesh properties.
  22673. * This method must not get confused with createInstance().
  22674. * The parameter `name` is a string, the name given to the new mesh.
  22675. * The optional parameter `newParent` can be any Node object (default `null`).
  22676. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22677. * 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.
  22678. */
  22679. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22680. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22681. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22682. };
  22683. /**
  22684. * Disposes the mesh.
  22685. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22686. */
  22687. Mesh.prototype.dispose = function (doNotRecurse) {
  22688. var _this = this;
  22689. this.morphTargetManager = undefined;
  22690. if (this._geometry) {
  22691. this._geometry.releaseForMesh(this, true);
  22692. }
  22693. // Sources
  22694. var meshes = this.getScene().meshes;
  22695. meshes.forEach(function (mesh) {
  22696. if (mesh._source && mesh._source === _this) {
  22697. mesh._source = null;
  22698. }
  22699. });
  22700. this._source = null;
  22701. // Instances
  22702. if (this._instancesBuffer) {
  22703. this._instancesBuffer.dispose();
  22704. this._instancesBuffer = null;
  22705. }
  22706. while (this.instances.length) {
  22707. this.instances[0].dispose();
  22708. }
  22709. // Highlight layers.
  22710. var highlightLayers = this.getScene().highlightLayers;
  22711. for (var i = 0; i < highlightLayers.length; i++) {
  22712. var highlightLayer = highlightLayers[i];
  22713. if (highlightLayer) {
  22714. highlightLayer.removeMesh(this);
  22715. highlightLayer.removeExcludedMesh(this);
  22716. }
  22717. }
  22718. _super.prototype.dispose.call(this, doNotRecurse);
  22719. };
  22720. /**
  22721. * Modifies the mesh geometry according to a displacement map.
  22722. * 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.
  22723. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22724. * This method returns nothing.
  22725. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22726. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22727. * 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.
  22728. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22729. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22730. *
  22731. * Returns the Mesh.
  22732. */
  22733. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22734. var _this = this;
  22735. var scene = this.getScene();
  22736. var onload = function (img) {
  22737. // Getting height map data
  22738. var canvas = document.createElement("canvas");
  22739. var context = canvas.getContext("2d");
  22740. var heightMapWidth = img.width;
  22741. var heightMapHeight = img.height;
  22742. canvas.width = heightMapWidth;
  22743. canvas.height = heightMapHeight;
  22744. context.drawImage(img, 0, 0);
  22745. // Create VertexData from map data
  22746. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22747. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22748. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22749. //execute success callback, if set
  22750. if (onSuccess) {
  22751. onSuccess(_this);
  22752. }
  22753. };
  22754. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22755. return this;
  22756. };
  22757. /**
  22758. * Modifies the mesh geometry according to a displacementMap buffer.
  22759. * 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.
  22760. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22761. * This method returns nothing.
  22762. * 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.
  22763. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22764. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22765. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22766. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22767. *
  22768. * Returns the Mesh.
  22769. */
  22770. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22771. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22772. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22773. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22774. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22775. return this;
  22776. }
  22777. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22778. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22779. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22780. var position = BABYLON.Vector3.Zero();
  22781. var normal = BABYLON.Vector3.Zero();
  22782. var uv = BABYLON.Vector2.Zero();
  22783. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22784. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22785. for (var index = 0; index < positions.length; index += 3) {
  22786. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22787. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22788. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22789. // Compute height
  22790. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22791. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22792. var pos = (u + v * heightMapWidth) * 4;
  22793. var r = buffer[pos] / 255.0;
  22794. var g = buffer[pos + 1] / 255.0;
  22795. var b = buffer[pos + 2] / 255.0;
  22796. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22797. normal.normalize();
  22798. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22799. position = position.add(normal);
  22800. position.toArray(positions, index);
  22801. }
  22802. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22803. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22804. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22805. return this;
  22806. };
  22807. /**
  22808. * Modify the mesh to get a flat shading rendering.
  22809. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22810. * This method returns the Mesh.
  22811. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22812. */
  22813. Mesh.prototype.convertToFlatShadedMesh = function () {
  22814. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22815. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22816. var kinds = this.getVerticesDataKinds();
  22817. var vbs = [];
  22818. var data = [];
  22819. var newdata = [];
  22820. var updatableNormals = false;
  22821. var kindIndex;
  22822. var kind;
  22823. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22824. kind = kinds[kindIndex];
  22825. var vertexBuffer = this.getVertexBuffer(kind);
  22826. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22827. updatableNormals = vertexBuffer.isUpdatable();
  22828. kinds.splice(kindIndex, 1);
  22829. kindIndex--;
  22830. continue;
  22831. }
  22832. vbs[kind] = vertexBuffer;
  22833. data[kind] = vbs[kind].getData();
  22834. newdata[kind] = [];
  22835. }
  22836. // Save previous submeshes
  22837. var previousSubmeshes = this.subMeshes.slice(0);
  22838. var indices = this.getIndices();
  22839. var totalIndices = this.getTotalIndices();
  22840. // Generating unique vertices per face
  22841. var index;
  22842. for (index = 0; index < totalIndices; index++) {
  22843. var vertexIndex = indices[index];
  22844. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22845. kind = kinds[kindIndex];
  22846. var stride = vbs[kind].getStrideSize();
  22847. for (var offset = 0; offset < stride; offset++) {
  22848. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22849. }
  22850. }
  22851. }
  22852. // Updating faces & normal
  22853. var normals = [];
  22854. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22855. for (index = 0; index < totalIndices; index += 3) {
  22856. indices[index] = index;
  22857. indices[index + 1] = index + 1;
  22858. indices[index + 2] = index + 2;
  22859. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22860. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22861. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22862. var p1p2 = p1.subtract(p2);
  22863. var p3p2 = p3.subtract(p2);
  22864. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22865. // Store same normals for every vertex
  22866. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22867. normals.push(normal.x);
  22868. normals.push(normal.y);
  22869. normals.push(normal.z);
  22870. }
  22871. }
  22872. this.setIndices(indices);
  22873. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22874. // Updating vertex buffers
  22875. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22876. kind = kinds[kindIndex];
  22877. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22878. }
  22879. // Updating submeshes
  22880. this.releaseSubMeshes();
  22881. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22882. var previousOne = previousSubmeshes[submeshIndex];
  22883. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22884. }
  22885. this.synchronizeInstances();
  22886. return this;
  22887. };
  22888. /**
  22889. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22890. * In other words, more vertices, no more indices and a single bigger VBO.
  22891. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22892. * Returns the Mesh.
  22893. */
  22894. Mesh.prototype.convertToUnIndexedMesh = function () {
  22895. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22896. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22897. var kinds = this.getVerticesDataKinds();
  22898. var vbs = [];
  22899. var data = [];
  22900. var newdata = [];
  22901. var updatableNormals = false;
  22902. var kindIndex;
  22903. var kind;
  22904. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22905. kind = kinds[kindIndex];
  22906. var vertexBuffer = this.getVertexBuffer(kind);
  22907. vbs[kind] = vertexBuffer;
  22908. data[kind] = vbs[kind].getData();
  22909. newdata[kind] = [];
  22910. }
  22911. // Save previous submeshes
  22912. var previousSubmeshes = this.subMeshes.slice(0);
  22913. var indices = this.getIndices();
  22914. var totalIndices = this.getTotalIndices();
  22915. // Generating unique vertices per face
  22916. var index;
  22917. for (index = 0; index < totalIndices; index++) {
  22918. var vertexIndex = indices[index];
  22919. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22920. kind = kinds[kindIndex];
  22921. var stride = vbs[kind].getStrideSize();
  22922. for (var offset = 0; offset < stride; offset++) {
  22923. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22924. }
  22925. }
  22926. }
  22927. // Updating indices
  22928. for (index = 0; index < totalIndices; index += 3) {
  22929. indices[index] = index;
  22930. indices[index + 1] = index + 1;
  22931. indices[index + 2] = index + 2;
  22932. }
  22933. this.setIndices(indices);
  22934. // Updating vertex buffers
  22935. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22936. kind = kinds[kindIndex];
  22937. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22938. }
  22939. // Updating submeshes
  22940. this.releaseSubMeshes();
  22941. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22942. var previousOne = previousSubmeshes[submeshIndex];
  22943. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22944. }
  22945. this._unIndexed = true;
  22946. this.synchronizeInstances();
  22947. return this;
  22948. };
  22949. /**
  22950. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22951. * This method returns the Mesh.
  22952. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22953. */
  22954. Mesh.prototype.flipFaces = function (flipNormals) {
  22955. if (flipNormals === void 0) { flipNormals = false; }
  22956. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22957. var i;
  22958. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22959. for (i = 0; i < vertex_data.normals.length; i++) {
  22960. vertex_data.normals[i] *= -1;
  22961. }
  22962. }
  22963. var temp;
  22964. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22965. // reassign indices
  22966. temp = vertex_data.indices[i + 1];
  22967. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22968. vertex_data.indices[i + 2] = temp;
  22969. }
  22970. vertex_data.applyToMesh(this);
  22971. return this;
  22972. };
  22973. // Instances
  22974. /**
  22975. * Creates a new InstancedMesh object from the mesh model.
  22976. * An instance shares the same properties and the same material than its model.
  22977. * Only these properties of each instance can then be set individually :
  22978. * - position
  22979. * - rotation
  22980. * - rotationQuaternion
  22981. * - setPivotMatrix
  22982. * - scaling
  22983. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22984. * Warning : this method is not supported for Line mesh and LineSystem
  22985. */
  22986. Mesh.prototype.createInstance = function (name) {
  22987. return new BABYLON.InstancedMesh(name, this);
  22988. };
  22989. /**
  22990. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22991. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22992. * This method returns the Mesh.
  22993. */
  22994. Mesh.prototype.synchronizeInstances = function () {
  22995. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22996. var instance = this.instances[instanceIndex];
  22997. instance._syncSubMeshes();
  22998. }
  22999. return this;
  23000. };
  23001. /**
  23002. * Simplify the mesh according to the given array of settings.
  23003. * Function will return immediately and will simplify async. It returns the Mesh.
  23004. * @param settings a collection of simplification settings.
  23005. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23006. * @param type the type of simplification to run.
  23007. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23008. */
  23009. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23010. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23011. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23012. this.getScene().simplificationQueue.addTask({
  23013. settings: settings,
  23014. parallelProcessing: parallelProcessing,
  23015. mesh: this,
  23016. simplificationType: simplificationType,
  23017. successCallback: successCallback
  23018. });
  23019. return this;
  23020. };
  23021. /**
  23022. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23023. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23024. * This should be used together with the simplification to avoid disappearing triangles.
  23025. * Returns the Mesh.
  23026. * @param successCallback an optional success callback to be called after the optimization finished.
  23027. */
  23028. Mesh.prototype.optimizeIndices = function (successCallback) {
  23029. var _this = this;
  23030. var indices = this.getIndices();
  23031. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23032. var vectorPositions = [];
  23033. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23034. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23035. }
  23036. var dupes = [];
  23037. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23038. var realPos = vectorPositions.length - 1 - iteration;
  23039. var testedPosition = vectorPositions[realPos];
  23040. for (var j = 0; j < realPos; ++j) {
  23041. var againstPosition = vectorPositions[j];
  23042. if (testedPosition.equals(againstPosition)) {
  23043. dupes[realPos] = j;
  23044. break;
  23045. }
  23046. }
  23047. }, function () {
  23048. for (var i = 0; i < indices.length; ++i) {
  23049. indices[i] = dupes[indices[i]] || indices[i];
  23050. }
  23051. //indices are now reordered
  23052. var originalSubMeshes = _this.subMeshes.slice(0);
  23053. _this.setIndices(indices);
  23054. _this.subMeshes = originalSubMeshes;
  23055. if (successCallback) {
  23056. successCallback(_this);
  23057. }
  23058. });
  23059. return this;
  23060. };
  23061. Mesh.prototype.serialize = function (serializationObject) {
  23062. serializationObject.name = this.name;
  23063. serializationObject.id = this.id;
  23064. serializationObject.type = this.getClassName();
  23065. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  23066. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23067. }
  23068. serializationObject.position = this.position.asArray();
  23069. if (this.rotationQuaternion) {
  23070. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  23071. }
  23072. else if (this.rotation) {
  23073. serializationObject.rotation = this.rotation.asArray();
  23074. }
  23075. serializationObject.scaling = this.scaling.asArray();
  23076. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  23077. serializationObject.isEnabled = this.isEnabled();
  23078. serializationObject.isVisible = this.isVisible;
  23079. serializationObject.infiniteDistance = this.infiniteDistance;
  23080. serializationObject.pickable = this.isPickable;
  23081. serializationObject.receiveShadows = this.receiveShadows;
  23082. serializationObject.billboardMode = this.billboardMode;
  23083. serializationObject.visibility = this.visibility;
  23084. serializationObject.checkCollisions = this.checkCollisions;
  23085. serializationObject.isBlocker = this.isBlocker;
  23086. // Parent
  23087. if (this.parent) {
  23088. serializationObject.parentId = this.parent.id;
  23089. }
  23090. // Geometry
  23091. var geometry = this._geometry;
  23092. if (geometry) {
  23093. var geometryId = geometry.id;
  23094. serializationObject.geometryId = geometryId;
  23095. // SubMeshes
  23096. serializationObject.subMeshes = [];
  23097. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  23098. var subMesh = this.subMeshes[subIndex];
  23099. serializationObject.subMeshes.push({
  23100. materialIndex: subMesh.materialIndex,
  23101. verticesStart: subMesh.verticesStart,
  23102. verticesCount: subMesh.verticesCount,
  23103. indexStart: subMesh.indexStart,
  23104. indexCount: subMesh.indexCount
  23105. });
  23106. }
  23107. }
  23108. // Material
  23109. if (this.material) {
  23110. serializationObject.materialId = this.material.id;
  23111. }
  23112. else {
  23113. this.material = null;
  23114. }
  23115. // Morph targets
  23116. if (this.morphTargetManager) {
  23117. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  23118. }
  23119. // Skeleton
  23120. if (this.skeleton) {
  23121. serializationObject.skeletonId = this.skeleton.id;
  23122. }
  23123. // Physics
  23124. //TODO implement correct serialization for physics impostors.
  23125. if (this.getPhysicsImpostor()) {
  23126. var impostor = this.getPhysicsImpostor();
  23127. serializationObject.physicsMass = impostor.getParam("mass");
  23128. serializationObject.physicsFriction = impostor.getParam("friction");
  23129. serializationObject.physicsRestitution = impostor.getParam("mass");
  23130. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  23131. }
  23132. // Metadata
  23133. if (this.metadata) {
  23134. serializationObject.metadata = this.metadata;
  23135. }
  23136. // Instances
  23137. serializationObject.instances = [];
  23138. for (var index = 0; index < this.instances.length; index++) {
  23139. var instance = this.instances[index];
  23140. var serializationInstance = {
  23141. name: instance.name,
  23142. position: instance.position.asArray(),
  23143. scaling: instance.scaling.asArray()
  23144. };
  23145. if (instance.rotationQuaternion) {
  23146. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23147. }
  23148. else if (instance.rotation) {
  23149. serializationInstance.rotation = instance.rotation.asArray();
  23150. }
  23151. serializationObject.instances.push(serializationInstance);
  23152. // Animations
  23153. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23154. serializationInstance.ranges = instance.serializeAnimationRanges();
  23155. }
  23156. //
  23157. // Animations
  23158. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23159. serializationObject.ranges = this.serializeAnimationRanges();
  23160. // Layer mask
  23161. serializationObject.layerMask = this.layerMask;
  23162. // Alpha
  23163. serializationObject.alphaIndex = this.alphaIndex;
  23164. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23165. // Overlay
  23166. serializationObject.overlayAlpha = this.overlayAlpha;
  23167. serializationObject.overlayColor = this.overlayColor.asArray();
  23168. serializationObject.renderOverlay = this.renderOverlay;
  23169. // Fog
  23170. serializationObject.applyFog = this.applyFog;
  23171. // Action Manager
  23172. if (this.actionManager) {
  23173. serializationObject.actions = this.actionManager.serialize(this.name);
  23174. }
  23175. };
  23176. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23177. if (!this.geometry) {
  23178. return;
  23179. }
  23180. this._markSubMeshesAsAttributesDirty();
  23181. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  23182. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23183. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23184. this.morphTargetManager = undefined;
  23185. return;
  23186. }
  23187. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  23188. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  23189. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23190. if (morphTarget.hasNormals) {
  23191. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23192. }
  23193. if (morphTarget.hasTangents) {
  23194. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23195. }
  23196. }
  23197. }
  23198. else {
  23199. var index = 0;
  23200. // Positions
  23201. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23202. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23203. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23204. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23205. }
  23206. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23207. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23208. }
  23209. index++;
  23210. }
  23211. }
  23212. };
  23213. // Statics
  23214. /**
  23215. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23216. * The parameter `parsedMesh` is the mesh to be copied.
  23217. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23218. */
  23219. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23220. var mesh;
  23221. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  23222. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  23223. }
  23224. else {
  23225. mesh = new Mesh(parsedMesh.name, scene);
  23226. }
  23227. mesh.id = parsedMesh.id;
  23228. if (BABYLON.Tags) {
  23229. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23230. }
  23231. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23232. if (parsedMesh.metadata !== undefined) {
  23233. mesh.metadata = parsedMesh.metadata;
  23234. }
  23235. if (parsedMesh.rotationQuaternion) {
  23236. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23237. }
  23238. else if (parsedMesh.rotation) {
  23239. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23240. }
  23241. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23242. if (parsedMesh.localMatrix) {
  23243. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23244. }
  23245. else if (parsedMesh.pivotMatrix) {
  23246. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23247. }
  23248. mesh.setEnabled(parsedMesh.isEnabled);
  23249. mesh.isVisible = parsedMesh.isVisible;
  23250. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23251. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23252. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23253. if (parsedMesh.applyFog !== undefined) {
  23254. mesh.applyFog = parsedMesh.applyFog;
  23255. }
  23256. if (parsedMesh.pickable !== undefined) {
  23257. mesh.isPickable = parsedMesh.pickable;
  23258. }
  23259. if (parsedMesh.alphaIndex !== undefined) {
  23260. mesh.alphaIndex = parsedMesh.alphaIndex;
  23261. }
  23262. mesh.receiveShadows = parsedMesh.receiveShadows;
  23263. mesh.billboardMode = parsedMesh.billboardMode;
  23264. if (parsedMesh.visibility !== undefined) {
  23265. mesh.visibility = parsedMesh.visibility;
  23266. }
  23267. mesh.checkCollisions = parsedMesh.checkCollisions;
  23268. if (parsedMesh.isBlocker !== undefined) {
  23269. mesh.isBlocker = parsedMesh.isBlocker;
  23270. }
  23271. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23272. // freezeWorldMatrix
  23273. if (parsedMesh.freezeWorldMatrix) {
  23274. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23275. }
  23276. // Parent
  23277. if (parsedMesh.parentId) {
  23278. mesh._waitingParentId = parsedMesh.parentId;
  23279. }
  23280. // Actions
  23281. if (parsedMesh.actions !== undefined) {
  23282. mesh._waitingActions = parsedMesh.actions;
  23283. }
  23284. // Overlay
  23285. if (parsedMesh.overlayAlpha !== undefined) {
  23286. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23287. }
  23288. if (parsedMesh.overlayColor !== undefined) {
  23289. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23290. }
  23291. if (parsedMesh.renderOverlay !== undefined) {
  23292. mesh.renderOverlay = parsedMesh.renderOverlay;
  23293. }
  23294. // Geometry
  23295. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23296. if (parsedMesh.delayLoadingFile) {
  23297. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23298. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23299. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23300. if (parsedMesh._binaryInfo) {
  23301. mesh._binaryInfo = parsedMesh._binaryInfo;
  23302. }
  23303. mesh._delayInfo = [];
  23304. if (parsedMesh.hasUVs) {
  23305. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23306. }
  23307. if (parsedMesh.hasUVs2) {
  23308. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23309. }
  23310. if (parsedMesh.hasUVs3) {
  23311. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23312. }
  23313. if (parsedMesh.hasUVs4) {
  23314. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23315. }
  23316. if (parsedMesh.hasUVs5) {
  23317. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23318. }
  23319. if (parsedMesh.hasUVs6) {
  23320. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23321. }
  23322. if (parsedMesh.hasColors) {
  23323. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23324. }
  23325. if (parsedMesh.hasMatricesIndices) {
  23326. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23327. }
  23328. if (parsedMesh.hasMatricesWeights) {
  23329. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23330. }
  23331. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23332. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23333. mesh._checkDelayState();
  23334. }
  23335. }
  23336. else {
  23337. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23338. }
  23339. // Material
  23340. if (parsedMesh.materialId) {
  23341. mesh.setMaterialByID(parsedMesh.materialId);
  23342. }
  23343. else {
  23344. mesh.material = null;
  23345. }
  23346. // Morph targets
  23347. if (parsedMesh.morphTargetManagerId > -1) {
  23348. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23349. }
  23350. // Skeleton
  23351. if (parsedMesh.skeletonId > -1) {
  23352. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23353. if (parsedMesh.numBoneInfluencers) {
  23354. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23355. }
  23356. }
  23357. // Animations
  23358. if (parsedMesh.animations) {
  23359. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23360. var parsedAnimation = parsedMesh.animations[animationIndex];
  23361. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23362. }
  23363. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23364. }
  23365. if (parsedMesh.autoAnimate) {
  23366. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23367. }
  23368. // Layer Mask
  23369. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23370. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23371. }
  23372. else {
  23373. mesh.layerMask = 0x0FFFFFFF;
  23374. }
  23375. // Physics
  23376. if (parsedMesh.physicsImpostor) {
  23377. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23378. mass: parsedMesh.physicsMass,
  23379. friction: parsedMesh.physicsFriction,
  23380. restitution: parsedMesh.physicsRestitution
  23381. }, scene);
  23382. }
  23383. // Instances
  23384. if (parsedMesh.instances) {
  23385. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23386. var parsedInstance = parsedMesh.instances[index];
  23387. var instance = mesh.createInstance(parsedInstance.name);
  23388. if (BABYLON.Tags) {
  23389. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23390. }
  23391. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23392. if (parsedInstance.parentId) {
  23393. instance._waitingParentId = parsedInstance.parentId;
  23394. }
  23395. if (parsedInstance.rotationQuaternion) {
  23396. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23397. }
  23398. else if (parsedInstance.rotation) {
  23399. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23400. }
  23401. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23402. instance.checkCollisions = mesh.checkCollisions;
  23403. if (parsedMesh.animations) {
  23404. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23405. parsedAnimation = parsedMesh.animations[animationIndex];
  23406. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23407. }
  23408. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23409. }
  23410. }
  23411. }
  23412. return mesh;
  23413. };
  23414. /**
  23415. * Creates a ribbon mesh.
  23416. * Please consider using the same method from the MeshBuilder class instead.
  23417. * 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.
  23418. *
  23419. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23420. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23421. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23422. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23423. * 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.
  23424. * 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.
  23425. * 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
  23426. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23427. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23428. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23429. */
  23430. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23431. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23432. pathArray: pathArray,
  23433. closeArray: closeArray,
  23434. closePath: closePath,
  23435. offset: offset,
  23436. updatable: updatable,
  23437. sideOrientation: sideOrientation,
  23438. instance: instance
  23439. }, scene);
  23440. };
  23441. /**
  23442. * Creates a plane polygonal mesh. By default, this is a disc.
  23443. * Please consider using the same method from the MeshBuilder class instead.
  23444. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23445. * 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.
  23446. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23447. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23449. */
  23450. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23451. var options = {
  23452. radius: radius,
  23453. tessellation: tessellation,
  23454. sideOrientation: sideOrientation,
  23455. updatable: updatable
  23456. };
  23457. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23458. };
  23459. /**
  23460. * Creates a box mesh.
  23461. * Please consider using the same method from the MeshBuilder class instead.
  23462. * The parameter `size` sets the size (float) of each box side (default 1).
  23463. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23464. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23466. */
  23467. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23468. var options = {
  23469. size: size,
  23470. sideOrientation: sideOrientation,
  23471. updatable: updatable
  23472. };
  23473. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23474. };
  23475. /**
  23476. * Creates a sphere mesh.
  23477. * Please consider using the same method from the MeshBuilder class instead.
  23478. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23479. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23480. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23481. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23482. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23483. */
  23484. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23485. var options = {
  23486. segments: segments,
  23487. diameterX: diameter,
  23488. diameterY: diameter,
  23489. diameterZ: diameter,
  23490. sideOrientation: sideOrientation,
  23491. updatable: updatable
  23492. };
  23493. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23494. };
  23495. /**
  23496. * Creates a cylinder or a cone mesh.
  23497. * Please consider using the same method from the MeshBuilder class instead.
  23498. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23499. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23500. * 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.
  23501. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23502. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23503. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23504. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23506. */
  23507. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23508. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23509. if (scene !== undefined) {
  23510. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23511. updatable = scene;
  23512. }
  23513. scene = subdivisions;
  23514. subdivisions = 1;
  23515. }
  23516. var options = {
  23517. height: height,
  23518. diameterTop: diameterTop,
  23519. diameterBottom: diameterBottom,
  23520. tessellation: tessellation,
  23521. subdivisions: subdivisions,
  23522. sideOrientation: sideOrientation,
  23523. updatable: updatable
  23524. };
  23525. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23526. };
  23527. // Torus (Code from SharpDX.org)
  23528. /**
  23529. * Creates a torus mesh.
  23530. * Please consider using the same method from the MeshBuilder class instead.
  23531. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23532. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23533. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23537. */
  23538. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23539. var options = {
  23540. diameter: diameter,
  23541. thickness: thickness,
  23542. tessellation: tessellation,
  23543. sideOrientation: sideOrientation,
  23544. updatable: updatable
  23545. };
  23546. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23547. };
  23548. /**
  23549. * Creates a torus knot mesh.
  23550. * Please consider using the same method from the MeshBuilder class instead.
  23551. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23552. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23553. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23554. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23555. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23556. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23558. */
  23559. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23560. var options = {
  23561. radius: radius,
  23562. tube: tube,
  23563. radialSegments: radialSegments,
  23564. tubularSegments: tubularSegments,
  23565. p: p,
  23566. q: q,
  23567. sideOrientation: sideOrientation,
  23568. updatable: updatable
  23569. };
  23570. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23571. };
  23572. /**
  23573. * Creates a line mesh.
  23574. * Please consider using the same method from the MeshBuilder class instead.
  23575. * 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.
  23576. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23577. * The parameter `points` is an array successive Vector3.
  23578. * 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
  23579. * When updating an instance, remember that only point positions can change, not the number of points.
  23580. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23581. */
  23582. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23583. var options = {
  23584. points: points,
  23585. updatable: updatable,
  23586. instance: instance
  23587. };
  23588. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23589. };
  23590. /**
  23591. * Creates a dashed line mesh.
  23592. * Please consider using the same method from the MeshBuilder class instead.
  23593. * 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.
  23594. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23595. * The parameter `points` is an array successive Vector3.
  23596. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23597. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23598. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23599. * 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
  23600. * When updating an instance, remember that only point positions can change, not the number of points.
  23601. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23602. */
  23603. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23604. var options = {
  23605. points: points,
  23606. dashSize: dashSize,
  23607. gapSize: gapSize,
  23608. dashNb: dashNb,
  23609. updatable: updatable,
  23610. instance: instance
  23611. };
  23612. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23613. };
  23614. /**
  23615. * Creates a polygon mesh.
  23616. * Please consider using the same method from the MeshBuilder class instead.
  23617. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23618. * 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.
  23619. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23621. * Remember you can only change the shape positions, not their number when updating a polygon.
  23622. */
  23623. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23624. var options = {
  23625. shape: shape,
  23626. holes: holes,
  23627. updatable: updatable,
  23628. sideOrientation: sideOrientation
  23629. };
  23630. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23631. };
  23632. /**
  23633. * Creates an extruded polygon mesh, with depth in the Y direction.
  23634. * Please consider using the same method from the MeshBuilder class instead.
  23635. */
  23636. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23637. var options = {
  23638. shape: shape,
  23639. holes: holes,
  23640. depth: depth,
  23641. updatable: updatable,
  23642. sideOrientation: sideOrientation
  23643. };
  23644. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23645. };
  23646. /**
  23647. * Creates an extruded shape mesh.
  23648. * 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.
  23649. * Please consider using the same method from the MeshBuilder class instead.
  23650. *
  23651. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23652. * 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
  23653. * extruded along the Z axis.
  23654. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23655. * 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.
  23656. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23657. * 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
  23658. * 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
  23659. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23661. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23663. */
  23664. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23665. var options = {
  23666. shape: shape,
  23667. path: path,
  23668. scale: scale,
  23669. rotation: rotation,
  23670. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23671. sideOrientation: sideOrientation,
  23672. instance: instance,
  23673. updatable: updatable
  23674. };
  23675. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23676. };
  23677. /**
  23678. * Creates an custom extruded shape mesh.
  23679. * 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.
  23680. * Please consider using the same method from the MeshBuilder class instead.
  23681. *
  23682. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23683. * 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
  23684. * extruded along the Z axis.
  23685. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23686. * 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
  23687. * and the distance of this point from the begining of the path :
  23688. * ```javascript
  23689. * var rotationFunction = function(i, distance) {
  23690. * // do things
  23691. * return rotationValue; }
  23692. * ```
  23693. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23694. * 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
  23695. * and the distance of this point from the begining of the path :
  23696. * ```javascript
  23697. * var scaleFunction = function(i, distance) {
  23698. * // do things
  23699. * return scaleValue;}
  23700. * ```
  23701. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23702. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23703. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23704. * 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
  23705. * 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
  23706. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23708. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23710. */
  23711. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23712. var options = {
  23713. shape: shape,
  23714. path: path,
  23715. scaleFunction: scaleFunction,
  23716. rotationFunction: rotationFunction,
  23717. ribbonCloseArray: ribbonCloseArray,
  23718. ribbonClosePath: ribbonClosePath,
  23719. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23720. sideOrientation: sideOrientation,
  23721. instance: instance,
  23722. updatable: updatable
  23723. };
  23724. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23725. };
  23726. /**
  23727. * Creates lathe mesh.
  23728. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23729. * Please consider using the same method from the MeshBuilder class instead.
  23730. * 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
  23731. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23732. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23733. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23734. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23735. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23737. */
  23738. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23739. var options = {
  23740. shape: shape,
  23741. radius: radius,
  23742. tessellation: tessellation,
  23743. sideOrientation: sideOrientation,
  23744. updatable: updatable
  23745. };
  23746. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23747. };
  23748. /**
  23749. * Creates a plane mesh.
  23750. * Please consider using the same method from the MeshBuilder class instead.
  23751. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23752. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23753. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23754. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23755. */
  23756. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23757. var options = {
  23758. size: size,
  23759. width: size,
  23760. height: size,
  23761. sideOrientation: sideOrientation,
  23762. updatable: updatable
  23763. };
  23764. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23765. };
  23766. /**
  23767. * Creates a ground mesh.
  23768. * Please consider using the same method from the MeshBuilder class instead.
  23769. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23770. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23772. */
  23773. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23774. var options = {
  23775. width: width,
  23776. height: height,
  23777. subdivisions: subdivisions,
  23778. updatable: updatable
  23779. };
  23780. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23781. };
  23782. /**
  23783. * Creates a tiled ground mesh.
  23784. * Please consider using the same method from the MeshBuilder class instead.
  23785. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23786. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23787. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23788. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23789. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23790. * numbers of subdivisions on the ground width and height of each tile.
  23791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23792. */
  23793. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23794. var options = {
  23795. xmin: xmin,
  23796. zmin: zmin,
  23797. xmax: xmax,
  23798. zmax: zmax,
  23799. subdivisions: subdivisions,
  23800. precision: precision,
  23801. updatable: updatable
  23802. };
  23803. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23804. };
  23805. /**
  23806. * Creates a ground mesh from a height map.
  23807. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23808. * Please consider using the same method from the MeshBuilder class instead.
  23809. * The parameter `url` sets the URL of the height map image resource.
  23810. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23811. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23812. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23813. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23814. * 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).
  23815. * This function is passed the newly built mesh :
  23816. * ```javascript
  23817. * function(mesh) { // do things
  23818. * return; }
  23819. * ```
  23820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23821. */
  23822. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23823. var options = {
  23824. width: width,
  23825. height: height,
  23826. subdivisions: subdivisions,
  23827. minHeight: minHeight,
  23828. maxHeight: maxHeight,
  23829. updatable: updatable,
  23830. onReady: onReady
  23831. };
  23832. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23833. };
  23834. /**
  23835. * Creates a tube mesh.
  23836. * 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.
  23837. * Please consider using the same method from the MeshBuilder class instead.
  23838. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23839. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23840. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23841. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23842. * 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.
  23843. * It must return a radius value (positive float) :
  23844. * ```javascript
  23845. * var radiusFunction = function(i, distance) {
  23846. * // do things
  23847. * return radius; }
  23848. * ```
  23849. * 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
  23850. * 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
  23851. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23852. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23854. */
  23855. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23856. var options = {
  23857. path: path,
  23858. radius: radius,
  23859. tessellation: tessellation,
  23860. radiusFunction: radiusFunction,
  23861. arc: 1,
  23862. cap: cap,
  23863. updatable: updatable,
  23864. sideOrientation: sideOrientation,
  23865. instance: instance
  23866. };
  23867. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23868. };
  23869. /**
  23870. * Creates a polyhedron mesh.
  23871. * Please consider using the same method from the MeshBuilder class instead.
  23872. * 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
  23873. * to choose the wanted type.
  23874. * The parameter `size` (positive float, default 1) sets the polygon size.
  23875. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23876. * 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`.
  23877. * 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
  23878. * 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)`).
  23879. * 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
  23880. * 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.
  23881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23882. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23884. */
  23885. Mesh.CreatePolyhedron = function (name, options, scene) {
  23886. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23887. };
  23888. /**
  23889. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23890. * Please consider using the same method from the MeshBuilder class instead.
  23891. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23892. * 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`).
  23893. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23894. * 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.
  23895. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23896. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23898. */
  23899. Mesh.CreateIcoSphere = function (name, options, scene) {
  23900. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23901. };
  23902. /**
  23903. * Creates a decal mesh.
  23904. * Please consider using the same method from the MeshBuilder class instead.
  23905. * 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.
  23906. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23907. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23908. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23909. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23910. */
  23911. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23912. var options = {
  23913. position: position,
  23914. normal: normal,
  23915. size: size,
  23916. angle: angle
  23917. };
  23918. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23919. };
  23920. // Skeletons
  23921. /**
  23922. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23923. */
  23924. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23925. var source;
  23926. if (!this._sourcePositions) {
  23927. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23928. this._sourcePositions = new Float32Array(source);
  23929. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23930. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23931. }
  23932. }
  23933. return this._sourcePositions;
  23934. };
  23935. /**
  23936. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23937. */
  23938. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23939. var source;
  23940. if (!this._sourceNormals) {
  23941. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23942. this._sourceNormals = new Float32Array(source);
  23943. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23944. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23945. }
  23946. }
  23947. return this._sourceNormals;
  23948. };
  23949. /**
  23950. * Updates the vertex buffer by applying transformation from the bones.
  23951. * Returns the Mesh.
  23952. *
  23953. * @param {skeleton} skeleton to apply
  23954. */
  23955. Mesh.prototype.applySkeleton = function (skeleton) {
  23956. if (!this.geometry) {
  23957. return this;
  23958. }
  23959. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23960. return this;
  23961. }
  23962. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23963. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23964. return this;
  23965. }
  23966. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23967. return this;
  23968. }
  23969. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23970. return this;
  23971. }
  23972. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23973. return this;
  23974. }
  23975. if (!this._sourcePositions) {
  23976. var submeshes = this.subMeshes.slice();
  23977. this.setPositionsForCPUSkinning();
  23978. this.subMeshes = submeshes;
  23979. }
  23980. if (!this._sourceNormals) {
  23981. this.setNormalsForCPUSkinning();
  23982. }
  23983. // positionsData checks for not being Float32Array will only pass at most once
  23984. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23985. if (!(positionsData instanceof Float32Array)) {
  23986. positionsData = new Float32Array(positionsData);
  23987. }
  23988. // normalsData checks for not being Float32Array will only pass at most once
  23989. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23990. if (!(normalsData instanceof Float32Array)) {
  23991. normalsData = new Float32Array(normalsData);
  23992. }
  23993. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23994. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23995. var needExtras = this.numBoneInfluencers > 4;
  23996. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23997. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23998. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23999. var tempVector3 = BABYLON.Vector3.Zero();
  24000. var finalMatrix = new BABYLON.Matrix();
  24001. var tempMatrix = new BABYLON.Matrix();
  24002. var matWeightIdx = 0;
  24003. var inf;
  24004. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24005. var weight;
  24006. for (inf = 0; inf < 4; inf++) {
  24007. weight = matricesWeightsData[matWeightIdx + inf];
  24008. if (weight > 0) {
  24009. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24010. finalMatrix.addToSelf(tempMatrix);
  24011. }
  24012. else
  24013. break;
  24014. }
  24015. if (needExtras) {
  24016. for (inf = 0; inf < 4; inf++) {
  24017. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24018. if (weight > 0) {
  24019. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24020. finalMatrix.addToSelf(tempMatrix);
  24021. }
  24022. else
  24023. break;
  24024. }
  24025. }
  24026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24027. tempVector3.toArray(positionsData, index);
  24028. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24029. tempVector3.toArray(normalsData, index);
  24030. finalMatrix.reset();
  24031. }
  24032. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24033. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24034. return this;
  24035. };
  24036. // Tools
  24037. /**
  24038. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24039. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24040. */
  24041. Mesh.MinMax = function (meshes) {
  24042. var minVector = null;
  24043. var maxVector = null;
  24044. meshes.forEach(function (mesh, index, array) {
  24045. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24046. if (!minVector) {
  24047. minVector = boundingBox.minimumWorld;
  24048. maxVector = boundingBox.maximumWorld;
  24049. }
  24050. else {
  24051. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24052. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24053. }
  24054. });
  24055. return {
  24056. min: minVector,
  24057. max: maxVector
  24058. };
  24059. };
  24060. /**
  24061. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24062. */
  24063. Mesh.Center = function (meshesOrMinMaxVector) {
  24064. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24065. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24066. };
  24067. /**
  24068. * Merge the array of meshes into a single mesh for performance reasons.
  24069. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24070. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24071. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24072. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24073. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24074. */
  24075. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24076. if (disposeSource === void 0) { disposeSource = true; }
  24077. var index;
  24078. if (!allow32BitsIndices) {
  24079. var totalVertices = 0;
  24080. // Counting vertices
  24081. for (index = 0; index < meshes.length; index++) {
  24082. if (meshes[index]) {
  24083. totalVertices += meshes[index].getTotalVertices();
  24084. if (totalVertices > 65536) {
  24085. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24086. return null;
  24087. }
  24088. }
  24089. }
  24090. }
  24091. // Merge
  24092. var vertexData;
  24093. var otherVertexData;
  24094. var indiceArray = new Array();
  24095. var source;
  24096. for (index = 0; index < meshes.length; index++) {
  24097. if (meshes[index]) {
  24098. meshes[index].computeWorldMatrix(true);
  24099. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24100. otherVertexData.transform(meshes[index].getWorldMatrix());
  24101. if (vertexData) {
  24102. vertexData.merge(otherVertexData);
  24103. }
  24104. else {
  24105. vertexData = otherVertexData;
  24106. source = meshes[index];
  24107. }
  24108. if (subdivideWithSubMeshes) {
  24109. indiceArray.push(meshes[index].getTotalIndices());
  24110. }
  24111. }
  24112. }
  24113. if (!meshSubclass) {
  24114. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24115. }
  24116. vertexData.applyToMesh(meshSubclass);
  24117. // Setting properties
  24118. meshSubclass.material = source.material;
  24119. meshSubclass.checkCollisions = source.checkCollisions;
  24120. // Cleaning
  24121. if (disposeSource) {
  24122. for (index = 0; index < meshes.length; index++) {
  24123. if (meshes[index]) {
  24124. meshes[index].dispose();
  24125. }
  24126. }
  24127. }
  24128. // Subdivide
  24129. if (subdivideWithSubMeshes) {
  24130. //-- Suppresions du submesh global
  24131. meshSubclass.releaseSubMeshes();
  24132. index = 0;
  24133. var offset = 0;
  24134. //-- aplique la subdivision en fonction du tableau d'indices
  24135. while (index < indiceArray.length) {
  24136. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24137. offset += indiceArray[index];
  24138. index++;
  24139. }
  24140. }
  24141. return meshSubclass;
  24142. };
  24143. // Consts
  24144. Mesh._FRONTSIDE = 0;
  24145. Mesh._BACKSIDE = 1;
  24146. Mesh._DOUBLESIDE = 2;
  24147. Mesh._DEFAULTSIDE = 0;
  24148. Mesh._NO_CAP = 0;
  24149. Mesh._CAP_START = 1;
  24150. Mesh._CAP_END = 2;
  24151. Mesh._CAP_ALL = 3;
  24152. return Mesh;
  24153. }(BABYLON.AbstractMesh));
  24154. BABYLON.Mesh = Mesh;
  24155. })(BABYLON || (BABYLON = {}));
  24156. //# sourceMappingURL=babylon.mesh.js.map
  24157. var BABYLON;
  24158. (function (BABYLON) {
  24159. var BaseSubMesh = (function () {
  24160. function BaseSubMesh() {
  24161. }
  24162. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24163. get: function () {
  24164. return this._materialEffect;
  24165. },
  24166. enumerable: true,
  24167. configurable: true
  24168. });
  24169. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24170. if (this._materialEffect === effect) {
  24171. if (!effect) {
  24172. this._materialDefines = undefined;
  24173. }
  24174. return;
  24175. }
  24176. this._materialDefines = defines;
  24177. this._materialEffect = effect;
  24178. };
  24179. return BaseSubMesh;
  24180. }());
  24181. BABYLON.BaseSubMesh = BaseSubMesh;
  24182. var SubMesh = (function (_super) {
  24183. __extends(SubMesh, _super);
  24184. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24185. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24186. var _this = _super.call(this) || this;
  24187. _this.materialIndex = materialIndex;
  24188. _this.verticesStart = verticesStart;
  24189. _this.verticesCount = verticesCount;
  24190. _this.indexStart = indexStart;
  24191. _this.indexCount = indexCount;
  24192. _this._renderId = 0;
  24193. _this._mesh = mesh;
  24194. _this._renderingMesh = renderingMesh || mesh;
  24195. mesh.subMeshes.push(_this);
  24196. _this._trianglePlanes = [];
  24197. _this._id = mesh.subMeshes.length - 1;
  24198. if (createBoundingBox) {
  24199. _this.refreshBoundingInfo();
  24200. mesh.computeWorldMatrix(true);
  24201. }
  24202. return _this;
  24203. }
  24204. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24205. get: function () {
  24206. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24207. },
  24208. enumerable: true,
  24209. configurable: true
  24210. });
  24211. /**
  24212. * Returns the submesh BoudingInfo object.
  24213. */
  24214. SubMesh.prototype.getBoundingInfo = function () {
  24215. if (this.IsGlobal) {
  24216. return this._mesh.getBoundingInfo();
  24217. }
  24218. return this._boundingInfo;
  24219. };
  24220. /**
  24221. * Sets the submesh BoundingInfo.
  24222. * Return the SubMesh.
  24223. */
  24224. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24225. this._boundingInfo = boundingInfo;
  24226. return this;
  24227. };
  24228. /**
  24229. * Returns the mesh of the current submesh.
  24230. */
  24231. SubMesh.prototype.getMesh = function () {
  24232. return this._mesh;
  24233. };
  24234. /**
  24235. * Returns the rendering mesh of the submesh.
  24236. */
  24237. SubMesh.prototype.getRenderingMesh = function () {
  24238. return this._renderingMesh;
  24239. };
  24240. /**
  24241. * Returns the submesh material.
  24242. */
  24243. SubMesh.prototype.getMaterial = function () {
  24244. var rootMaterial = this._renderingMesh.material;
  24245. if (rootMaterial && rootMaterial.getSubMaterial) {
  24246. var multiMaterial = rootMaterial;
  24247. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24248. if (this._currentMaterial !== effectiveMaterial) {
  24249. this._currentMaterial = effectiveMaterial;
  24250. this._materialDefines = undefined;
  24251. }
  24252. return effectiveMaterial;
  24253. }
  24254. if (!rootMaterial) {
  24255. return this._mesh.getScene().defaultMaterial;
  24256. }
  24257. return rootMaterial;
  24258. };
  24259. // Methods
  24260. /**
  24261. * Sets a new updated BoundingInfo object to the submesh.
  24262. * Returns the SubMesh.
  24263. */
  24264. SubMesh.prototype.refreshBoundingInfo = function () {
  24265. this._lastColliderWorldVertices = null;
  24266. if (this.IsGlobal) {
  24267. return;
  24268. }
  24269. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24270. if (!data) {
  24271. this._boundingInfo = this._mesh._boundingInfo;
  24272. return;
  24273. }
  24274. var indices = this._renderingMesh.getIndices();
  24275. var extend;
  24276. //is this the only submesh?
  24277. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24278. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24279. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24280. }
  24281. else {
  24282. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24283. }
  24284. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24285. return this;
  24286. };
  24287. SubMesh.prototype._checkCollision = function (collider) {
  24288. return this.getBoundingInfo()._checkCollision(collider);
  24289. };
  24290. /**
  24291. * Updates the submesh BoundingInfo.
  24292. * Returns the Submesh.
  24293. */
  24294. SubMesh.prototype.updateBoundingInfo = function (world) {
  24295. if (!this.getBoundingInfo()) {
  24296. this.refreshBoundingInfo();
  24297. }
  24298. this.getBoundingInfo().update(world);
  24299. return this;
  24300. };
  24301. /**
  24302. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24303. * Boolean returned.
  24304. */
  24305. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24306. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24307. };
  24308. /**
  24309. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24310. * Boolean returned.
  24311. */
  24312. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24313. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24314. };
  24315. /**
  24316. * Renders the submesh.
  24317. * Returns it.
  24318. */
  24319. SubMesh.prototype.render = function (enableAlphaMode) {
  24320. this._renderingMesh.render(this, enableAlphaMode);
  24321. return this;
  24322. };
  24323. /**
  24324. * Returns a new Index Buffer.
  24325. * Type returned : WebGLBuffer.
  24326. */
  24327. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24328. if (!this._linesIndexBuffer) {
  24329. var linesIndices = [];
  24330. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24331. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24332. }
  24333. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24334. this.linesIndexCount = linesIndices.length;
  24335. }
  24336. return this._linesIndexBuffer;
  24337. };
  24338. /**
  24339. * True is the passed Ray intersects the submesh bounding box.
  24340. * Boolean returned.
  24341. */
  24342. SubMesh.prototype.canIntersects = function (ray) {
  24343. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24344. };
  24345. /**
  24346. * Returns an object IntersectionInfo.
  24347. */
  24348. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24349. var intersectInfo = null;
  24350. // LineMesh first as it's also a Mesh...
  24351. if (this._mesh instanceof BABYLON.LinesMesh) {
  24352. var lineMesh = this._mesh;
  24353. // Line test
  24354. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24355. var p0 = positions[indices[index]];
  24356. var p1 = positions[indices[index + 1]];
  24357. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24358. if (length < 0) {
  24359. continue;
  24360. }
  24361. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24362. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24363. if (fastCheck) {
  24364. break;
  24365. }
  24366. }
  24367. }
  24368. }
  24369. else {
  24370. // Triangles test
  24371. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24372. var p0 = positions[indices[index]];
  24373. var p1 = positions[indices[index + 1]];
  24374. var p2 = positions[indices[index + 2]];
  24375. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24376. if (currentIntersectInfo) {
  24377. if (currentIntersectInfo.distance < 0) {
  24378. continue;
  24379. }
  24380. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24381. intersectInfo = currentIntersectInfo;
  24382. intersectInfo.faceId = index / 3;
  24383. if (fastCheck) {
  24384. break;
  24385. }
  24386. }
  24387. }
  24388. }
  24389. }
  24390. return intersectInfo;
  24391. };
  24392. SubMesh.prototype._rebuild = function () {
  24393. if (this._linesIndexBuffer) {
  24394. this._linesIndexBuffer = null;
  24395. }
  24396. };
  24397. // Clone
  24398. /**
  24399. * Creates a new Submesh from the passed Mesh.
  24400. */
  24401. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24402. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24403. if (!this.IsGlobal) {
  24404. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24405. }
  24406. return result;
  24407. };
  24408. // Dispose
  24409. /**
  24410. * Disposes the Submesh.
  24411. * Returns nothing.
  24412. */
  24413. SubMesh.prototype.dispose = function () {
  24414. if (this._linesIndexBuffer) {
  24415. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24416. this._linesIndexBuffer = null;
  24417. }
  24418. // Remove from mesh
  24419. var index = this._mesh.subMeshes.indexOf(this);
  24420. this._mesh.subMeshes.splice(index, 1);
  24421. };
  24422. // Statics
  24423. /**
  24424. * Creates a new Submesh from the passed parameters :
  24425. * - materialIndex (integer) : the index of the main mesh material.
  24426. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24427. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24428. * - mesh (Mesh) : the main mesh to create the submesh from.
  24429. * - renderingMesh (optional Mesh) : rendering mesh.
  24430. */
  24431. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24432. var minVertexIndex = Number.MAX_VALUE;
  24433. var maxVertexIndex = -Number.MAX_VALUE;
  24434. renderingMesh = renderingMesh || mesh;
  24435. var indices = renderingMesh.getIndices();
  24436. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24437. var vertexIndex = indices[index];
  24438. if (vertexIndex < minVertexIndex)
  24439. minVertexIndex = vertexIndex;
  24440. if (vertexIndex > maxVertexIndex)
  24441. maxVertexIndex = vertexIndex;
  24442. }
  24443. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24444. };
  24445. return SubMesh;
  24446. }(BaseSubMesh));
  24447. BABYLON.SubMesh = SubMesh;
  24448. })(BABYLON || (BABYLON = {}));
  24449. //# sourceMappingURL=babylon.subMesh.js.map
  24450. var BABYLON;
  24451. (function (BABYLON) {
  24452. var EffectFallbacks = (function () {
  24453. function EffectFallbacks() {
  24454. this._defines = {};
  24455. this._currentRank = 32;
  24456. this._maxRank = -1;
  24457. }
  24458. EffectFallbacks.prototype.unBindMesh = function () {
  24459. this._mesh = null;
  24460. };
  24461. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24462. if (!this._defines[rank]) {
  24463. if (rank < this._currentRank) {
  24464. this._currentRank = rank;
  24465. }
  24466. if (rank > this._maxRank) {
  24467. this._maxRank = rank;
  24468. }
  24469. this._defines[rank] = new Array();
  24470. }
  24471. this._defines[rank].push(define);
  24472. };
  24473. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24474. this._meshRank = rank;
  24475. this._mesh = mesh;
  24476. if (rank < this._currentRank) {
  24477. this._currentRank = rank;
  24478. }
  24479. if (rank > this._maxRank) {
  24480. this._maxRank = rank;
  24481. }
  24482. };
  24483. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24484. get: function () {
  24485. return this._currentRank <= this._maxRank;
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24491. // First we try to switch to CPU skinning
  24492. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24493. this._mesh.computeBonesUsingShaders = false;
  24494. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24495. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24496. var scene = this._mesh.getScene();
  24497. for (var index = 0; index < scene.meshes.length; index++) {
  24498. var otherMesh = scene.meshes[index];
  24499. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24500. otherMesh.computeBonesUsingShaders = false;
  24501. }
  24502. }
  24503. }
  24504. else {
  24505. var currentFallbacks = this._defines[this._currentRank];
  24506. if (currentFallbacks) {
  24507. for (var index = 0; index < currentFallbacks.length; index++) {
  24508. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24509. }
  24510. }
  24511. this._currentRank++;
  24512. }
  24513. return currentDefines;
  24514. };
  24515. return EffectFallbacks;
  24516. }());
  24517. BABYLON.EffectFallbacks = EffectFallbacks;
  24518. var EffectCreationOptions = (function () {
  24519. function EffectCreationOptions() {
  24520. }
  24521. return EffectCreationOptions;
  24522. }());
  24523. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24524. var Effect = (function () {
  24525. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24526. var _this = this;
  24527. this.uniqueId = 0;
  24528. this.onCompileObservable = new BABYLON.Observable();
  24529. this.onErrorObservable = new BABYLON.Observable();
  24530. this.onBindObservable = new BABYLON.Observable();
  24531. this._uniformBuffersNames = {};
  24532. this._isReady = false;
  24533. this._compilationError = "";
  24534. this.name = baseName;
  24535. if (attributesNamesOrOptions.attributes) {
  24536. var options = attributesNamesOrOptions;
  24537. this._engine = uniformsNamesOrEngine;
  24538. this._attributesNames = options.attributes;
  24539. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24540. this._samplers = options.samplers;
  24541. this.defines = options.defines;
  24542. this.onError = options.onError;
  24543. this.onCompiled = options.onCompiled;
  24544. this._fallbacks = options.fallbacks;
  24545. this._indexParameters = options.indexParameters;
  24546. if (options.uniformBuffersNames) {
  24547. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24548. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24549. }
  24550. }
  24551. }
  24552. else {
  24553. this._engine = engine;
  24554. this.defines = defines;
  24555. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24556. this._samplers = samplers;
  24557. this._attributesNames = attributesNamesOrOptions;
  24558. this.onError = onError;
  24559. this.onCompiled = onCompiled;
  24560. this._indexParameters = indexParameters;
  24561. this._fallbacks = fallbacks;
  24562. }
  24563. this.uniqueId = Effect._uniqueIdSeed++;
  24564. var vertexSource;
  24565. var fragmentSource;
  24566. if (baseName.vertexElement) {
  24567. vertexSource = document.getElementById(baseName.vertexElement);
  24568. if (!vertexSource) {
  24569. vertexSource = baseName.vertexElement;
  24570. }
  24571. }
  24572. else {
  24573. vertexSource = baseName.vertex || baseName;
  24574. }
  24575. if (baseName.fragmentElement) {
  24576. fragmentSource = document.getElementById(baseName.fragmentElement);
  24577. if (!fragmentSource) {
  24578. fragmentSource = baseName.fragmentElement;
  24579. }
  24580. }
  24581. else {
  24582. fragmentSource = baseName.fragment || baseName;
  24583. }
  24584. this._loadVertexShader(vertexSource, function (vertexCode) {
  24585. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24586. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24587. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24588. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24589. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24590. if (baseName) {
  24591. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  24592. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  24593. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  24594. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  24595. }
  24596. else {
  24597. _this._vertexSourceCode = migratedVertexCode;
  24598. _this._fragmentSourceCode = migratedFragmentCode;
  24599. }
  24600. _this._prepareEffect();
  24601. });
  24602. });
  24603. });
  24604. });
  24605. });
  24606. });
  24607. }
  24608. Object.defineProperty(Effect.prototype, "key", {
  24609. get: function () {
  24610. return this._key;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. // Properties
  24616. Effect.prototype.isReady = function () {
  24617. return this._isReady;
  24618. };
  24619. Effect.prototype.getEngine = function () {
  24620. return this._engine;
  24621. };
  24622. Effect.prototype.getProgram = function () {
  24623. return this._program;
  24624. };
  24625. Effect.prototype.getAttributesNames = function () {
  24626. return this._attributesNames;
  24627. };
  24628. Effect.prototype.getAttributeLocation = function (index) {
  24629. return this._attributes[index];
  24630. };
  24631. Effect.prototype.getAttributeLocationByName = function (name) {
  24632. var index = this._attributesNames.indexOf(name);
  24633. return this._attributes[index];
  24634. };
  24635. Effect.prototype.getAttributesCount = function () {
  24636. return this._attributes.length;
  24637. };
  24638. Effect.prototype.getUniformIndex = function (uniformName) {
  24639. return this._uniformsNames.indexOf(uniformName);
  24640. };
  24641. Effect.prototype.getUniform = function (uniformName) {
  24642. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24643. };
  24644. Effect.prototype.getSamplers = function () {
  24645. return this._samplers;
  24646. };
  24647. Effect.prototype.getCompilationError = function () {
  24648. return this._compilationError;
  24649. };
  24650. // Methods
  24651. Effect.prototype.executeWhenCompiled = function (func) {
  24652. if (this.isReady()) {
  24653. func(this);
  24654. return;
  24655. }
  24656. this.onCompileObservable.add(function (effect) {
  24657. func(effect);
  24658. });
  24659. };
  24660. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24661. // DOM element ?
  24662. if (vertex instanceof HTMLElement) {
  24663. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24664. callback(vertexCode);
  24665. return;
  24666. }
  24667. // Base64 encoded ?
  24668. if (vertex.substr(0, 7) === "base64:") {
  24669. var vertexBinary = window.atob(vertex.substr(7));
  24670. callback(vertexBinary);
  24671. return;
  24672. }
  24673. // Is in local store ?
  24674. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24675. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24676. return;
  24677. }
  24678. var vertexShaderUrl;
  24679. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24680. vertexShaderUrl = vertex;
  24681. }
  24682. else {
  24683. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24684. }
  24685. // Vertex shader
  24686. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24687. };
  24688. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24689. // DOM element ?
  24690. if (fragment instanceof HTMLElement) {
  24691. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24692. callback(fragmentCode);
  24693. return;
  24694. }
  24695. // Base64 encoded ?
  24696. if (fragment.substr(0, 7) === "base64:") {
  24697. var fragmentBinary = window.atob(fragment.substr(7));
  24698. callback(fragmentBinary);
  24699. return;
  24700. }
  24701. // Is in local store ?
  24702. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24703. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24704. return;
  24705. }
  24706. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24707. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24708. return;
  24709. }
  24710. var fragmentShaderUrl;
  24711. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24712. fragmentShaderUrl = fragment;
  24713. }
  24714. else {
  24715. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24716. }
  24717. // Fragment shader
  24718. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24719. };
  24720. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24721. // Rebuild shaders source code
  24722. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24723. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24724. vertexCode = prefix + vertexCode;
  24725. fragmentCode = prefix + fragmentCode;
  24726. // Number lines of shaders source code
  24727. var i = 2;
  24728. var regex = /\n/gm;
  24729. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24730. i = 2;
  24731. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24732. // Dump shaders name and formatted source code
  24733. if (this.name.vertexElement) {
  24734. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24735. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24736. }
  24737. else if (this.name.vertex) {
  24738. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24739. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24740. }
  24741. else {
  24742. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24743. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24744. }
  24745. };
  24746. ;
  24747. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24748. var preparedSourceCode = this._processPrecision(sourceCode);
  24749. if (this._engine.webGLVersion == 1) {
  24750. callback(preparedSourceCode);
  24751. return;
  24752. }
  24753. // Already converted
  24754. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24755. callback(preparedSourceCode.replace("#version 300 es", ""));
  24756. return;
  24757. }
  24758. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24759. // Remove extensions
  24760. // #extension GL_OES_standard_derivatives : enable
  24761. // #extension GL_EXT_shader_texture_lod : enable
  24762. // #extension GL_EXT_frag_depth : enable
  24763. // #extension GL_EXT_draw_buffers : require
  24764. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24765. var result = preparedSourceCode.replace(regex, "");
  24766. // Migrate to GLSL v300
  24767. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24768. result = result.replace(/attribute[ \t]/g, "in ");
  24769. result = result.replace(/[ \t]attribute/g, " in");
  24770. if (isFragment) {
  24771. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  24772. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  24773. result = result.replace(/texture2D\s*\(/g, "texture(");
  24774. result = result.replace(/textureCube\s*\(/g, "texture(");
  24775. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24776. result = result.replace(/gl_FragColor/g, "glFragColor");
  24777. result = result.replace(/gl_FragData/g, "glFragData");
  24778. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  24779. }
  24780. callback(result);
  24781. };
  24782. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24783. var _this = this;
  24784. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24785. var match = regex.exec(sourceCode);
  24786. var returnValue = new String(sourceCode);
  24787. while (match != null) {
  24788. var includeFile = match[1];
  24789. // Uniform declaration
  24790. if (includeFile.indexOf("__decl__") !== -1) {
  24791. includeFile = includeFile.replace(/__decl__/, "");
  24792. if (this._engine.supportsUniformBuffers) {
  24793. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24794. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24795. }
  24796. includeFile = includeFile + "Declaration";
  24797. }
  24798. if (Effect.IncludesShadersStore[includeFile]) {
  24799. // Substitution
  24800. var includeContent = Effect.IncludesShadersStore[includeFile];
  24801. if (match[2]) {
  24802. var splits = match[3].split(",");
  24803. for (var index = 0; index < splits.length; index += 2) {
  24804. var source = new RegExp(splits[index], "g");
  24805. var dest = splits[index + 1];
  24806. includeContent = includeContent.replace(source, dest);
  24807. }
  24808. }
  24809. if (match[4]) {
  24810. var indexString = match[5];
  24811. if (indexString.indexOf("..") !== -1) {
  24812. var indexSplits = indexString.split("..");
  24813. var minIndex = parseInt(indexSplits[0]);
  24814. var maxIndex = parseInt(indexSplits[1]);
  24815. var sourceIncludeContent = includeContent.slice(0);
  24816. includeContent = "";
  24817. if (isNaN(maxIndex)) {
  24818. maxIndex = this._indexParameters[indexSplits[1]];
  24819. }
  24820. for (var i = minIndex; i < maxIndex; i++) {
  24821. if (!this._engine.supportsUniformBuffers) {
  24822. // Ubo replacement
  24823. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24824. return p1 + "{X}";
  24825. });
  24826. }
  24827. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24828. }
  24829. }
  24830. else {
  24831. if (!this._engine.supportsUniformBuffers) {
  24832. // Ubo replacement
  24833. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24834. return p1 + "{X}";
  24835. });
  24836. }
  24837. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24838. }
  24839. }
  24840. // Replace
  24841. returnValue = returnValue.replace(match[0], includeContent);
  24842. }
  24843. else {
  24844. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24845. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24846. Effect.IncludesShadersStore[includeFile] = fileContent;
  24847. _this._processIncludes(returnValue, callback);
  24848. });
  24849. return;
  24850. }
  24851. match = regex.exec(sourceCode);
  24852. }
  24853. callback(returnValue);
  24854. };
  24855. Effect.prototype._processPrecision = function (source) {
  24856. if (source.indexOf("precision highp float") === -1) {
  24857. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24858. source = "precision mediump float;\n" + source;
  24859. }
  24860. else {
  24861. source = "precision highp float;\n" + source;
  24862. }
  24863. }
  24864. else {
  24865. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24866. source = source.replace("precision highp float", "precision mediump float");
  24867. }
  24868. }
  24869. return source;
  24870. };
  24871. Effect.prototype._prepareEffect = function () {
  24872. var attributesNames = this._attributesNames;
  24873. var defines = this.defines;
  24874. var fallbacks = this._fallbacks;
  24875. this._valueCache = {};
  24876. try {
  24877. var engine = this._engine;
  24878. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24879. if (engine.webGLVersion > 1) {
  24880. for (var name in this._uniformBuffersNames) {
  24881. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24882. }
  24883. }
  24884. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24885. this._attributes = engine.getAttributes(this._program, attributesNames);
  24886. var index;
  24887. for (index = 0; index < this._samplers.length; index++) {
  24888. var sampler = this.getUniform(this._samplers[index]);
  24889. if (sampler == null) {
  24890. this._samplers.splice(index, 1);
  24891. index--;
  24892. }
  24893. }
  24894. engine.bindSamplers(this);
  24895. this._compilationError = "";
  24896. this._isReady = true;
  24897. if (this.onCompiled) {
  24898. this.onCompiled(this);
  24899. }
  24900. this.onCompileObservable.notifyObservers(this);
  24901. this.onCompileObservable.clear();
  24902. // Unbind mesh reference in fallbacks
  24903. if (this._fallbacks) {
  24904. this._fallbacks.unBindMesh();
  24905. }
  24906. }
  24907. catch (e) {
  24908. this._compilationError = e.message;
  24909. // Let's go through fallbacks then
  24910. BABYLON.Tools.Error("Unable to compile effect:");
  24911. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24912. return " " + uniform;
  24913. }));
  24914. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24915. return " " + attribute;
  24916. }));
  24917. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24918. BABYLON.Tools.Error("Error: " + this._compilationError);
  24919. if (fallbacks && fallbacks.isMoreFallbacks) {
  24920. BABYLON.Tools.Error("Trying next fallback.");
  24921. this.defines = fallbacks.reduce(this.defines);
  24922. this._prepareEffect();
  24923. }
  24924. else {
  24925. if (this.onError) {
  24926. this.onError(this, this._compilationError);
  24927. }
  24928. this.onErrorObservable.notifyObservers(this);
  24929. this.onErrorObservable.clear();
  24930. // Unbind mesh reference in fallbacks
  24931. if (this._fallbacks) {
  24932. this._fallbacks.unBindMesh();
  24933. }
  24934. }
  24935. }
  24936. };
  24937. Object.defineProperty(Effect.prototype, "isSupported", {
  24938. get: function () {
  24939. return this._compilationError === "";
  24940. },
  24941. enumerable: true,
  24942. configurable: true
  24943. });
  24944. Effect.prototype._bindTexture = function (channel, texture) {
  24945. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24946. };
  24947. Effect.prototype.setTexture = function (channel, texture) {
  24948. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24949. };
  24950. Effect.prototype.setTextureArray = function (channel, textures) {
  24951. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24952. var initialPos = this._samplers.indexOf(channel);
  24953. for (var index = 1; index < textures.length; index++) {
  24954. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24955. }
  24956. }
  24957. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24958. };
  24959. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24960. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24961. };
  24962. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24963. var cache = this._valueCache[uniformName];
  24964. var flag = matrix.updateFlag;
  24965. if (cache !== undefined && cache === flag) {
  24966. return false;
  24967. }
  24968. this._valueCache[uniformName] = flag;
  24969. return true;
  24970. };
  24971. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24972. var cache = this._valueCache[uniformName];
  24973. if (!cache) {
  24974. cache = [x, y];
  24975. this._valueCache[uniformName] = cache;
  24976. return true;
  24977. }
  24978. var changed = false;
  24979. if (cache[0] !== x) {
  24980. cache[0] = x;
  24981. changed = true;
  24982. }
  24983. if (cache[1] !== y) {
  24984. cache[1] = y;
  24985. changed = true;
  24986. }
  24987. return changed;
  24988. };
  24989. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24990. var cache = this._valueCache[uniformName];
  24991. if (!cache) {
  24992. cache = [x, y, z];
  24993. this._valueCache[uniformName] = cache;
  24994. return true;
  24995. }
  24996. var changed = false;
  24997. if (cache[0] !== x) {
  24998. cache[0] = x;
  24999. changed = true;
  25000. }
  25001. if (cache[1] !== y) {
  25002. cache[1] = y;
  25003. changed = true;
  25004. }
  25005. if (cache[2] !== z) {
  25006. cache[2] = z;
  25007. changed = true;
  25008. }
  25009. return changed;
  25010. };
  25011. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25012. var cache = this._valueCache[uniformName];
  25013. if (!cache) {
  25014. cache = [x, y, z, w];
  25015. this._valueCache[uniformName] = cache;
  25016. return true;
  25017. }
  25018. var changed = false;
  25019. if (cache[0] !== x) {
  25020. cache[0] = x;
  25021. changed = true;
  25022. }
  25023. if (cache[1] !== y) {
  25024. cache[1] = y;
  25025. changed = true;
  25026. }
  25027. if (cache[2] !== z) {
  25028. cache[2] = z;
  25029. changed = true;
  25030. }
  25031. if (cache[3] !== w) {
  25032. cache[3] = w;
  25033. changed = true;
  25034. }
  25035. return changed;
  25036. };
  25037. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  25038. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  25039. return;
  25040. }
  25041. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  25042. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  25043. };
  25044. Effect.prototype.bindUniformBlock = function (blockName, index) {
  25045. this._engine.bindUniformBlock(this._program, blockName, index);
  25046. };
  25047. Effect.prototype.setIntArray = function (uniformName, array) {
  25048. this._valueCache[uniformName] = null;
  25049. this._engine.setIntArray(this.getUniform(uniformName), array);
  25050. return this;
  25051. };
  25052. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25053. this._valueCache[uniformName] = null;
  25054. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25055. return this;
  25056. };
  25057. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25058. this._valueCache[uniformName] = null;
  25059. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25060. return this;
  25061. };
  25062. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25063. this._valueCache[uniformName] = null;
  25064. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25065. return this;
  25066. };
  25067. Effect.prototype.setFloatArray = function (uniformName, array) {
  25068. this._valueCache[uniformName] = null;
  25069. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25070. return this;
  25071. };
  25072. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25073. this._valueCache[uniformName] = null;
  25074. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25075. return this;
  25076. };
  25077. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25078. this._valueCache[uniformName] = null;
  25079. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25080. return this;
  25081. };
  25082. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25083. this._valueCache[uniformName] = null;
  25084. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25085. return this;
  25086. };
  25087. Effect.prototype.setArray = function (uniformName, array) {
  25088. this._valueCache[uniformName] = null;
  25089. this._engine.setArray(this.getUniform(uniformName), array);
  25090. return this;
  25091. };
  25092. Effect.prototype.setArray2 = function (uniformName, array) {
  25093. this._valueCache[uniformName] = null;
  25094. this._engine.setArray2(this.getUniform(uniformName), array);
  25095. return this;
  25096. };
  25097. Effect.prototype.setArray3 = function (uniformName, array) {
  25098. this._valueCache[uniformName] = null;
  25099. this._engine.setArray3(this.getUniform(uniformName), array);
  25100. return this;
  25101. };
  25102. Effect.prototype.setArray4 = function (uniformName, array) {
  25103. this._valueCache[uniformName] = null;
  25104. this._engine.setArray4(this.getUniform(uniformName), array);
  25105. return this;
  25106. };
  25107. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25108. if (!matrices) {
  25109. return;
  25110. }
  25111. this._valueCache[uniformName] = null;
  25112. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25113. return this;
  25114. };
  25115. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25116. if (this._cacheMatrix(uniformName, matrix)) {
  25117. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25118. }
  25119. return this;
  25120. };
  25121. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25122. this._valueCache[uniformName] = null;
  25123. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25124. return this;
  25125. };
  25126. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25127. this._valueCache[uniformName] = null;
  25128. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25129. return this;
  25130. };
  25131. Effect.prototype.setFloat = function (uniformName, value) {
  25132. var cache = this._valueCache[uniformName];
  25133. if (cache !== undefined && cache === value)
  25134. return this;
  25135. this._valueCache[uniformName] = value;
  25136. this._engine.setFloat(this.getUniform(uniformName), value);
  25137. return this;
  25138. };
  25139. Effect.prototype.setBool = function (uniformName, bool) {
  25140. var cache = this._valueCache[uniformName];
  25141. if (cache !== undefined && cache === bool)
  25142. return this;
  25143. this._valueCache[uniformName] = bool;
  25144. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25145. return this;
  25146. };
  25147. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25148. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25149. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25150. }
  25151. return this;
  25152. };
  25153. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25154. if (this._cacheFloat2(uniformName, x, y)) {
  25155. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25156. }
  25157. return this;
  25158. };
  25159. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25160. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25161. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25162. }
  25163. return this;
  25164. };
  25165. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25166. if (this._cacheFloat3(uniformName, x, y, z)) {
  25167. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25168. }
  25169. return this;
  25170. };
  25171. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25172. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25173. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25174. }
  25175. return this;
  25176. };
  25177. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25178. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25179. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25180. }
  25181. return this;
  25182. };
  25183. Effect.prototype.setColor3 = function (uniformName, color3) {
  25184. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25185. this._engine.setColor3(this.getUniform(uniformName), color3);
  25186. }
  25187. return this;
  25188. };
  25189. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25190. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25191. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25192. }
  25193. return this;
  25194. };
  25195. Effect.ResetCache = function () {
  25196. Effect._baseCache = {};
  25197. };
  25198. Effect._uniqueIdSeed = 0;
  25199. Effect._baseCache = {};
  25200. // Statics
  25201. Effect.ShadersStore = {};
  25202. Effect.IncludesShadersStore = {};
  25203. return Effect;
  25204. }());
  25205. BABYLON.Effect = Effect;
  25206. })(BABYLON || (BABYLON = {}));
  25207. //# sourceMappingURL=babylon.effect.js.map
  25208. var BABYLON;
  25209. (function (BABYLON) {
  25210. var MaterialHelper = (function () {
  25211. function MaterialHelper() {
  25212. }
  25213. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  25214. defines._needUVs = true;
  25215. defines[key] = true;
  25216. if (texture.getTextureMatrix().isIdentity(true)) {
  25217. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  25218. if (texture.coordinatesIndex === 0) {
  25219. defines["MAINUV1"] = true;
  25220. }
  25221. else {
  25222. defines["MAINUV2"] = true;
  25223. }
  25224. }
  25225. else {
  25226. defines[key + "DIRECTUV"] = 0;
  25227. }
  25228. };
  25229. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  25230. var matrix = texture.getTextureMatrix();
  25231. if (!matrix.isIdentity(true)) {
  25232. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25233. }
  25234. };
  25235. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25236. if (defines._areMiscDirty) {
  25237. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25238. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25239. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25240. }
  25241. };
  25242. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25243. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25244. var changed = false;
  25245. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25246. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25247. changed = true;
  25248. }
  25249. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25250. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25251. changed = true;
  25252. }
  25253. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25254. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25255. changed = true;
  25256. }
  25257. if (defines["INSTANCES"] !== useInstances) {
  25258. defines["INSTANCES"] = useInstances;
  25259. changed = true;
  25260. }
  25261. if (changed) {
  25262. defines.markAsUnprocessed();
  25263. }
  25264. };
  25265. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25266. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25267. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25268. return false;
  25269. }
  25270. defines._normals = defines._needNormals;
  25271. defines._uvs = defines._needUVs;
  25272. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25273. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25274. defines["TANGENT"] = true;
  25275. }
  25276. if (defines._needUVs) {
  25277. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25278. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25279. }
  25280. else {
  25281. defines["UV1"] = false;
  25282. defines["UV2"] = false;
  25283. }
  25284. if (useVertexColor) {
  25285. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25286. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25287. }
  25288. if (useBones) {
  25289. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25290. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25291. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25292. }
  25293. else {
  25294. defines["NUM_BONE_INFLUENCERS"] = 0;
  25295. defines["BonesPerMesh"] = 0;
  25296. }
  25297. }
  25298. if (useMorphTargets) {
  25299. if (mesh.morphTargetManager) {
  25300. var manager = mesh.morphTargetManager;
  25301. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25302. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25303. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25304. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25305. }
  25306. else {
  25307. defines["MORPHTARGETS_TANGENT"] = false;
  25308. defines["MORPHTARGETS_NORMAL"] = false;
  25309. defines["MORPHTARGETS"] = false;
  25310. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25311. }
  25312. }
  25313. return true;
  25314. };
  25315. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25316. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25317. if (disableLighting === void 0) { disableLighting = false; }
  25318. if (!defines._areLightsDirty) {
  25319. return defines._needNormals;
  25320. }
  25321. var lightIndex = 0;
  25322. var needNormals = false;
  25323. var needRebuild = false;
  25324. var lightmapMode = false;
  25325. var shadowEnabled = false;
  25326. var specularEnabled = false;
  25327. if (scene.lightsEnabled && !disableLighting) {
  25328. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25329. var light = _a[_i];
  25330. needNormals = true;
  25331. if (defines["LIGHT" + lightIndex] === undefined) {
  25332. needRebuild = true;
  25333. }
  25334. defines["LIGHT" + lightIndex] = true;
  25335. defines["SPOTLIGHT" + lightIndex] = false;
  25336. defines["HEMILIGHT" + lightIndex] = false;
  25337. defines["POINTLIGHT" + lightIndex] = false;
  25338. defines["DIRLIGHT" + lightIndex] = false;
  25339. var type;
  25340. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25341. type = "SPOTLIGHT" + lightIndex;
  25342. }
  25343. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25344. type = "HEMILIGHT" + lightIndex;
  25345. }
  25346. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25347. type = "POINTLIGHT" + lightIndex;
  25348. }
  25349. else {
  25350. type = "DIRLIGHT" + lightIndex;
  25351. }
  25352. defines[type] = true;
  25353. // Specular
  25354. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25355. specularEnabled = true;
  25356. }
  25357. // Shadows
  25358. defines["SHADOW" + lightIndex] = false;
  25359. defines["SHADOWPCF" + lightIndex] = false;
  25360. defines["SHADOWESM" + lightIndex] = false;
  25361. defines["SHADOWCUBE" + lightIndex] = false;
  25362. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25363. var shadowGenerator = light.getShadowGenerator();
  25364. if (shadowGenerator) {
  25365. shadowEnabled = true;
  25366. shadowGenerator.prepareDefines(defines, lightIndex);
  25367. }
  25368. }
  25369. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25370. lightmapMode = true;
  25371. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25372. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25373. }
  25374. else {
  25375. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25376. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25377. }
  25378. lightIndex++;
  25379. if (lightIndex === maxSimultaneousLights)
  25380. break;
  25381. }
  25382. }
  25383. defines["SPECULARTERM"] = specularEnabled;
  25384. defines["SHADOWS"] = shadowEnabled;
  25385. // Resetting all other lights if any
  25386. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25387. if (defines["LIGHT" + index] !== undefined) {
  25388. defines["LIGHT" + index] = false;
  25389. defines["HEMILIGHT" + lightIndex] = false;
  25390. defines["POINTLIGHT" + lightIndex] = false;
  25391. defines["DIRLIGHT" + lightIndex] = false;
  25392. defines["SPOTLIGHT" + lightIndex] = false;
  25393. defines["SHADOW" + lightIndex] = false;
  25394. }
  25395. }
  25396. var caps = scene.getEngine().getCaps();
  25397. if (defines["SHADOWFLOAT"] === undefined) {
  25398. needRebuild = true;
  25399. }
  25400. defines["SHADOWFLOAT"] = shadowEnabled &&
  25401. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25402. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25403. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25404. if (needRebuild) {
  25405. defines.rebuild();
  25406. }
  25407. return needNormals;
  25408. };
  25409. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25410. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25411. var uniformsList, uniformBuffersList, samplersList, defines;
  25412. if (uniformsListOrOptions.uniformsNames) {
  25413. var options = uniformsListOrOptions;
  25414. uniformsList = options.uniformsNames;
  25415. uniformBuffersList = options.uniformBuffersNames;
  25416. samplersList = options.samplers;
  25417. defines = options.defines;
  25418. maxSimultaneousLights = options.maxSimultaneousLights;
  25419. }
  25420. else {
  25421. uniformsList = uniformsListOrOptions;
  25422. }
  25423. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25424. if (!defines["LIGHT" + lightIndex]) {
  25425. break;
  25426. }
  25427. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25428. if (uniformBuffersList) {
  25429. uniformBuffersList.push("Light" + lightIndex);
  25430. }
  25431. samplersList.push("shadowSampler" + lightIndex);
  25432. }
  25433. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25434. uniformsList.push("morphTargetInfluences");
  25435. }
  25436. };
  25437. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25438. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25439. if (!defines["SHADOWS"]) {
  25440. return;
  25441. }
  25442. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25443. if (!defines["LIGHT" + lightIndex]) {
  25444. break;
  25445. }
  25446. if (lightIndex > 0) {
  25447. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25448. }
  25449. if (defines["SHADOW" + lightIndex]) {
  25450. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25451. }
  25452. if (defines["SHADOWPCF" + lightIndex]) {
  25453. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25454. }
  25455. if (defines["SHADOWESM" + lightIndex]) {
  25456. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25457. }
  25458. }
  25459. };
  25460. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25461. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25462. if (influencers > 0) {
  25463. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25464. var manager = mesh.morphTargetManager;
  25465. var normal = manager.supportsNormals && defines["NORMAL"];
  25466. var tangent = manager.supportsTangents && defines["TANGENT"];
  25467. for (var index = 0; index < influencers; index++) {
  25468. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25469. if (normal) {
  25470. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25471. }
  25472. if (tangent) {
  25473. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25474. }
  25475. if (attribs.length > maxAttributesCount) {
  25476. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25477. }
  25478. }
  25479. }
  25480. };
  25481. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25482. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25483. fallbacks.addCPUSkinningFallback(0, mesh);
  25484. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25485. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25486. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25487. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25488. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25489. }
  25490. }
  25491. };
  25492. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25493. if (defines["INSTANCES"]) {
  25494. attribs.push("world0");
  25495. attribs.push("world1");
  25496. attribs.push("world2");
  25497. attribs.push("world3");
  25498. }
  25499. };
  25500. // Bindings
  25501. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25502. if (light.shadowEnabled && mesh.receiveShadows) {
  25503. var shadowGenerator = light.getShadowGenerator();
  25504. if (shadowGenerator) {
  25505. shadowGenerator.bindShadowLight(lightIndex, effect);
  25506. }
  25507. }
  25508. };
  25509. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25510. light.transferToEffect(effect, lightIndex + "");
  25511. };
  25512. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25513. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25514. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25515. var lightIndex = 0;
  25516. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25517. var light = _a[_i];
  25518. var scaledIntensity = light.getScaledIntensity();
  25519. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25520. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25521. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25522. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25523. if (defines["SPECULARTERM"]) {
  25524. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25525. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25526. }
  25527. // Shadows
  25528. if (scene.shadowsEnabled) {
  25529. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25530. }
  25531. light._uniformBuffer.update();
  25532. lightIndex++;
  25533. if (lightIndex === maxSimultaneousLights)
  25534. break;
  25535. }
  25536. };
  25537. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25538. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25539. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25540. effect.setColor3("vFogColor", scene.fogColor);
  25541. }
  25542. };
  25543. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25544. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25545. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25546. if (matrices) {
  25547. effect.setMatrices("mBones", matrices);
  25548. }
  25549. }
  25550. };
  25551. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25552. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25553. return;
  25554. }
  25555. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25556. };
  25557. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25558. if (defines["LOGARITHMICDEPTH"]) {
  25559. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25560. }
  25561. };
  25562. MaterialHelper.BindClipPlane = function (effect, scene) {
  25563. if (scene.clipPlane) {
  25564. var clipPlane = scene.clipPlane;
  25565. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25566. }
  25567. };
  25568. return MaterialHelper;
  25569. }());
  25570. BABYLON.MaterialHelper = MaterialHelper;
  25571. })(BABYLON || (BABYLON = {}));
  25572. //# sourceMappingURL=babylon.materialHelper.js.map
  25573. var BABYLON;
  25574. (function (BABYLON) {
  25575. var MaterialDefines = (function () {
  25576. function MaterialDefines() {
  25577. this._isDirty = true;
  25578. this._areLightsDirty = true;
  25579. this._areAttributesDirty = true;
  25580. this._areTexturesDirty = true;
  25581. this._areFresnelDirty = true;
  25582. this._areMiscDirty = true;
  25583. this._areImageProcessingDirty = true;
  25584. this._normals = false;
  25585. this._uvs = false;
  25586. this._needNormals = false;
  25587. this._needUVs = false;
  25588. }
  25589. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25590. get: function () {
  25591. return this._isDirty;
  25592. },
  25593. enumerable: true,
  25594. configurable: true
  25595. });
  25596. MaterialDefines.prototype.markAsProcessed = function () {
  25597. this._isDirty = false;
  25598. this._areAttributesDirty = false;
  25599. this._areTexturesDirty = false;
  25600. this._areFresnelDirty = false;
  25601. this._areLightsDirty = false;
  25602. this._areMiscDirty = false;
  25603. this._areImageProcessingDirty = false;
  25604. };
  25605. MaterialDefines.prototype.markAsUnprocessed = function () {
  25606. this._isDirty = true;
  25607. };
  25608. MaterialDefines.prototype.markAllAsDirty = function () {
  25609. this._areTexturesDirty = true;
  25610. this._areAttributesDirty = true;
  25611. this._areLightsDirty = true;
  25612. this._areFresnelDirty = true;
  25613. this._areMiscDirty = true;
  25614. this._areImageProcessingDirty = true;
  25615. this._isDirty = true;
  25616. };
  25617. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25618. this._areImageProcessingDirty = true;
  25619. this._isDirty = true;
  25620. };
  25621. MaterialDefines.prototype.markAsLightDirty = function () {
  25622. this._areLightsDirty = true;
  25623. this._isDirty = true;
  25624. };
  25625. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25626. this._areAttributesDirty = true;
  25627. this._isDirty = true;
  25628. };
  25629. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25630. this._areTexturesDirty = true;
  25631. this._isDirty = true;
  25632. };
  25633. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25634. this._areFresnelDirty = true;
  25635. this._isDirty = true;
  25636. };
  25637. MaterialDefines.prototype.markAsMiscDirty = function () {
  25638. this._areMiscDirty = true;
  25639. this._isDirty = true;
  25640. };
  25641. MaterialDefines.prototype.rebuild = function () {
  25642. if (this._keys) {
  25643. delete this._keys;
  25644. }
  25645. this._keys = [];
  25646. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25647. var key = _a[_i];
  25648. if (key[0] === "_") {
  25649. continue;
  25650. }
  25651. this._keys.push(key);
  25652. }
  25653. };
  25654. MaterialDefines.prototype.isEqual = function (other) {
  25655. if (this._keys.length !== other._keys.length) {
  25656. return false;
  25657. }
  25658. for (var index = 0; index < this._keys.length; index++) {
  25659. var prop = this._keys[index];
  25660. if (this[prop] !== other[prop]) {
  25661. return false;
  25662. }
  25663. }
  25664. return true;
  25665. };
  25666. MaterialDefines.prototype.cloneTo = function (other) {
  25667. if (this._keys.length !== other._keys.length) {
  25668. other._keys = this._keys.slice(0);
  25669. }
  25670. for (var index = 0; index < this._keys.length; index++) {
  25671. var prop = this._keys[index];
  25672. other[prop] = this[prop];
  25673. }
  25674. };
  25675. MaterialDefines.prototype.reset = function () {
  25676. for (var index = 0; index < this._keys.length; index++) {
  25677. var prop = this._keys[index];
  25678. if (typeof (this[prop]) === "number") {
  25679. this[prop] = 0;
  25680. }
  25681. else {
  25682. this[prop] = false;
  25683. }
  25684. }
  25685. };
  25686. MaterialDefines.prototype.toString = function () {
  25687. var result = "";
  25688. for (var index = 0; index < this._keys.length; index++) {
  25689. var prop = this._keys[index];
  25690. var value = this[prop];
  25691. if (typeof (value) === "number") {
  25692. result += "#define " + prop + " " + this[prop] + "\n";
  25693. }
  25694. else if (value) {
  25695. result += "#define " + prop + "\n";
  25696. }
  25697. }
  25698. return result;
  25699. };
  25700. return MaterialDefines;
  25701. }());
  25702. BABYLON.MaterialDefines = MaterialDefines;
  25703. var Material = (function () {
  25704. function Material(name, scene, doNotAdd) {
  25705. this.checkReadyOnEveryCall = false;
  25706. this.checkReadyOnlyOnce = false;
  25707. this.state = "";
  25708. this.alpha = 1.0;
  25709. this._backFaceCulling = true;
  25710. this.doNotSerialize = false;
  25711. this.storeEffectOnSubMeshes = false;
  25712. /**
  25713. * An event triggered when the material is disposed.
  25714. * @type {BABYLON.Observable}
  25715. */
  25716. this.onDisposeObservable = new BABYLON.Observable();
  25717. /**
  25718. * An event triggered when the material is bound.
  25719. * @type {BABYLON.Observable}
  25720. */
  25721. this.onBindObservable = new BABYLON.Observable();
  25722. /**
  25723. * An event triggered when the material is unbound.
  25724. * @type {BABYLON.Observable}
  25725. */
  25726. this.onUnBindObservable = new BABYLON.Observable();
  25727. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25728. this._needDepthPrePass = false;
  25729. this.disableDepthWrite = false;
  25730. this.forceDepthWrite = false;
  25731. this.separateCullingPass = false;
  25732. this._fogEnabled = true;
  25733. this.pointSize = 1.0;
  25734. this.zOffset = 0;
  25735. this._wasPreviouslyReady = false;
  25736. this._fillMode = Material.TriangleFillMode;
  25737. this.name = name;
  25738. this.id = name || BABYLON.Tools.RandomId();
  25739. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25740. if (this._scene.useRightHandedSystem) {
  25741. this.sideOrientation = Material.ClockWiseSideOrientation;
  25742. }
  25743. else {
  25744. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25745. }
  25746. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25747. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25748. if (!doNotAdd) {
  25749. this._scene.materials.push(this);
  25750. }
  25751. }
  25752. Object.defineProperty(Material, "TriangleFillMode", {
  25753. get: function () {
  25754. return Material._TriangleFillMode;
  25755. },
  25756. enumerable: true,
  25757. configurable: true
  25758. });
  25759. Object.defineProperty(Material, "WireFrameFillMode", {
  25760. get: function () {
  25761. return Material._WireFrameFillMode;
  25762. },
  25763. enumerable: true,
  25764. configurable: true
  25765. });
  25766. Object.defineProperty(Material, "PointFillMode", {
  25767. get: function () {
  25768. return Material._PointFillMode;
  25769. },
  25770. enumerable: true,
  25771. configurable: true
  25772. });
  25773. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25774. get: function () {
  25775. return Material._ClockWiseSideOrientation;
  25776. },
  25777. enumerable: true,
  25778. configurable: true
  25779. });
  25780. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25781. get: function () {
  25782. return Material._CounterClockWiseSideOrientation;
  25783. },
  25784. enumerable: true,
  25785. configurable: true
  25786. });
  25787. Object.defineProperty(Material, "TextureDirtyFlag", {
  25788. get: function () {
  25789. return Material._TextureDirtyFlag;
  25790. },
  25791. enumerable: true,
  25792. configurable: true
  25793. });
  25794. Object.defineProperty(Material, "LightDirtyFlag", {
  25795. get: function () {
  25796. return Material._LightDirtyFlag;
  25797. },
  25798. enumerable: true,
  25799. configurable: true
  25800. });
  25801. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25802. get: function () {
  25803. return Material._FresnelDirtyFlag;
  25804. },
  25805. enumerable: true,
  25806. configurable: true
  25807. });
  25808. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25809. get: function () {
  25810. return Material._AttributesDirtyFlag;
  25811. },
  25812. enumerable: true,
  25813. configurable: true
  25814. });
  25815. Object.defineProperty(Material, "MiscDirtyFlag", {
  25816. get: function () {
  25817. return Material._MiscDirtyFlag;
  25818. },
  25819. enumerable: true,
  25820. configurable: true
  25821. });
  25822. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25823. get: function () {
  25824. return this._backFaceCulling;
  25825. },
  25826. set: function (value) {
  25827. if (this._backFaceCulling === value) {
  25828. return;
  25829. }
  25830. this._backFaceCulling = value;
  25831. this.markAsDirty(Material.TextureDirtyFlag);
  25832. },
  25833. enumerable: true,
  25834. configurable: true
  25835. });
  25836. Object.defineProperty(Material.prototype, "onDispose", {
  25837. set: function (callback) {
  25838. if (this._onDisposeObserver) {
  25839. this.onDisposeObservable.remove(this._onDisposeObserver);
  25840. }
  25841. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25842. },
  25843. enumerable: true,
  25844. configurable: true
  25845. });
  25846. Object.defineProperty(Material.prototype, "onBind", {
  25847. set: function (callback) {
  25848. if (this._onBindObserver) {
  25849. this.onBindObservable.remove(this._onBindObserver);
  25850. }
  25851. this._onBindObserver = this.onBindObservable.add(callback);
  25852. },
  25853. enumerable: true,
  25854. configurable: true
  25855. });
  25856. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  25857. get: function () {
  25858. return this._needDepthPrePass;
  25859. },
  25860. set: function (value) {
  25861. if (this._needDepthPrePass === value) {
  25862. return;
  25863. }
  25864. this._needDepthPrePass = value;
  25865. if (this._needDepthPrePass) {
  25866. this.checkReadyOnEveryCall = true;
  25867. }
  25868. },
  25869. enumerable: true,
  25870. configurable: true
  25871. });
  25872. Object.defineProperty(Material.prototype, "fogEnabled", {
  25873. get: function () {
  25874. return this._fogEnabled;
  25875. },
  25876. set: function (value) {
  25877. if (this._fogEnabled === value) {
  25878. return;
  25879. }
  25880. this._fogEnabled = value;
  25881. this.markAsDirty(Material.MiscDirtyFlag);
  25882. },
  25883. enumerable: true,
  25884. configurable: true
  25885. });
  25886. Object.defineProperty(Material.prototype, "wireframe", {
  25887. get: function () {
  25888. return this._fillMode === Material.WireFrameFillMode;
  25889. },
  25890. set: function (value) {
  25891. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25892. },
  25893. enumerable: true,
  25894. configurable: true
  25895. });
  25896. Object.defineProperty(Material.prototype, "pointsCloud", {
  25897. get: function () {
  25898. return this._fillMode === Material.PointFillMode;
  25899. },
  25900. set: function (value) {
  25901. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25902. },
  25903. enumerable: true,
  25904. configurable: true
  25905. });
  25906. Object.defineProperty(Material.prototype, "fillMode", {
  25907. get: function () {
  25908. return this._fillMode;
  25909. },
  25910. set: function (value) {
  25911. if (this._fillMode === value) {
  25912. return;
  25913. }
  25914. this._fillMode = value;
  25915. this.markAsDirty(Material.MiscDirtyFlag);
  25916. },
  25917. enumerable: true,
  25918. configurable: true
  25919. });
  25920. /**
  25921. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25922. * subclasses should override adding information pertainent to themselves
  25923. */
  25924. Material.prototype.toString = function (fullDetails) {
  25925. var ret = "Name: " + this.name;
  25926. if (fullDetails) {
  25927. }
  25928. return ret;
  25929. };
  25930. /**
  25931. * Child classes can use it to update shaders
  25932. */
  25933. Material.prototype.getClassName = function () {
  25934. return "Material";
  25935. };
  25936. Object.defineProperty(Material.prototype, "isFrozen", {
  25937. get: function () {
  25938. return this.checkReadyOnlyOnce;
  25939. },
  25940. enumerable: true,
  25941. configurable: true
  25942. });
  25943. Material.prototype.freeze = function () {
  25944. this.checkReadyOnlyOnce = true;
  25945. };
  25946. Material.prototype.unfreeze = function () {
  25947. this.checkReadyOnlyOnce = false;
  25948. };
  25949. Material.prototype.isReady = function (mesh, useInstances) {
  25950. return true;
  25951. };
  25952. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25953. return false;
  25954. };
  25955. Material.prototype.getEffect = function () {
  25956. return this._effect;
  25957. };
  25958. Material.prototype.getScene = function () {
  25959. return this._scene;
  25960. };
  25961. Material.prototype.needAlphaBlending = function () {
  25962. return (this.alpha < 1.0);
  25963. };
  25964. Material.prototype.needAlphaTesting = function () {
  25965. return false;
  25966. };
  25967. Material.prototype.getAlphaTestTexture = function () {
  25968. return null;
  25969. };
  25970. Material.prototype.markDirty = function () {
  25971. this._wasPreviouslyReady = false;
  25972. };
  25973. Material.prototype._preBind = function (effect, overrideOrientation) {
  25974. var engine = this._scene.getEngine();
  25975. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  25976. var reverse = orientation === Material.ClockWiseSideOrientation;
  25977. engine.enableEffect(effect ? effect : this._effect);
  25978. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25979. return reverse;
  25980. };
  25981. Material.prototype.bind = function (world, mesh) {
  25982. };
  25983. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25984. };
  25985. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25986. };
  25987. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25988. sceneUbo.bindToEffect(effect, "Scene");
  25989. };
  25990. Material.prototype.bindView = function (effect) {
  25991. if (!this._useUBO) {
  25992. effect.setMatrix("view", this.getScene().getViewMatrix());
  25993. }
  25994. else {
  25995. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25996. }
  25997. };
  25998. Material.prototype.bindViewProjection = function (effect) {
  25999. if (!this._useUBO) {
  26000. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26001. }
  26002. else {
  26003. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26004. }
  26005. };
  26006. Material.prototype._afterBind = function (mesh) {
  26007. this._scene._cachedMaterial = this;
  26008. if (mesh) {
  26009. this._scene._cachedVisibility = mesh.visibility;
  26010. }
  26011. else {
  26012. this._scene._cachedVisibility = 1;
  26013. }
  26014. this.onBindObservable.notifyObservers(mesh);
  26015. if (this.disableDepthWrite) {
  26016. var engine = this._scene.getEngine();
  26017. this._cachedDepthWriteState = engine.getDepthWrite();
  26018. engine.setDepthWrite(false);
  26019. }
  26020. };
  26021. Material.prototype.unbind = function () {
  26022. this.onUnBindObservable.notifyObservers(this);
  26023. if (this.disableDepthWrite) {
  26024. var engine = this._scene.getEngine();
  26025. engine.setDepthWrite(this._cachedDepthWriteState);
  26026. }
  26027. };
  26028. Material.prototype.getActiveTextures = function () {
  26029. return [];
  26030. };
  26031. Material.prototype.hasTexture = function (texture) {
  26032. return false;
  26033. };
  26034. Material.prototype.clone = function (name) {
  26035. return null;
  26036. };
  26037. Material.prototype.getBindedMeshes = function () {
  26038. var result = new Array();
  26039. for (var index = 0; index < this._scene.meshes.length; index++) {
  26040. var mesh = this._scene.meshes[index];
  26041. if (mesh.material === this) {
  26042. result.push(mesh);
  26043. }
  26044. }
  26045. return result;
  26046. };
  26047. /**
  26048. * Force shader compilation including textures ready check
  26049. */
  26050. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  26051. var _this = this;
  26052. var subMesh = new BABYLON.BaseSubMesh();
  26053. var scene = this.getScene();
  26054. var engine = scene.getEngine();
  26055. var checkReady = function () {
  26056. if (!_this._scene || !_this._scene.getEngine()) {
  26057. return;
  26058. }
  26059. if (subMesh._materialDefines) {
  26060. subMesh._materialDefines._renderId = -1;
  26061. }
  26062. var alphaTestState = engine.getAlphaTesting();
  26063. var clipPlaneState = scene.clipPlane;
  26064. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  26065. if (options && options.clipPlane) {
  26066. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  26067. }
  26068. if (_this.storeEffectOnSubMeshes) {
  26069. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  26070. if (onCompiled) {
  26071. onCompiled(_this);
  26072. }
  26073. }
  26074. else {
  26075. setTimeout(checkReady, 16);
  26076. }
  26077. }
  26078. else {
  26079. if (_this.isReady(mesh)) {
  26080. if (onCompiled) {
  26081. onCompiled(_this);
  26082. }
  26083. }
  26084. else {
  26085. setTimeout(checkReady, 16);
  26086. }
  26087. }
  26088. engine.setAlphaTesting(alphaTestState);
  26089. if (options && options.clipPlane) {
  26090. scene.clipPlane = clipPlaneState;
  26091. }
  26092. };
  26093. checkReady();
  26094. };
  26095. Material.prototype.markAsDirty = function (flag) {
  26096. if (flag & Material.TextureDirtyFlag) {
  26097. this._markAllSubMeshesAsTexturesDirty();
  26098. }
  26099. if (flag & Material.LightDirtyFlag) {
  26100. this._markAllSubMeshesAsLightsDirty();
  26101. }
  26102. if (flag & Material.FresnelDirtyFlag) {
  26103. this._markAllSubMeshesAsFresnelDirty();
  26104. }
  26105. if (flag & Material.AttributesDirtyFlag) {
  26106. this._markAllSubMeshesAsAttributesDirty();
  26107. }
  26108. if (flag & Material.MiscDirtyFlag) {
  26109. this._markAllSubMeshesAsMiscDirty();
  26110. }
  26111. this.getScene().resetCachedMaterial();
  26112. };
  26113. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  26114. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  26115. var mesh = _a[_i];
  26116. if (!mesh.subMeshes) {
  26117. continue;
  26118. }
  26119. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26120. var subMesh = _c[_b];
  26121. if (subMesh.getMaterial() !== this) {
  26122. continue;
  26123. }
  26124. if (!subMesh._materialDefines) {
  26125. continue;
  26126. }
  26127. func(subMesh._materialDefines);
  26128. }
  26129. }
  26130. };
  26131. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  26132. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  26133. };
  26134. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  26135. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  26136. };
  26137. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  26138. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  26139. };
  26140. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  26141. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  26142. };
  26143. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  26144. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  26145. };
  26146. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  26147. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  26148. };
  26149. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26150. // Animations
  26151. this.getScene().stopAnimation(this);
  26152. // Remove from scene
  26153. var index = this._scene.materials.indexOf(this);
  26154. if (index >= 0) {
  26155. this._scene.materials.splice(index, 1);
  26156. }
  26157. // Remove from meshes
  26158. for (index = 0; index < this._scene.meshes.length; index++) {
  26159. var mesh = this._scene.meshes[index];
  26160. if (mesh.material === this) {
  26161. mesh.material = null;
  26162. if (mesh.geometry) {
  26163. var geometry = mesh.geometry;
  26164. if (this.storeEffectOnSubMeshes) {
  26165. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  26166. var subMesh = _a[_i];
  26167. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  26168. }
  26169. }
  26170. else {
  26171. geometry._releaseVertexArrayObject(this._effect);
  26172. }
  26173. }
  26174. }
  26175. }
  26176. this._uniformBuffer.dispose();
  26177. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26178. if (forceDisposeEffect && this._effect) {
  26179. if (this.storeEffectOnSubMeshes) {
  26180. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26181. var subMesh = _c[_b];
  26182. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  26183. }
  26184. }
  26185. else {
  26186. this._scene.getEngine()._releaseEffect(this._effect);
  26187. }
  26188. this._effect = null;
  26189. }
  26190. // Callback
  26191. this.onDisposeObservable.notifyObservers(this);
  26192. this.onDisposeObservable.clear();
  26193. this.onBindObservable.clear();
  26194. this.onUnBindObservable.clear();
  26195. };
  26196. Material.prototype.serialize = function () {
  26197. return BABYLON.SerializationHelper.Serialize(this);
  26198. };
  26199. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26200. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26201. multiMaterial.id = parsedMultiMaterial.id;
  26202. if (BABYLON.Tags) {
  26203. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26204. }
  26205. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26206. var subMatId = parsedMultiMaterial.materials[matIndex];
  26207. if (subMatId) {
  26208. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26209. }
  26210. else {
  26211. multiMaterial.subMaterials.push(null);
  26212. }
  26213. }
  26214. return multiMaterial;
  26215. };
  26216. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26217. if (!parsedMaterial.customType) {
  26218. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26219. }
  26220. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  26221. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  26222. if (!BABYLON.LegacyPBRMaterial) {
  26223. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  26224. return;
  26225. }
  26226. }
  26227. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26228. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26229. ;
  26230. };
  26231. Material._TriangleFillMode = 0;
  26232. Material._WireFrameFillMode = 1;
  26233. Material._PointFillMode = 2;
  26234. Material._ClockWiseSideOrientation = 0;
  26235. Material._CounterClockWiseSideOrientation = 1;
  26236. Material._TextureDirtyFlag = 1;
  26237. Material._LightDirtyFlag = 2;
  26238. Material._FresnelDirtyFlag = 4;
  26239. Material._AttributesDirtyFlag = 8;
  26240. Material._MiscDirtyFlag = 16;
  26241. __decorate([
  26242. BABYLON.serialize()
  26243. ], Material.prototype, "id", void 0);
  26244. __decorate([
  26245. BABYLON.serialize()
  26246. ], Material.prototype, "name", void 0);
  26247. __decorate([
  26248. BABYLON.serialize()
  26249. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26250. __decorate([
  26251. BABYLON.serialize()
  26252. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26253. __decorate([
  26254. BABYLON.serialize()
  26255. ], Material.prototype, "state", void 0);
  26256. __decorate([
  26257. BABYLON.serialize()
  26258. ], Material.prototype, "alpha", void 0);
  26259. __decorate([
  26260. BABYLON.serialize("backFaceCulling")
  26261. ], Material.prototype, "_backFaceCulling", void 0);
  26262. __decorate([
  26263. BABYLON.serialize()
  26264. ], Material.prototype, "sideOrientation", void 0);
  26265. __decorate([
  26266. BABYLON.serialize()
  26267. ], Material.prototype, "alphaMode", void 0);
  26268. __decorate([
  26269. BABYLON.serialize()
  26270. ], Material.prototype, "_needDepthPrePass", void 0);
  26271. __decorate([
  26272. BABYLON.serialize()
  26273. ], Material.prototype, "disableDepthWrite", void 0);
  26274. __decorate([
  26275. BABYLON.serialize()
  26276. ], Material.prototype, "forceDepthWrite", void 0);
  26277. __decorate([
  26278. BABYLON.serialize()
  26279. ], Material.prototype, "separateCullingPass", void 0);
  26280. __decorate([
  26281. BABYLON.serialize("fogEnabled")
  26282. ], Material.prototype, "_fogEnabled", void 0);
  26283. __decorate([
  26284. BABYLON.serialize()
  26285. ], Material.prototype, "pointSize", void 0);
  26286. __decorate([
  26287. BABYLON.serialize()
  26288. ], Material.prototype, "zOffset", void 0);
  26289. __decorate([
  26290. BABYLON.serialize()
  26291. ], Material.prototype, "wireframe", null);
  26292. __decorate([
  26293. BABYLON.serialize()
  26294. ], Material.prototype, "pointsCloud", null);
  26295. __decorate([
  26296. BABYLON.serialize()
  26297. ], Material.prototype, "fillMode", null);
  26298. return Material;
  26299. }());
  26300. BABYLON.Material = Material;
  26301. })(BABYLON || (BABYLON = {}));
  26302. //# sourceMappingURL=babylon.material.js.map
  26303. var BABYLON;
  26304. (function (BABYLON) {
  26305. var UniformBuffer = (function () {
  26306. /**
  26307. * Uniform buffer objects.
  26308. *
  26309. * Handles blocks of uniform on the GPU.
  26310. *
  26311. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26312. *
  26313. * For more information, please refer to :
  26314. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26315. */
  26316. function UniformBuffer(engine, data, dynamic) {
  26317. this._engine = engine;
  26318. this._noUBO = !engine.supportsUniformBuffers;
  26319. this._dynamic = dynamic;
  26320. this._data = data || [];
  26321. this._uniformLocations = {};
  26322. this._uniformSizes = {};
  26323. this._uniformLocationPointer = 0;
  26324. this._needSync = false;
  26325. if (this._noUBO) {
  26326. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26327. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26328. this.updateFloat = this._updateFloatForEffect;
  26329. this.updateFloat2 = this._updateFloat2ForEffect;
  26330. this.updateFloat3 = this._updateFloat3ForEffect;
  26331. this.updateFloat4 = this._updateFloat4ForEffect;
  26332. this.updateMatrix = this._updateMatrixForEffect;
  26333. this.updateVector3 = this._updateVector3ForEffect;
  26334. this.updateVector4 = this._updateVector4ForEffect;
  26335. this.updateColor3 = this._updateColor3ForEffect;
  26336. this.updateColor4 = this._updateColor4ForEffect;
  26337. }
  26338. else {
  26339. this._engine._uniformBuffers.push(this);
  26340. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26341. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26342. this.updateFloat = this._updateFloatForUniform;
  26343. this.updateFloat2 = this._updateFloat2ForUniform;
  26344. this.updateFloat3 = this._updateFloat3ForUniform;
  26345. this.updateFloat4 = this._updateFloat4ForUniform;
  26346. this.updateMatrix = this._updateMatrixForUniform;
  26347. this.updateVector3 = this._updateVector3ForUniform;
  26348. this.updateVector4 = this._updateVector4ForUniform;
  26349. this.updateColor3 = this._updateColor3ForUniform;
  26350. this.updateColor4 = this._updateColor4ForUniform;
  26351. }
  26352. }
  26353. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26354. // Properties
  26355. /**
  26356. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26357. * or just falling back on setUniformXXX calls.
  26358. */
  26359. get: function () {
  26360. return !this._noUBO;
  26361. },
  26362. enumerable: true,
  26363. configurable: true
  26364. });
  26365. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26366. /**
  26367. * Indicates if the WebGL underlying uniform buffer is in sync
  26368. * with the javascript cache data.
  26369. */
  26370. get: function () {
  26371. return !this._needSync;
  26372. },
  26373. enumerable: true,
  26374. configurable: true
  26375. });
  26376. /**
  26377. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26378. * Also, a dynamic UniformBuffer will disable cache verification and always
  26379. * update the underlying WebGL uniform buffer to the GPU.
  26380. */
  26381. UniformBuffer.prototype.isDynamic = function () {
  26382. return this._dynamic;
  26383. };
  26384. /**
  26385. * The data cache on JS side.
  26386. */
  26387. UniformBuffer.prototype.getData = function () {
  26388. return this._bufferData;
  26389. };
  26390. /**
  26391. * The underlying WebGL Uniform buffer.
  26392. */
  26393. UniformBuffer.prototype.getBuffer = function () {
  26394. return this._buffer;
  26395. };
  26396. /**
  26397. * std140 layout specifies how to align data within an UBO structure.
  26398. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26399. * for specs.
  26400. */
  26401. UniformBuffer.prototype._fillAlignment = function (size) {
  26402. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26403. // and 4x4 matrices
  26404. // TODO : change if other types are used
  26405. var alignment;
  26406. if (size <= 2) {
  26407. alignment = size;
  26408. }
  26409. else {
  26410. alignment = 4;
  26411. }
  26412. if ((this._uniformLocationPointer % alignment) !== 0) {
  26413. var oldPointer = this._uniformLocationPointer;
  26414. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26415. var diff = this._uniformLocationPointer - oldPointer;
  26416. for (var i = 0; i < diff; i++) {
  26417. this._data.push(0);
  26418. }
  26419. }
  26420. };
  26421. /**
  26422. * Adds an uniform in the buffer.
  26423. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26424. * for the layout to be correct !
  26425. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26426. * @param {number|number[]} size Data size, or data directly.
  26427. */
  26428. UniformBuffer.prototype.addUniform = function (name, size) {
  26429. if (this._noUBO) {
  26430. return;
  26431. }
  26432. if (this._uniformLocations[name] !== undefined) {
  26433. // Already existing uniform
  26434. return;
  26435. }
  26436. // This function must be called in the order of the shader layout !
  26437. // size can be the size of the uniform, or data directly
  26438. var data;
  26439. if (size instanceof Array) {
  26440. data = size;
  26441. size = data.length;
  26442. }
  26443. else {
  26444. size = size;
  26445. data = [];
  26446. // Fill with zeros
  26447. for (var i = 0; i < size; i++) {
  26448. data.push(0);
  26449. }
  26450. }
  26451. this._fillAlignment(size);
  26452. this._uniformSizes[name] = size;
  26453. this._uniformLocations[name] = this._uniformLocationPointer;
  26454. this._uniformLocationPointer += size;
  26455. for (var i = 0; i < size; i++) {
  26456. this._data.push(data[i]);
  26457. }
  26458. this._needSync = true;
  26459. };
  26460. /**
  26461. * Wrapper for addUniform.
  26462. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26463. * @param {Matrix} mat A 4x4 matrix.
  26464. */
  26465. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26466. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26467. };
  26468. /**
  26469. * Wrapper for addUniform.
  26470. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26471. * @param {number} x
  26472. * @param {number} y
  26473. */
  26474. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26475. var temp = [x, y];
  26476. this.addUniform(name, temp);
  26477. };
  26478. /**
  26479. * Wrapper for addUniform.
  26480. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26481. * @param {number} x
  26482. * @param {number} y
  26483. * @param {number} z
  26484. */
  26485. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26486. var temp = [x, y, z];
  26487. this.addUniform(name, temp);
  26488. };
  26489. /**
  26490. * Wrapper for addUniform.
  26491. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26492. * @param {Color3} color
  26493. */
  26494. UniformBuffer.prototype.addColor3 = function (name, color) {
  26495. var temp = [];
  26496. color.toArray(temp);
  26497. this.addUniform(name, temp);
  26498. };
  26499. /**
  26500. * Wrapper for addUniform.
  26501. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26502. * @param {Color3} color
  26503. * @param {number} alpha
  26504. */
  26505. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26506. var temp = [];
  26507. color.toArray(temp);
  26508. temp.push(alpha);
  26509. this.addUniform(name, temp);
  26510. };
  26511. /**
  26512. * Wrapper for addUniform.
  26513. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26514. * @param {Vector3} vector
  26515. */
  26516. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26517. var temp = [];
  26518. vector.toArray(temp);
  26519. this.addUniform(name, temp);
  26520. };
  26521. /**
  26522. * Wrapper for addUniform.
  26523. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26524. */
  26525. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26526. this.addUniform(name, 12);
  26527. };
  26528. /**
  26529. * Wrapper for addUniform.
  26530. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26531. */
  26532. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26533. this.addUniform(name, 8);
  26534. };
  26535. /**
  26536. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26537. */
  26538. UniformBuffer.prototype.create = function () {
  26539. if (this._noUBO) {
  26540. return;
  26541. }
  26542. if (this._buffer) {
  26543. return; // nothing to do
  26544. }
  26545. // See spec, alignment must be filled as a vec4
  26546. this._fillAlignment(4);
  26547. this._bufferData = new Float32Array(this._data);
  26548. this._rebuild();
  26549. this._needSync = true;
  26550. };
  26551. UniformBuffer.prototype._rebuild = function () {
  26552. if (this._noUBO) {
  26553. return;
  26554. }
  26555. if (this._dynamic) {
  26556. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26557. }
  26558. else {
  26559. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26560. }
  26561. };
  26562. /**
  26563. * Updates the WebGL Uniform Buffer on the GPU.
  26564. * If the `dynamic` flag is set to true, no cache comparison is done.
  26565. * Otherwise, the buffer will be updated only if the cache differs.
  26566. */
  26567. UniformBuffer.prototype.update = function () {
  26568. if (!this._buffer) {
  26569. this.create();
  26570. return;
  26571. }
  26572. if (!this._dynamic && !this._needSync) {
  26573. return;
  26574. }
  26575. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26576. this._needSync = false;
  26577. };
  26578. /**
  26579. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26580. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26581. * @param {number[]|Float32Array} data Flattened data
  26582. * @param {number} size Size of the data.
  26583. */
  26584. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26585. var location = this._uniformLocations[uniformName];
  26586. if (location === undefined) {
  26587. if (this._buffer) {
  26588. // Cannot add an uniform if the buffer is already created
  26589. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26590. return;
  26591. }
  26592. this.addUniform(uniformName, size);
  26593. location = this._uniformLocations[uniformName];
  26594. }
  26595. if (!this._buffer) {
  26596. this.create();
  26597. }
  26598. if (!this._dynamic) {
  26599. // Cache for static uniform buffers
  26600. var changed = false;
  26601. for (var i = 0; i < size; i++) {
  26602. if (this._bufferData[location + i] !== data[i]) {
  26603. changed = true;
  26604. this._bufferData[location + i] = data[i];
  26605. }
  26606. }
  26607. this._needSync = this._needSync || changed;
  26608. }
  26609. else {
  26610. // No cache for dynamic
  26611. for (var i = 0; i < size; i++) {
  26612. this._bufferData[location + i] = data[i];
  26613. }
  26614. }
  26615. };
  26616. // Update methods
  26617. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26618. // To match std140, matrix must be realigned
  26619. for (var i = 0; i < 3; i++) {
  26620. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26621. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26622. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26623. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26624. }
  26625. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26626. };
  26627. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26628. this._currentEffect.setMatrix3x3(name, matrix);
  26629. };
  26630. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26631. this._currentEffect.setMatrix2x2(name, matrix);
  26632. };
  26633. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26634. // To match std140, matrix must be realigned
  26635. for (var i = 0; i < 2; i++) {
  26636. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26637. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26638. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26639. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26640. }
  26641. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26642. };
  26643. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26644. this._currentEffect.setFloat(name, x);
  26645. };
  26646. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26647. UniformBuffer._tempBuffer[0] = x;
  26648. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26649. };
  26650. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26651. if (suffix === void 0) { suffix = ""; }
  26652. this._currentEffect.setFloat2(name + suffix, x, y);
  26653. };
  26654. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26655. if (suffix === void 0) { suffix = ""; }
  26656. UniformBuffer._tempBuffer[0] = x;
  26657. UniformBuffer._tempBuffer[1] = y;
  26658. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26659. };
  26660. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26661. if (suffix === void 0) { suffix = ""; }
  26662. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26663. };
  26664. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26665. if (suffix === void 0) { suffix = ""; }
  26666. UniformBuffer._tempBuffer[0] = x;
  26667. UniformBuffer._tempBuffer[1] = y;
  26668. UniformBuffer._tempBuffer[2] = z;
  26669. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26670. };
  26671. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26672. if (suffix === void 0) { suffix = ""; }
  26673. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26674. };
  26675. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26676. if (suffix === void 0) { suffix = ""; }
  26677. UniformBuffer._tempBuffer[0] = x;
  26678. UniformBuffer._tempBuffer[1] = y;
  26679. UniformBuffer._tempBuffer[2] = z;
  26680. UniformBuffer._tempBuffer[3] = w;
  26681. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26682. };
  26683. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26684. this._currentEffect.setMatrix(name, mat);
  26685. };
  26686. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26687. this.updateUniform(name, mat.toArray(), 16);
  26688. };
  26689. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26690. this._currentEffect.setVector3(name, vector);
  26691. };
  26692. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26693. vector.toArray(UniformBuffer._tempBuffer);
  26694. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26695. };
  26696. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26697. this._currentEffect.setVector4(name, vector);
  26698. };
  26699. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26700. vector.toArray(UniformBuffer._tempBuffer);
  26701. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26702. };
  26703. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26704. if (suffix === void 0) { suffix = ""; }
  26705. this._currentEffect.setColor3(name + suffix, color);
  26706. };
  26707. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26708. if (suffix === void 0) { suffix = ""; }
  26709. color.toArray(UniformBuffer._tempBuffer);
  26710. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26711. };
  26712. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26713. if (suffix === void 0) { suffix = ""; }
  26714. this._currentEffect.setColor4(name + suffix, color, alpha);
  26715. };
  26716. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26717. if (suffix === void 0) { suffix = ""; }
  26718. color.toArray(UniformBuffer._tempBuffer);
  26719. UniformBuffer._tempBuffer[3] = alpha;
  26720. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26721. };
  26722. /**
  26723. * Sets a sampler uniform on the effect.
  26724. * @param {string} name Name of the sampler.
  26725. * @param {Texture} texture
  26726. */
  26727. UniformBuffer.prototype.setTexture = function (name, texture) {
  26728. this._currentEffect.setTexture(name, texture);
  26729. };
  26730. /**
  26731. * Directly updates the value of the uniform in the cache AND on the GPU.
  26732. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26733. * @param {number[]|Float32Array} data Flattened data
  26734. */
  26735. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26736. this.updateUniform(uniformName, data, data.length);
  26737. this.update();
  26738. };
  26739. /**
  26740. * Binds this uniform buffer to an effect.
  26741. * @param {Effect} effect
  26742. * @param {string} name Name of the uniform block in the shader.
  26743. */
  26744. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26745. this._currentEffect = effect;
  26746. if (this._noUBO) {
  26747. return;
  26748. }
  26749. effect.bindUniformBuffer(this._buffer, name);
  26750. };
  26751. /**
  26752. * Disposes the uniform buffer.
  26753. */
  26754. UniformBuffer.prototype.dispose = function () {
  26755. if (this._noUBO) {
  26756. return;
  26757. }
  26758. var index = this._engine._uniformBuffers.indexOf(this);
  26759. if (index !== -1) {
  26760. this._engine._uniformBuffers.splice(index, 1);
  26761. }
  26762. if (!this._buffer) {
  26763. return;
  26764. }
  26765. if (this._engine._releaseBuffer(this._buffer)) {
  26766. this._buffer = null;
  26767. }
  26768. };
  26769. // Pool for avoiding memory leaks
  26770. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26771. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26772. return UniformBuffer;
  26773. }());
  26774. BABYLON.UniformBuffer = UniformBuffer;
  26775. })(BABYLON || (BABYLON = {}));
  26776. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26777. var BABYLON;
  26778. (function (BABYLON) {
  26779. var PushMaterial = (function (_super) {
  26780. __extends(PushMaterial, _super);
  26781. function PushMaterial(name, scene) {
  26782. var _this = _super.call(this, name, scene) || this;
  26783. _this.storeEffectOnSubMeshes = true;
  26784. return _this;
  26785. }
  26786. PushMaterial.prototype.getEffect = function () {
  26787. return this._activeEffect;
  26788. };
  26789. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26790. if (!mesh) {
  26791. return false;
  26792. }
  26793. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26794. return true;
  26795. }
  26796. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26797. };
  26798. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26799. this._activeEffect.setMatrix("world", world);
  26800. };
  26801. PushMaterial.prototype.bind = function (world, mesh) {
  26802. if (!mesh) {
  26803. return;
  26804. }
  26805. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26806. };
  26807. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26808. _super.prototype._afterBind.call(this, mesh);
  26809. this.getScene()._cachedEffect = effect;
  26810. };
  26811. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26812. if (visibility === void 0) { visibility = 1; }
  26813. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26814. };
  26815. return PushMaterial;
  26816. }(BABYLON.Material));
  26817. BABYLON.PushMaterial = PushMaterial;
  26818. })(BABYLON || (BABYLON = {}));
  26819. //# sourceMappingURL=babylon.pushMaterial.js.map
  26820. var BABYLON;
  26821. (function (BABYLON) {
  26822. var VertexData = (function () {
  26823. function VertexData() {
  26824. }
  26825. VertexData.prototype.set = function (data, kind) {
  26826. switch (kind) {
  26827. case BABYLON.VertexBuffer.PositionKind:
  26828. this.positions = data;
  26829. break;
  26830. case BABYLON.VertexBuffer.NormalKind:
  26831. this.normals = data;
  26832. break;
  26833. case BABYLON.VertexBuffer.TangentKind:
  26834. this.tangents = data;
  26835. break;
  26836. case BABYLON.VertexBuffer.UVKind:
  26837. this.uvs = data;
  26838. break;
  26839. case BABYLON.VertexBuffer.UV2Kind:
  26840. this.uvs2 = data;
  26841. break;
  26842. case BABYLON.VertexBuffer.UV3Kind:
  26843. this.uvs3 = data;
  26844. break;
  26845. case BABYLON.VertexBuffer.UV4Kind:
  26846. this.uvs4 = data;
  26847. break;
  26848. case BABYLON.VertexBuffer.UV5Kind:
  26849. this.uvs5 = data;
  26850. break;
  26851. case BABYLON.VertexBuffer.UV6Kind:
  26852. this.uvs6 = data;
  26853. break;
  26854. case BABYLON.VertexBuffer.ColorKind:
  26855. this.colors = data;
  26856. break;
  26857. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26858. this.matricesIndices = data;
  26859. break;
  26860. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26861. this.matricesWeights = data;
  26862. break;
  26863. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26864. this.matricesIndicesExtra = data;
  26865. break;
  26866. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26867. this.matricesWeightsExtra = data;
  26868. break;
  26869. }
  26870. };
  26871. /**
  26872. * Associates the vertexData to the passed Mesh.
  26873. * Sets it as updatable or not (default `false`).
  26874. * Returns the VertexData.
  26875. */
  26876. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26877. this._applyTo(mesh, updatable);
  26878. return this;
  26879. };
  26880. /**
  26881. * Associates the vertexData to the passed Geometry.
  26882. * Sets it as updatable or not (default `false`).
  26883. * Returns the VertexData.
  26884. */
  26885. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26886. this._applyTo(geometry, updatable);
  26887. return this;
  26888. };
  26889. /**
  26890. * Updates the associated mesh.
  26891. * Returns the VertexData.
  26892. */
  26893. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26894. this._update(mesh);
  26895. return this;
  26896. };
  26897. /**
  26898. * Updates the associated geometry.
  26899. * Returns the VertexData.
  26900. */
  26901. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26902. this._update(geometry);
  26903. return this;
  26904. };
  26905. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26906. if (this.positions) {
  26907. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26908. }
  26909. if (this.normals) {
  26910. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26911. }
  26912. if (this.tangents) {
  26913. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26914. }
  26915. if (this.uvs) {
  26916. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26917. }
  26918. if (this.uvs2) {
  26919. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26920. }
  26921. if (this.uvs3) {
  26922. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26923. }
  26924. if (this.uvs4) {
  26925. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26926. }
  26927. if (this.uvs5) {
  26928. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26929. }
  26930. if (this.uvs6) {
  26931. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26932. }
  26933. if (this.colors) {
  26934. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26935. }
  26936. if (this.matricesIndices) {
  26937. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26938. }
  26939. if (this.matricesWeights) {
  26940. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26941. }
  26942. if (this.matricesIndicesExtra) {
  26943. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26944. }
  26945. if (this.matricesWeightsExtra) {
  26946. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26947. }
  26948. if (this.indices) {
  26949. meshOrGeometry.setIndices(this.indices);
  26950. }
  26951. return this;
  26952. };
  26953. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26954. if (this.positions) {
  26955. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26956. }
  26957. if (this.normals) {
  26958. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26959. }
  26960. if (this.tangents) {
  26961. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26962. }
  26963. if (this.uvs) {
  26964. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26965. }
  26966. if (this.uvs2) {
  26967. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26968. }
  26969. if (this.uvs3) {
  26970. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26971. }
  26972. if (this.uvs4) {
  26973. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26974. }
  26975. if (this.uvs5) {
  26976. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26977. }
  26978. if (this.uvs6) {
  26979. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26980. }
  26981. if (this.colors) {
  26982. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26983. }
  26984. if (this.matricesIndices) {
  26985. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26986. }
  26987. if (this.matricesWeights) {
  26988. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26989. }
  26990. if (this.matricesIndicesExtra) {
  26991. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26992. }
  26993. if (this.matricesWeightsExtra) {
  26994. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26995. }
  26996. if (this.indices) {
  26997. meshOrGeometry.setIndices(this.indices);
  26998. }
  26999. return this;
  27000. };
  27001. /**
  27002. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  27003. * Returns the VertexData.
  27004. */
  27005. VertexData.prototype.transform = function (matrix) {
  27006. var transformed = BABYLON.Vector3.Zero();
  27007. var index;
  27008. if (this.positions) {
  27009. var position = BABYLON.Vector3.Zero();
  27010. for (index = 0; index < this.positions.length; index += 3) {
  27011. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27012. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27013. this.positions[index] = transformed.x;
  27014. this.positions[index + 1] = transformed.y;
  27015. this.positions[index + 2] = transformed.z;
  27016. }
  27017. }
  27018. if (this.normals) {
  27019. var normal = BABYLON.Vector3.Zero();
  27020. for (index = 0; index < this.normals.length; index += 3) {
  27021. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27022. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27023. this.normals[index] = transformed.x;
  27024. this.normals[index + 1] = transformed.y;
  27025. this.normals[index + 2] = transformed.z;
  27026. }
  27027. }
  27028. if (this.tangents) {
  27029. var tangent = BABYLON.Vector4.Zero();
  27030. var tangentTransformed = BABYLON.Vector4.Zero();
  27031. for (index = 0; index < this.tangents.length; index += 4) {
  27032. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  27033. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  27034. this.tangents[index] = tangentTransformed.x;
  27035. this.tangents[index + 1] = tangentTransformed.y;
  27036. this.tangents[index + 2] = tangentTransformed.z;
  27037. this.tangents[index + 3] = tangentTransformed.w;
  27038. }
  27039. }
  27040. return this;
  27041. };
  27042. /**
  27043. * Merges the passed VertexData into the current one.
  27044. * Returns the modified VertexData.
  27045. */
  27046. VertexData.prototype.merge = function (other) {
  27047. if (other.indices) {
  27048. if (!this.indices) {
  27049. this.indices = [];
  27050. }
  27051. var offset = this.positions ? this.positions.length / 3 : 0;
  27052. for (var index = 0; index < other.indices.length; index++) {
  27053. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  27054. this.indices.push(other.indices[index] + offset);
  27055. }
  27056. }
  27057. this.positions = this._mergeElement(this.positions, other.positions);
  27058. var count = this.positions.length / 3;
  27059. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  27060. this.tangents = this._mergeElement(this.tangents, other.tangents, count * 4);
  27061. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  27062. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  27063. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  27064. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  27065. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  27066. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  27067. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  27068. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  27069. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  27070. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  27071. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  27072. return this;
  27073. };
  27074. VertexData.prototype._mergeElement = function (source, other, length) {
  27075. if (length === void 0) { length = 0; }
  27076. if (!other && !source) {
  27077. return null;
  27078. }
  27079. if (!other) {
  27080. return this._mergeElement(source, new Float32Array(source.length), length);
  27081. }
  27082. if (!source) {
  27083. if (length === other.length) {
  27084. return other;
  27085. }
  27086. return this._mergeElement(new Float32Array(length - other.length), other, length);
  27087. }
  27088. var len = other.length + source.length;
  27089. var isSrcTypedArray = source instanceof Float32Array;
  27090. var isOthTypedArray = other instanceof Float32Array;
  27091. // use non-loop method when the source is Float32Array
  27092. if (isSrcTypedArray) {
  27093. var ret32 = new Float32Array(len);
  27094. ret32.set(source);
  27095. ret32.set(other, source.length);
  27096. return ret32;
  27097. // source is number[], when other is also use concat
  27098. }
  27099. else if (!isOthTypedArray) {
  27100. return source.concat(other);
  27101. // source is a number[], but other is a Float32Array, loop required
  27102. }
  27103. else {
  27104. var ret = source.slice(0); // copy source to a separate array
  27105. for (var i = 0, len = other.length; i < len; i++) {
  27106. ret.push(other[i]);
  27107. }
  27108. return ret;
  27109. }
  27110. };
  27111. /**
  27112. * Serializes the VertexData.
  27113. * Returns a serialized object.
  27114. */
  27115. VertexData.prototype.serialize = function () {
  27116. var serializationObject = this.serialize();
  27117. if (this.positions) {
  27118. serializationObject.positions = this.positions;
  27119. }
  27120. if (this.normals) {
  27121. serializationObject.normals = this.normals;
  27122. }
  27123. if (this.tangents) {
  27124. serializationObject.tangents = this.tangents;
  27125. }
  27126. if (this.uvs) {
  27127. serializationObject.uvs = this.uvs;
  27128. }
  27129. if (this.uvs2) {
  27130. serializationObject.uvs2 = this.uvs2;
  27131. }
  27132. if (this.uvs3) {
  27133. serializationObject.uvs3 = this.uvs3;
  27134. }
  27135. if (this.uvs4) {
  27136. serializationObject.uvs4 = this.uvs4;
  27137. }
  27138. if (this.uvs5) {
  27139. serializationObject.uvs5 = this.uvs5;
  27140. }
  27141. if (this.uvs6) {
  27142. serializationObject.uvs6 = this.uvs6;
  27143. }
  27144. if (this.colors) {
  27145. serializationObject.colors = this.colors;
  27146. }
  27147. if (this.matricesIndices) {
  27148. serializationObject.matricesIndices = this.matricesIndices;
  27149. serializationObject.matricesIndices._isExpanded = true;
  27150. }
  27151. if (this.matricesWeights) {
  27152. serializationObject.matricesWeights = this.matricesWeights;
  27153. }
  27154. if (this.matricesIndicesExtra) {
  27155. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27156. serializationObject.matricesIndicesExtra._isExpanded = true;
  27157. }
  27158. if (this.matricesWeightsExtra) {
  27159. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27160. }
  27161. serializationObject.indices = this.indices;
  27162. return serializationObject;
  27163. };
  27164. // Statics
  27165. /**
  27166. * Returns the object VertexData associated to the passed mesh.
  27167. */
  27168. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  27169. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  27170. };
  27171. /**
  27172. * Returns the object VertexData associated to the passed geometry.
  27173. */
  27174. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  27175. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  27176. };
  27177. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  27178. var result = new VertexData();
  27179. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27180. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  27181. }
  27182. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27183. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  27184. }
  27185. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27186. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  27187. }
  27188. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27189. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  27190. }
  27191. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27192. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  27193. }
  27194. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27195. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  27196. }
  27197. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27198. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  27199. }
  27200. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27201. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  27202. }
  27203. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27204. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  27205. }
  27206. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27207. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  27208. }
  27209. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27210. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  27211. }
  27212. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27213. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  27214. }
  27215. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27216. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  27217. }
  27218. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27219. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  27220. }
  27221. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27222. return result;
  27223. };
  27224. /**
  27225. * Creates the vertexData of the Ribbon.
  27226. */
  27227. VertexData.CreateRibbon = function (options) {
  27228. var pathArray = options.pathArray;
  27229. var closeArray = options.closeArray || false;
  27230. var closePath = options.closePath || false;
  27231. var invertUV = options.invertUV || false;
  27232. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27233. var offset = options.offset || defaultOffset;
  27234. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27235. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27236. var customUV = options.uvs;
  27237. var customColors = options.colors;
  27238. var positions = [];
  27239. var indices = [];
  27240. var normals = [];
  27241. var uvs = [];
  27242. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27243. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27244. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27245. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27246. var minlg; // minimal length among all paths from pathArray
  27247. var lg = []; // array of path lengths : nb of vertex per path
  27248. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27249. var p; // path iterator
  27250. var i; // point iterator
  27251. var j; // point iterator
  27252. // if single path in pathArray
  27253. if (pathArray.length < 2) {
  27254. var ar1 = [];
  27255. var ar2 = [];
  27256. for (i = 0; i < pathArray[0].length - offset; i++) {
  27257. ar1.push(pathArray[0][i]);
  27258. ar2.push(pathArray[0][i + offset]);
  27259. }
  27260. pathArray = [ar1, ar2];
  27261. }
  27262. // positions and horizontal distances (u)
  27263. var idc = 0;
  27264. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  27265. var path;
  27266. var l;
  27267. minlg = pathArray[0].length;
  27268. var vectlg;
  27269. var dist;
  27270. for (p = 0; p < pathArray.length; p++) {
  27271. uTotalDistance[p] = 0;
  27272. us[p] = [0];
  27273. path = pathArray[p];
  27274. l = path.length;
  27275. minlg = (minlg < l) ? minlg : l;
  27276. j = 0;
  27277. while (j < l) {
  27278. positions.push(path[j].x, path[j].y, path[j].z);
  27279. if (j > 0) {
  27280. vectlg = path[j].subtract(path[j - 1]).length();
  27281. dist = vectlg + uTotalDistance[p];
  27282. us[p].push(dist);
  27283. uTotalDistance[p] = dist;
  27284. }
  27285. j++;
  27286. }
  27287. if (closePath) {
  27288. j--;
  27289. positions.push(path[0].x, path[0].y, path[0].z);
  27290. vectlg = path[j].subtract(path[0]).length();
  27291. dist = vectlg + uTotalDistance[p];
  27292. us[p].push(dist);
  27293. uTotalDistance[p] = dist;
  27294. }
  27295. lg[p] = l + closePathCorr;
  27296. idx[p] = idc;
  27297. idc += (l + closePathCorr);
  27298. }
  27299. // vertical distances (v)
  27300. var path1;
  27301. var path2;
  27302. var vertex1;
  27303. var vertex2;
  27304. for (i = 0; i < minlg + closePathCorr; i++) {
  27305. vTotalDistance[i] = 0;
  27306. vs[i] = [0];
  27307. for (p = 0; p < pathArray.length - 1; p++) {
  27308. path1 = pathArray[p];
  27309. path2 = pathArray[p + 1];
  27310. if (i === minlg) {
  27311. vertex1 = path1[0];
  27312. vertex2 = path2[0];
  27313. }
  27314. else {
  27315. vertex1 = path1[i];
  27316. vertex2 = path2[i];
  27317. }
  27318. vectlg = vertex2.subtract(vertex1).length();
  27319. dist = vectlg + vTotalDistance[i];
  27320. vs[i].push(dist);
  27321. vTotalDistance[i] = dist;
  27322. }
  27323. if (closeArray) {
  27324. path1 = pathArray[p];
  27325. path2 = pathArray[0];
  27326. if (i === minlg) {
  27327. vertex2 = path2[0];
  27328. }
  27329. vectlg = vertex2.subtract(vertex1).length();
  27330. dist = vectlg + vTotalDistance[i];
  27331. vTotalDistance[i] = dist;
  27332. }
  27333. }
  27334. // uvs
  27335. var u;
  27336. var v;
  27337. if (customUV) {
  27338. for (p = 0; p < customUV.length; p++) {
  27339. uvs.push(customUV[p].x, customUV[p].y);
  27340. }
  27341. }
  27342. else {
  27343. for (p = 0; p < pathArray.length; p++) {
  27344. for (i = 0; i < minlg + closePathCorr; i++) {
  27345. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27346. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27347. if (invertUV) {
  27348. uvs.push(v, u);
  27349. }
  27350. else {
  27351. uvs.push(u, v);
  27352. }
  27353. }
  27354. }
  27355. }
  27356. // indices
  27357. p = 0; // path index
  27358. var pi = 0; // positions array index
  27359. var l1 = lg[p] - 1; // path1 length
  27360. var l2 = lg[p + 1] - 1; // path2 length
  27361. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27362. var shft = idx[1] - idx[0]; // shift
  27363. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27364. while (pi <= min && p < path1nb) {
  27365. // 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
  27366. indices.push(pi, pi + shft, pi + 1);
  27367. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27368. pi += 1;
  27369. if (pi === min) {
  27370. p++;
  27371. if (p === lg.length - 1) {
  27372. shft = idx[0] - idx[p];
  27373. l1 = lg[p] - 1;
  27374. l2 = lg[0] - 1;
  27375. }
  27376. else {
  27377. shft = idx[p + 1] - idx[p];
  27378. l1 = lg[p] - 1;
  27379. l2 = lg[p + 1] - 1;
  27380. }
  27381. pi = idx[p];
  27382. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27383. }
  27384. }
  27385. // normals
  27386. VertexData.ComputeNormals(positions, indices, normals);
  27387. if (closePath) {
  27388. var indexFirst = 0;
  27389. var indexLast = 0;
  27390. for (p = 0; p < pathArray.length; p++) {
  27391. indexFirst = idx[p] * 3;
  27392. if (p + 1 < pathArray.length) {
  27393. indexLast = (idx[p + 1] - 1) * 3;
  27394. }
  27395. else {
  27396. indexLast = normals.length - 3;
  27397. }
  27398. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27399. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27400. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27401. normals[indexLast] = normals[indexFirst];
  27402. normals[indexLast + 1] = normals[indexFirst + 1];
  27403. normals[indexLast + 2] = normals[indexFirst + 2];
  27404. }
  27405. }
  27406. // sides
  27407. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27408. // Colors
  27409. if (customColors) {
  27410. var colors = new Float32Array(customColors.length * 4);
  27411. for (var c = 0; c < customColors.length; c++) {
  27412. colors[c * 4] = customColors[c].r;
  27413. colors[c * 4 + 1] = customColors[c].g;
  27414. colors[c * 4 + 2] = customColors[c].b;
  27415. colors[c * 4 + 3] = customColors[c].a;
  27416. }
  27417. }
  27418. // Result
  27419. var vertexData = new VertexData();
  27420. var positions32 = new Float32Array(positions);
  27421. var normals32 = new Float32Array(normals);
  27422. var uvs32 = new Float32Array(uvs);
  27423. vertexData.indices = indices;
  27424. vertexData.positions = positions32;
  27425. vertexData.normals = normals32;
  27426. vertexData.uvs = uvs32;
  27427. if (customColors) {
  27428. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27429. }
  27430. if (closePath) {
  27431. vertexData._idx = idx;
  27432. }
  27433. return vertexData;
  27434. };
  27435. /**
  27436. * Creates the VertexData of the Box.
  27437. */
  27438. VertexData.CreateBox = function (options) {
  27439. var normalsSource = [
  27440. new BABYLON.Vector3(0, 0, 1),
  27441. new BABYLON.Vector3(0, 0, -1),
  27442. new BABYLON.Vector3(1, 0, 0),
  27443. new BABYLON.Vector3(-1, 0, 0),
  27444. new BABYLON.Vector3(0, 1, 0),
  27445. new BABYLON.Vector3(0, -1, 0)
  27446. ];
  27447. var indices = [];
  27448. var positions = [];
  27449. var normals = [];
  27450. var uvs = [];
  27451. var width = options.width || options.size || 1;
  27452. var height = options.height || options.size || 1;
  27453. var depth = options.depth || options.size || 1;
  27454. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27455. var faceUV = options.faceUV || new Array(6);
  27456. var faceColors = options.faceColors;
  27457. var colors = [];
  27458. // default face colors and UV if undefined
  27459. for (var f = 0; f < 6; f++) {
  27460. if (faceUV[f] === undefined) {
  27461. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27462. }
  27463. if (faceColors && faceColors[f] === undefined) {
  27464. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27465. }
  27466. }
  27467. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27468. // Create each face in turn.
  27469. for (var index = 0; index < normalsSource.length; index++) {
  27470. var normal = normalsSource[index];
  27471. // Get two vectors perpendicular to the face normal and to each other.
  27472. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27473. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27474. // Six indices (two triangles) per face.
  27475. var verticesLength = positions.length / 3;
  27476. indices.push(verticesLength);
  27477. indices.push(verticesLength + 1);
  27478. indices.push(verticesLength + 2);
  27479. indices.push(verticesLength);
  27480. indices.push(verticesLength + 2);
  27481. indices.push(verticesLength + 3);
  27482. // Four vertices per face.
  27483. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27484. positions.push(vertex.x, vertex.y, vertex.z);
  27485. normals.push(normal.x, normal.y, normal.z);
  27486. uvs.push(faceUV[index].z, faceUV[index].w);
  27487. if (faceColors) {
  27488. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27489. }
  27490. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27491. positions.push(vertex.x, vertex.y, vertex.z);
  27492. normals.push(normal.x, normal.y, normal.z);
  27493. uvs.push(faceUV[index].x, faceUV[index].w);
  27494. if (faceColors) {
  27495. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27496. }
  27497. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27498. positions.push(vertex.x, vertex.y, vertex.z);
  27499. normals.push(normal.x, normal.y, normal.z);
  27500. uvs.push(faceUV[index].x, faceUV[index].y);
  27501. if (faceColors) {
  27502. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27503. }
  27504. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27505. positions.push(vertex.x, vertex.y, vertex.z);
  27506. normals.push(normal.x, normal.y, normal.z);
  27507. uvs.push(faceUV[index].z, faceUV[index].y);
  27508. if (faceColors) {
  27509. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27510. }
  27511. }
  27512. // sides
  27513. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27514. // Result
  27515. var vertexData = new VertexData();
  27516. vertexData.indices = indices;
  27517. vertexData.positions = positions;
  27518. vertexData.normals = normals;
  27519. vertexData.uvs = uvs;
  27520. if (faceColors) {
  27521. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27522. vertexData.colors = totalColors;
  27523. }
  27524. return vertexData;
  27525. };
  27526. /**
  27527. * Creates the VertexData of the Sphere.
  27528. */
  27529. VertexData.CreateSphere = function (options) {
  27530. var segments = options.segments || 32;
  27531. var diameterX = options.diameterX || options.diameter || 1;
  27532. var diameterY = options.diameterY || options.diameter || 1;
  27533. var diameterZ = options.diameterZ || options.diameter || 1;
  27534. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27535. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27536. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27537. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27538. var totalZRotationSteps = 2 + segments;
  27539. var totalYRotationSteps = 2 * totalZRotationSteps;
  27540. var indices = [];
  27541. var positions = [];
  27542. var normals = [];
  27543. var uvs = [];
  27544. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27545. var normalizedZ = zRotationStep / totalZRotationSteps;
  27546. var angleZ = normalizedZ * Math.PI * slice;
  27547. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27548. var normalizedY = yRotationStep / totalYRotationSteps;
  27549. var angleY = normalizedY * Math.PI * 2 * arc;
  27550. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27551. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27552. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27553. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27554. var vertex = complete.multiply(radius);
  27555. var normal = complete.divide(radius).normalize();
  27556. positions.push(vertex.x, vertex.y, vertex.z);
  27557. normals.push(normal.x, normal.y, normal.z);
  27558. uvs.push(normalizedY, normalizedZ);
  27559. }
  27560. if (zRotationStep > 0) {
  27561. var verticesCount = positions.length / 3;
  27562. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27563. indices.push((firstIndex));
  27564. indices.push((firstIndex + 1));
  27565. indices.push(firstIndex + totalYRotationSteps + 1);
  27566. indices.push((firstIndex + totalYRotationSteps + 1));
  27567. indices.push((firstIndex + 1));
  27568. indices.push((firstIndex + totalYRotationSteps + 2));
  27569. }
  27570. }
  27571. }
  27572. // Sides
  27573. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27574. // Result
  27575. var vertexData = new VertexData();
  27576. vertexData.indices = indices;
  27577. vertexData.positions = positions;
  27578. vertexData.normals = normals;
  27579. vertexData.uvs = uvs;
  27580. return vertexData;
  27581. };
  27582. /**
  27583. * Creates the VertexData of the Cylinder or Cone.
  27584. */
  27585. VertexData.CreateCylinder = function (options) {
  27586. var height = options.height || 2;
  27587. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27588. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27589. var tessellation = options.tessellation || 24;
  27590. var subdivisions = options.subdivisions || 1;
  27591. var hasRings = options.hasRings;
  27592. var enclose = options.enclose;
  27593. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27594. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27595. var faceUV = options.faceUV || new Array(3);
  27596. var faceColors = options.faceColors;
  27597. // default face colors and UV if undefined
  27598. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27599. var ringNb = (hasRings) ? subdivisions : 1;
  27600. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27601. var f;
  27602. for (f = 0; f < surfaceNb; f++) {
  27603. if (faceColors && faceColors[f] === undefined) {
  27604. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27605. }
  27606. }
  27607. for (f = 0; f < surfaceNb; f++) {
  27608. if (faceUV && faceUV[f] === undefined) {
  27609. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27610. }
  27611. }
  27612. var indices = [];
  27613. var positions = [];
  27614. var normals = [];
  27615. var uvs = [];
  27616. var colors = [];
  27617. var angle_step = Math.PI * 2 * arc / tessellation;
  27618. var angle;
  27619. var h;
  27620. var radius;
  27621. var tan = (diameterBottom - diameterTop) / 2 / height;
  27622. var ringVertex = BABYLON.Vector3.Zero();
  27623. var ringNormal = BABYLON.Vector3.Zero();
  27624. var ringFirstVertex = BABYLON.Vector3.Zero();
  27625. var ringFirstNormal = BABYLON.Vector3.Zero();
  27626. var quadNormal = BABYLON.Vector3.Zero();
  27627. var Y = BABYLON.Axis.Y;
  27628. // positions, normals, uvs
  27629. var i;
  27630. var j;
  27631. var r;
  27632. var ringIdx = 1;
  27633. var s = 1; // surface index
  27634. var cs = 0;
  27635. var v = 0;
  27636. for (i = 0; i <= subdivisions; i++) {
  27637. h = i / subdivisions;
  27638. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27639. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27640. for (r = 0; r < ringIdx; r++) {
  27641. if (hasRings) {
  27642. s += r;
  27643. }
  27644. if (enclose) {
  27645. s += 2 * r;
  27646. }
  27647. for (j = 0; j <= tessellation; j++) {
  27648. angle = j * angle_step;
  27649. // position
  27650. ringVertex.x = Math.cos(-angle) * radius;
  27651. ringVertex.y = -height / 2 + h * height;
  27652. ringVertex.z = Math.sin(-angle) * radius;
  27653. // normal
  27654. if (diameterTop === 0 && i === subdivisions) {
  27655. // if no top cap, reuse former normals
  27656. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27657. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27658. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27659. }
  27660. else {
  27661. ringNormal.x = ringVertex.x;
  27662. ringNormal.z = ringVertex.z;
  27663. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27664. ringNormal.normalize();
  27665. }
  27666. // keep first ring vertex values for enclose
  27667. if (j === 0) {
  27668. ringFirstVertex.copyFrom(ringVertex);
  27669. ringFirstNormal.copyFrom(ringNormal);
  27670. }
  27671. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27672. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27673. if (hasRings) {
  27674. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27675. }
  27676. else {
  27677. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27678. }
  27679. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27680. if (faceColors) {
  27681. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27682. }
  27683. }
  27684. // if enclose, add four vertices and their dedicated normals
  27685. if (arc !== 1 && enclose) {
  27686. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27687. positions.push(0, ringVertex.y, 0);
  27688. positions.push(0, ringVertex.y, 0);
  27689. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27690. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27691. quadNormal.normalize();
  27692. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27693. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27694. quadNormal.normalize();
  27695. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27696. if (hasRings) {
  27697. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27698. }
  27699. else {
  27700. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27701. }
  27702. uvs.push(faceUV[s + 1].x, v);
  27703. uvs.push(faceUV[s + 1].z, v);
  27704. if (hasRings) {
  27705. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27706. }
  27707. else {
  27708. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27709. }
  27710. uvs.push(faceUV[s + 2].x, v);
  27711. uvs.push(faceUV[s + 2].z, v);
  27712. if (faceColors) {
  27713. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27714. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27715. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27716. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27717. }
  27718. }
  27719. if (cs !== s) {
  27720. cs = s;
  27721. }
  27722. }
  27723. }
  27724. // indices
  27725. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27726. var s;
  27727. i = 0;
  27728. for (s = 0; s < subdivisions; s++) {
  27729. for (j = 0; j < tessellation; j++) {
  27730. var i0 = i * (e + 1) + j;
  27731. var i1 = (i + 1) * (e + 1) + j;
  27732. var i2 = i * (e + 1) + (j + 1);
  27733. var i3 = (i + 1) * (e + 1) + (j + 1);
  27734. indices.push(i0, i1, i2);
  27735. indices.push(i3, i2, i1);
  27736. }
  27737. if (arc !== 1 && enclose) {
  27738. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27739. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27740. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27741. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27742. }
  27743. i = (hasRings) ? (i + 2) : (i + 1);
  27744. }
  27745. // Caps
  27746. var createCylinderCap = function (isTop) {
  27747. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27748. if (radius === 0) {
  27749. return;
  27750. }
  27751. // Cap positions, normals & uvs
  27752. var angle;
  27753. var circleVector;
  27754. var i;
  27755. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27756. var c;
  27757. if (faceColors) {
  27758. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27759. }
  27760. // cap center
  27761. var vbase = positions.length / 3;
  27762. var offset = isTop ? height / 2 : -height / 2;
  27763. var center = new BABYLON.Vector3(0, offset, 0);
  27764. positions.push(center.x, center.y, center.z);
  27765. normals.push(0, isTop ? 1 : -1, 0);
  27766. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27767. if (faceColors) {
  27768. colors.push(c.r, c.g, c.b, c.a);
  27769. }
  27770. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27771. for (i = 0; i <= tessellation; i++) {
  27772. angle = Math.PI * 2 * i * arc / tessellation;
  27773. var cos = Math.cos(-angle);
  27774. var sin = Math.sin(-angle);
  27775. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27776. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27777. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27778. normals.push(0, isTop ? 1 : -1, 0);
  27779. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27780. if (faceColors) {
  27781. colors.push(c.r, c.g, c.b, c.a);
  27782. }
  27783. }
  27784. // Cap indices
  27785. for (i = 0; i < tessellation; i++) {
  27786. if (!isTop) {
  27787. indices.push(vbase);
  27788. indices.push(vbase + (i + 1));
  27789. indices.push(vbase + (i + 2));
  27790. }
  27791. else {
  27792. indices.push(vbase);
  27793. indices.push(vbase + (i + 2));
  27794. indices.push(vbase + (i + 1));
  27795. }
  27796. }
  27797. };
  27798. // add caps to geometry
  27799. createCylinderCap(false);
  27800. createCylinderCap(true);
  27801. // Sides
  27802. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27803. var vertexData = new VertexData();
  27804. vertexData.indices = indices;
  27805. vertexData.positions = positions;
  27806. vertexData.normals = normals;
  27807. vertexData.uvs = uvs;
  27808. if (faceColors) {
  27809. vertexData.colors = colors;
  27810. }
  27811. return vertexData;
  27812. };
  27813. /**
  27814. * Creates the VertexData of the Torus.
  27815. */
  27816. VertexData.CreateTorus = function (options) {
  27817. var indices = [];
  27818. var positions = [];
  27819. var normals = [];
  27820. var uvs = [];
  27821. var diameter = options.diameter || 1;
  27822. var thickness = options.thickness || 0.5;
  27823. var tessellation = options.tessellation || 16;
  27824. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27825. var stride = tessellation + 1;
  27826. for (var i = 0; i <= tessellation; i++) {
  27827. var u = i / tessellation;
  27828. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27829. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27830. for (var j = 0; j <= tessellation; j++) {
  27831. var v = 1 - j / tessellation;
  27832. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27833. var dx = Math.cos(innerAngle);
  27834. var dy = Math.sin(innerAngle);
  27835. // Create a vertex.
  27836. var normal = new BABYLON.Vector3(dx, dy, 0);
  27837. var position = normal.scale(thickness / 2);
  27838. var textureCoordinate = new BABYLON.Vector2(u, v);
  27839. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27840. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27841. positions.push(position.x, position.y, position.z);
  27842. normals.push(normal.x, normal.y, normal.z);
  27843. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27844. // And create indices for two triangles.
  27845. var nextI = (i + 1) % stride;
  27846. var nextJ = (j + 1) % stride;
  27847. indices.push(i * stride + j);
  27848. indices.push(i * stride + nextJ);
  27849. indices.push(nextI * stride + j);
  27850. indices.push(i * stride + nextJ);
  27851. indices.push(nextI * stride + nextJ);
  27852. indices.push(nextI * stride + j);
  27853. }
  27854. }
  27855. // Sides
  27856. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27857. // Result
  27858. var vertexData = new VertexData();
  27859. vertexData.indices = indices;
  27860. vertexData.positions = positions;
  27861. vertexData.normals = normals;
  27862. vertexData.uvs = uvs;
  27863. return vertexData;
  27864. };
  27865. /**
  27866. * Creates the VertexData of the LineSystem.
  27867. */
  27868. VertexData.CreateLineSystem = function (options) {
  27869. var indices = [];
  27870. var positions = [];
  27871. var lines = options.lines;
  27872. var idx = 0;
  27873. for (var l = 0; l < lines.length; l++) {
  27874. var points = lines[l];
  27875. for (var index = 0; index < points.length; index++) {
  27876. positions.push(points[index].x, points[index].y, points[index].z);
  27877. if (index > 0) {
  27878. indices.push(idx - 1);
  27879. indices.push(idx);
  27880. }
  27881. idx++;
  27882. }
  27883. }
  27884. var vertexData = new VertexData();
  27885. vertexData.indices = indices;
  27886. vertexData.positions = positions;
  27887. return vertexData;
  27888. };
  27889. /**
  27890. * Create the VertexData of the DashedLines.
  27891. */
  27892. VertexData.CreateDashedLines = function (options) {
  27893. var dashSize = options.dashSize || 3;
  27894. var gapSize = options.gapSize || 1;
  27895. var dashNb = options.dashNb || 200;
  27896. var points = options.points;
  27897. var positions = new Array();
  27898. var indices = new Array();
  27899. var curvect = BABYLON.Vector3.Zero();
  27900. var lg = 0;
  27901. var nb = 0;
  27902. var shft = 0;
  27903. var dashshft = 0;
  27904. var curshft = 0;
  27905. var idx = 0;
  27906. var i = 0;
  27907. for (i = 0; i < points.length - 1; i++) {
  27908. points[i + 1].subtractToRef(points[i], curvect);
  27909. lg += curvect.length();
  27910. }
  27911. shft = lg / dashNb;
  27912. dashshft = dashSize * shft / (dashSize + gapSize);
  27913. for (i = 0; i < points.length - 1; i++) {
  27914. points[i + 1].subtractToRef(points[i], curvect);
  27915. nb = Math.floor(curvect.length() / shft);
  27916. curvect.normalize();
  27917. for (var j = 0; j < nb; j++) {
  27918. curshft = shft * j;
  27919. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27920. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27921. indices.push(idx, idx + 1);
  27922. idx += 2;
  27923. }
  27924. }
  27925. // Result
  27926. var vertexData = new VertexData();
  27927. vertexData.positions = positions;
  27928. vertexData.indices = indices;
  27929. return vertexData;
  27930. };
  27931. /**
  27932. * Creates the VertexData of the Ground.
  27933. */
  27934. VertexData.CreateGround = function (options) {
  27935. var indices = [];
  27936. var positions = [];
  27937. var normals = [];
  27938. var uvs = [];
  27939. var row, col;
  27940. var width = options.width || 1;
  27941. var height = options.height || 1;
  27942. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27943. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27944. for (row = 0; row <= subdivisionsY; row++) {
  27945. for (col = 0; col <= subdivisionsX; col++) {
  27946. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27947. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27948. positions.push(position.x, position.y, position.z);
  27949. normals.push(normal.x, normal.y, normal.z);
  27950. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27951. }
  27952. }
  27953. for (row = 0; row < subdivisionsY; row++) {
  27954. for (col = 0; col < subdivisionsX; col++) {
  27955. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27956. indices.push(col + 1 + row * (subdivisionsX + 1));
  27957. indices.push(col + row * (subdivisionsX + 1));
  27958. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27959. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27960. indices.push(col + row * (subdivisionsX + 1));
  27961. }
  27962. }
  27963. // Result
  27964. var vertexData = new VertexData();
  27965. vertexData.indices = indices;
  27966. vertexData.positions = positions;
  27967. vertexData.normals = normals;
  27968. vertexData.uvs = uvs;
  27969. return vertexData;
  27970. };
  27971. /**
  27972. * Creates the VertexData of the TiledGround.
  27973. */
  27974. VertexData.CreateTiledGround = function (options) {
  27975. var xmin = options.xmin || -1.0;
  27976. var zmin = options.zmin || -1.0;
  27977. var xmax = options.xmax || 1.0;
  27978. var zmax = options.zmax || 1.0;
  27979. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27980. var precision = options.precision || { w: 1, h: 1 };
  27981. var indices = [];
  27982. var positions = [];
  27983. var normals = [];
  27984. var uvs = [];
  27985. var row, col, tileRow, tileCol;
  27986. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27987. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27988. precision.w = (precision.w < 1) ? 1 : precision.w;
  27989. precision.h = (precision.h < 1) ? 1 : precision.h;
  27990. var tileSize = {
  27991. 'w': (xmax - xmin) / subdivisions.w,
  27992. 'h': (zmax - zmin) / subdivisions.h
  27993. };
  27994. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27995. // Indices
  27996. var base = positions.length / 3;
  27997. var rowLength = precision.w + 1;
  27998. for (row = 0; row < precision.h; row++) {
  27999. for (col = 0; col < precision.w; col++) {
  28000. var square = [
  28001. base + col + row * rowLength,
  28002. base + (col + 1) + row * rowLength,
  28003. base + (col + 1) + (row + 1) * rowLength,
  28004. base + col + (row + 1) * rowLength
  28005. ];
  28006. indices.push(square[1]);
  28007. indices.push(square[2]);
  28008. indices.push(square[3]);
  28009. indices.push(square[0]);
  28010. indices.push(square[1]);
  28011. indices.push(square[3]);
  28012. }
  28013. }
  28014. // Position, normals and uvs
  28015. var position = BABYLON.Vector3.Zero();
  28016. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28017. for (row = 0; row <= precision.h; row++) {
  28018. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28019. for (col = 0; col <= precision.w; col++) {
  28020. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28021. position.y = 0;
  28022. positions.push(position.x, position.y, position.z);
  28023. normals.push(normal.x, normal.y, normal.z);
  28024. uvs.push(col / precision.w, row / precision.h);
  28025. }
  28026. }
  28027. }
  28028. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28029. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28030. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28031. }
  28032. }
  28033. // Result
  28034. var vertexData = new VertexData();
  28035. vertexData.indices = indices;
  28036. vertexData.positions = positions;
  28037. vertexData.normals = normals;
  28038. vertexData.uvs = uvs;
  28039. return vertexData;
  28040. };
  28041. /**
  28042. * Creates the VertexData of the Ground designed from a heightmap.
  28043. */
  28044. VertexData.CreateGroundFromHeightMap = function (options) {
  28045. var indices = [];
  28046. var positions = [];
  28047. var normals = [];
  28048. var uvs = [];
  28049. var row, col;
  28050. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  28051. // Vertices
  28052. for (row = 0; row <= options.subdivisions; row++) {
  28053. for (col = 0; col <= options.subdivisions; col++) {
  28054. 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));
  28055. // Compute height
  28056. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28057. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28058. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28059. var r = options.buffer[pos] / 255.0;
  28060. var g = options.buffer[pos + 1] / 255.0;
  28061. var b = options.buffer[pos + 2] / 255.0;
  28062. var gradient = r * filter.r + g * filter.g + b * filter.b;
  28063. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28064. // Add vertex
  28065. positions.push(position.x, position.y, position.z);
  28066. normals.push(0, 0, 0);
  28067. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28068. }
  28069. }
  28070. // Indices
  28071. for (row = 0; row < options.subdivisions; row++) {
  28072. for (col = 0; col < options.subdivisions; col++) {
  28073. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28074. indices.push(col + 1 + row * (options.subdivisions + 1));
  28075. indices.push(col + row * (options.subdivisions + 1));
  28076. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28077. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28078. indices.push(col + row * (options.subdivisions + 1));
  28079. }
  28080. }
  28081. // Normals
  28082. VertexData.ComputeNormals(positions, indices, normals);
  28083. // Result
  28084. var vertexData = new VertexData();
  28085. vertexData.indices = indices;
  28086. vertexData.positions = positions;
  28087. vertexData.normals = normals;
  28088. vertexData.uvs = uvs;
  28089. return vertexData;
  28090. };
  28091. /**
  28092. * Creates the VertexData of the Plane.
  28093. */
  28094. VertexData.CreatePlane = function (options) {
  28095. var indices = [];
  28096. var positions = [];
  28097. var normals = [];
  28098. var uvs = [];
  28099. var width = options.width || options.size || 1;
  28100. var height = options.height || options.size || 1;
  28101. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28102. // Vertices
  28103. var halfWidth = width / 2.0;
  28104. var halfHeight = height / 2.0;
  28105. positions.push(-halfWidth, -halfHeight, 0);
  28106. normals.push(0, 0, -1.0);
  28107. uvs.push(0.0, 0.0);
  28108. positions.push(halfWidth, -halfHeight, 0);
  28109. normals.push(0, 0, -1.0);
  28110. uvs.push(1.0, 0.0);
  28111. positions.push(halfWidth, halfHeight, 0);
  28112. normals.push(0, 0, -1.0);
  28113. uvs.push(1.0, 1.0);
  28114. positions.push(-halfWidth, halfHeight, 0);
  28115. normals.push(0, 0, -1.0);
  28116. uvs.push(0.0, 1.0);
  28117. // Indices
  28118. indices.push(0);
  28119. indices.push(1);
  28120. indices.push(2);
  28121. indices.push(0);
  28122. indices.push(2);
  28123. indices.push(3);
  28124. // Sides
  28125. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28126. // Result
  28127. var vertexData = new VertexData();
  28128. vertexData.indices = indices;
  28129. vertexData.positions = positions;
  28130. vertexData.normals = normals;
  28131. vertexData.uvs = uvs;
  28132. return vertexData;
  28133. };
  28134. /**
  28135. * Creates the VertexData of the Disc or regular Polygon.
  28136. */
  28137. VertexData.CreateDisc = function (options) {
  28138. var positions = [];
  28139. var indices = [];
  28140. var normals = [];
  28141. var uvs = [];
  28142. var radius = options.radius || 0.5;
  28143. var tessellation = options.tessellation || 64;
  28144. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28145. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28146. // positions and uvs
  28147. positions.push(0, 0, 0); // disc center first
  28148. uvs.push(0.5, 0.5);
  28149. var theta = Math.PI * 2 * arc;
  28150. var step = theta / tessellation;
  28151. for (var a = 0; a < theta; a += step) {
  28152. var x = Math.cos(a);
  28153. var y = Math.sin(a);
  28154. var u = (x + 1) / 2;
  28155. var v = (1 - y) / 2;
  28156. positions.push(radius * x, radius * y, 0);
  28157. uvs.push(u, v);
  28158. }
  28159. if (arc === 1) {
  28160. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28161. uvs.push(uvs[2], uvs[3]);
  28162. }
  28163. //indices
  28164. var vertexNb = positions.length / 3;
  28165. for (var i = 1; i < vertexNb - 1; i++) {
  28166. indices.push(i + 1, 0, i);
  28167. }
  28168. // result
  28169. VertexData.ComputeNormals(positions, indices, normals);
  28170. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28171. var vertexData = new VertexData();
  28172. vertexData.indices = indices;
  28173. vertexData.positions = positions;
  28174. vertexData.normals = normals;
  28175. vertexData.uvs = uvs;
  28176. return vertexData;
  28177. };
  28178. /**
  28179. * Re-creates the VertexData of the Polygon for sideOrientation.
  28180. */
  28181. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  28182. var faceUV = fUV || new Array(3);
  28183. var faceColors = fColors;
  28184. var colors = [];
  28185. // default face colors and UV if undefined
  28186. for (var f = 0; f < 3; f++) {
  28187. if (faceUV[f] === undefined) {
  28188. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28189. }
  28190. if (faceColors && faceColors[f] === undefined) {
  28191. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28192. }
  28193. }
  28194. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28195. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28196. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28197. var indices = polygon.getIndices();
  28198. // set face colours and textures
  28199. var idx = 0;
  28200. var face = 0;
  28201. for (var index = 0; index < normals.length; index += 3) {
  28202. //Edge Face no. 1
  28203. if (Math.abs(normals[index + 1]) < 0.001) {
  28204. face = 1;
  28205. }
  28206. //Top Face no. 0
  28207. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  28208. face = 0;
  28209. }
  28210. //Bottom Face no. 2
  28211. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  28212. face = 2;
  28213. }
  28214. idx = index / 3;
  28215. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  28216. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  28217. if (faceColors) {
  28218. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  28219. }
  28220. }
  28221. // sides
  28222. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  28223. // Result
  28224. var vertexData = new VertexData();
  28225. vertexData.indices = indices;
  28226. vertexData.positions = positions;
  28227. vertexData.normals = normals;
  28228. vertexData.uvs = uvs;
  28229. if (faceColors) {
  28230. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28231. vertexData.colors = totalColors;
  28232. }
  28233. return vertexData;
  28234. };
  28235. /**
  28236. * Creates the VertexData of the IcoSphere.
  28237. */
  28238. VertexData.CreateIcoSphere = function (options) {
  28239. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28240. var radius = options.radius || 1;
  28241. var flat = (options.flat === undefined) ? true : options.flat;
  28242. var subdivisions = options.subdivisions || 4;
  28243. var radiusX = options.radiusX || radius;
  28244. var radiusY = options.radiusY || radius;
  28245. var radiusZ = options.radiusZ || radius;
  28246. var t = (1 + Math.sqrt(5)) / 2;
  28247. // 12 vertex x,y,z
  28248. var ico_vertices = [
  28249. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28250. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28251. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28252. ];
  28253. // index of 3 vertex makes a face of icopshere
  28254. var ico_indices = [
  28255. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28256. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28257. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28258. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28259. ];
  28260. // vertex for uv have aliased position, not for UV
  28261. var vertices_unalias_id = [
  28262. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28263. // vertex alias
  28264. 0,
  28265. 2,
  28266. 3,
  28267. 3,
  28268. 3,
  28269. 4,
  28270. 7,
  28271. 8,
  28272. 9,
  28273. 9,
  28274. 10,
  28275. 11 // 23: B + 12
  28276. ];
  28277. // uv as integer step (not pixels !)
  28278. var ico_vertexuv = [
  28279. 5, 1, 3, 1, 6, 4, 0, 0,
  28280. 5, 3, 4, 2, 2, 2, 4, 0,
  28281. 2, 0, 1, 1, 6, 0, 6, 2,
  28282. // vertex alias (for same vertex on different faces)
  28283. 0, 4,
  28284. 3, 3,
  28285. 4, 4,
  28286. 3, 1,
  28287. 4, 2,
  28288. 4, 4,
  28289. 0, 2,
  28290. 1, 1,
  28291. 2, 2,
  28292. 3, 3,
  28293. 1, 3,
  28294. 2, 4 // 23: B + 12
  28295. ];
  28296. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28297. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28298. // First island of uv mapping
  28299. // v = 4h 3+ 2
  28300. // v = 3h 9+ 4
  28301. // v = 2h 9+ 5 B
  28302. // v = 1h 9 1 0
  28303. // v = 0h 3 8 7 A
  28304. // u = 0 1 2 3 4 5 6 *a
  28305. // Second island of uv mapping
  28306. // v = 4h 0+ B+ 4+
  28307. // v = 3h A+ 2+
  28308. // v = 2h 7+ 6 3+
  28309. // v = 1h 8+ 3+
  28310. // v = 0h
  28311. // u = 0 1 2 3 4 5 6 *a
  28312. // Face layout on texture UV mapping
  28313. // ============
  28314. // \ 4 /\ 16 / ======
  28315. // \ / \ / /\ 11 /
  28316. // \/ 7 \/ / \ /
  28317. // ======= / 10 \/
  28318. // /\ 17 /\ =======
  28319. // / \ / \ \ 15 /\
  28320. // / 8 \/ 12 \ \ / \
  28321. // ============ \/ 6 \
  28322. // \ 18 /\ ============
  28323. // \ / \ \ 5 /\ 0 /
  28324. // \/ 13 \ \ / \ /
  28325. // ======= \/ 1 \/
  28326. // =============
  28327. // /\ 19 /\ 2 /\
  28328. // / \ / \ / \
  28329. // / 14 \/ 9 \/ 3 \
  28330. // ===================
  28331. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28332. var ustep = 138 / 1024;
  28333. var vstep = 239 / 1024;
  28334. var uoffset = 60 / 1024;
  28335. var voffset = 26 / 1024;
  28336. // Second island should have margin, not to touch the first island
  28337. // avoid any borderline artefact in pixel rounding
  28338. var island_u_offset = -40 / 1024;
  28339. var island_v_offset = +20 / 1024;
  28340. // face is either island 0 or 1 :
  28341. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28342. var island = [
  28343. 0, 0, 0, 0, 1,
  28344. 0, 0, 1, 1, 0,
  28345. 0, 0, 1, 1, 0,
  28346. 0, 1, 1, 1, 0 // 15 - 19
  28347. ];
  28348. var indices = [];
  28349. var positions = [];
  28350. var normals = [];
  28351. var uvs = [];
  28352. var current_indice = 0;
  28353. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28354. var face_vertex_pos = new Array(3);
  28355. var face_vertex_uv = new Array(3);
  28356. var v012;
  28357. for (v012 = 0; v012 < 3; v012++) {
  28358. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28359. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28360. }
  28361. // create all with normals
  28362. for (var face = 0; face < 20; face++) {
  28363. // 3 vertex per face
  28364. for (v012 = 0; v012 < 3; v012++) {
  28365. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28366. var v_id = ico_indices[3 * face + v012];
  28367. // vertex have 3D position (x,y,z)
  28368. 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]);
  28369. // Normalize to get normal, then scale to radius
  28370. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28371. // uv Coordinates from vertex ID
  28372. 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);
  28373. }
  28374. // Subdivide the face (interpolate pos, norm, uv)
  28375. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28376. // - norm is linear interpolation of vertex corner normal
  28377. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28378. // - uv is linear interpolation
  28379. //
  28380. // Topology is as below for sub-divide by 2
  28381. // vertex shown as v0,v1,v2
  28382. // interp index is i1 to progress in range [v0,v1[
  28383. // interp index is i2 to progress in range [v0,v2[
  28384. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28385. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28386. //
  28387. //
  28388. // i2 v2
  28389. // ^ ^
  28390. // / / \
  28391. // / / \
  28392. // / / \
  28393. // / / (0,1) \
  28394. // / #---------\
  28395. // / / \ (0,0)'/ \
  28396. // / / \ / \
  28397. // / / \ / \
  28398. // / / (0,0) \ / (1,0) \
  28399. // / #---------#---------\
  28400. // v0 v1
  28401. //
  28402. // --------------------> i1
  28403. //
  28404. // interp of (i1,i2):
  28405. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28406. // along i1 : lerp(x0,x1, i1/(S-i2))
  28407. //
  28408. // centroid of triangle is needed to get help normal computation
  28409. // (c1,c2) are used for centroid location
  28410. var interp_vertex = function (i1, i2, c1, c2) {
  28411. // vertex is interpolated from
  28412. // - face_vertex_pos[0..2]
  28413. // - face_vertex_uv[0..2]
  28414. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28415. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28416. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28417. pos_interp.normalize();
  28418. var vertex_normal;
  28419. if (flat) {
  28420. // in flat mode, recalculate normal as face centroid normal
  28421. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28422. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28423. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28424. }
  28425. else {
  28426. // in smooth mode, recalculate normal from each single vertex position
  28427. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28428. }
  28429. // Vertex normal need correction due to X,Y,Z radius scaling
  28430. vertex_normal.x /= radiusX;
  28431. vertex_normal.y /= radiusY;
  28432. vertex_normal.z /= radiusZ;
  28433. vertex_normal.normalize();
  28434. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28435. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28436. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28437. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28438. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28439. uvs.push(uv_interp.x, uv_interp.y);
  28440. // push each vertex has member of a face
  28441. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28442. indices.push(current_indice);
  28443. current_indice++;
  28444. };
  28445. for (var i2 = 0; i2 < subdivisions; i2++) {
  28446. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28447. // face : (i1,i2) for /\ :
  28448. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28449. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28450. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28451. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28452. if (i1 + i2 + 1 < subdivisions) {
  28453. // face : (i1,i2)' for \/ :
  28454. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28455. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28456. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28457. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28458. }
  28459. }
  28460. }
  28461. }
  28462. // Sides
  28463. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28464. // Result
  28465. var vertexData = new VertexData();
  28466. vertexData.indices = indices;
  28467. vertexData.positions = positions;
  28468. vertexData.normals = normals;
  28469. vertexData.uvs = uvs;
  28470. return vertexData;
  28471. };
  28472. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28473. /**
  28474. * Creates the VertexData of the Polyhedron.
  28475. */
  28476. VertexData.CreatePolyhedron = function (options) {
  28477. // provided polyhedron types :
  28478. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28479. // 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)
  28480. var polyhedra = [];
  28481. 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]] };
  28482. 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]] };
  28483. polyhedra[2] = {
  28484. 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]],
  28485. 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]]
  28486. };
  28487. polyhedra[3] = {
  28488. 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]],
  28489. 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]]
  28490. };
  28491. polyhedra[4] = {
  28492. 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]],
  28493. 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]]
  28494. };
  28495. 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]] };
  28496. 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]] };
  28497. 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]] };
  28498. 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]] };
  28499. 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]] };
  28500. 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]] };
  28501. 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]] };
  28502. 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]] };
  28503. 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]] };
  28504. polyhedra[14] = {
  28505. 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]],
  28506. 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]]
  28507. };
  28508. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28509. var size = options.size;
  28510. var sizeX = options.sizeX || size || 1;
  28511. var sizeY = options.sizeY || size || 1;
  28512. var sizeZ = options.sizeZ || size || 1;
  28513. var data = options.custom || polyhedra[type];
  28514. var nbfaces = data.face.length;
  28515. var faceUV = options.faceUV || new Array(nbfaces);
  28516. var faceColors = options.faceColors;
  28517. var flat = (options.flat === undefined) ? true : options.flat;
  28518. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28519. var positions = [];
  28520. var indices = [];
  28521. var normals = [];
  28522. var uvs = [];
  28523. var colors = [];
  28524. var index = 0;
  28525. var faceIdx = 0; // face cursor in the array "indexes"
  28526. var indexes = [];
  28527. var i = 0;
  28528. var f = 0;
  28529. var u, v, ang, x, y, tmp;
  28530. // default face colors and UV if undefined
  28531. if (flat) {
  28532. for (f = 0; f < nbfaces; f++) {
  28533. if (faceColors && faceColors[f] === undefined) {
  28534. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28535. }
  28536. if (faceUV && faceUV[f] === undefined) {
  28537. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28538. }
  28539. }
  28540. }
  28541. if (!flat) {
  28542. for (i = 0; i < data.vertex.length; i++) {
  28543. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28544. uvs.push(0, 0);
  28545. }
  28546. for (f = 0; f < nbfaces; f++) {
  28547. for (i = 0; i < data.face[f].length - 2; i++) {
  28548. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28549. }
  28550. }
  28551. }
  28552. else {
  28553. for (f = 0; f < nbfaces; f++) {
  28554. var fl = data.face[f].length; // number of vertices of the current face
  28555. ang = 2 * Math.PI / fl;
  28556. x = 0.5 * Math.tan(ang / 2);
  28557. y = 0.5;
  28558. // positions, uvs, colors
  28559. for (i = 0; i < fl; i++) {
  28560. // positions
  28561. 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);
  28562. indexes.push(index);
  28563. index++;
  28564. // uvs
  28565. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28566. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28567. uvs.push(u, v);
  28568. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28569. y = x * Math.sin(ang) + y * Math.cos(ang);
  28570. x = tmp;
  28571. // colors
  28572. if (faceColors) {
  28573. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28574. }
  28575. }
  28576. // indices from indexes
  28577. for (i = 0; i < fl - 2; i++) {
  28578. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28579. }
  28580. faceIdx += fl;
  28581. }
  28582. }
  28583. VertexData.ComputeNormals(positions, indices, normals);
  28584. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28585. var vertexData = new VertexData();
  28586. vertexData.positions = positions;
  28587. vertexData.indices = indices;
  28588. vertexData.normals = normals;
  28589. vertexData.uvs = uvs;
  28590. if (faceColors && flat) {
  28591. vertexData.colors = colors;
  28592. }
  28593. return vertexData;
  28594. };
  28595. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28596. /**
  28597. * Creates the VertexData of the Torus Knot.
  28598. */
  28599. VertexData.CreateTorusKnot = function (options) {
  28600. var indices = [];
  28601. var positions = [];
  28602. var normals = [];
  28603. var uvs = [];
  28604. var radius = options.radius || 2;
  28605. var tube = options.tube || 0.5;
  28606. var radialSegments = options.radialSegments || 32;
  28607. var tubularSegments = options.tubularSegments || 32;
  28608. var p = options.p || 2;
  28609. var q = options.q || 3;
  28610. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28611. // Helper
  28612. var getPos = function (angle) {
  28613. var cu = Math.cos(angle);
  28614. var su = Math.sin(angle);
  28615. var quOverP = q / p * angle;
  28616. var cs = Math.cos(quOverP);
  28617. var tx = radius * (2 + cs) * 0.5 * cu;
  28618. var ty = radius * (2 + cs) * su * 0.5;
  28619. var tz = radius * Math.sin(quOverP) * 0.5;
  28620. return new BABYLON.Vector3(tx, ty, tz);
  28621. };
  28622. // Vertices
  28623. var i;
  28624. var j;
  28625. for (i = 0; i <= radialSegments; i++) {
  28626. var modI = i % radialSegments;
  28627. var u = modI / radialSegments * 2 * p * Math.PI;
  28628. var p1 = getPos(u);
  28629. var p2 = getPos(u + 0.01);
  28630. var tang = p2.subtract(p1);
  28631. var n = p2.add(p1);
  28632. var bitan = BABYLON.Vector3.Cross(tang, n);
  28633. n = BABYLON.Vector3.Cross(bitan, tang);
  28634. bitan.normalize();
  28635. n.normalize();
  28636. for (j = 0; j < tubularSegments; j++) {
  28637. var modJ = j % tubularSegments;
  28638. var v = modJ / tubularSegments * 2 * Math.PI;
  28639. var cx = -tube * Math.cos(v);
  28640. var cy = tube * Math.sin(v);
  28641. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28642. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28643. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28644. uvs.push(i / radialSegments);
  28645. uvs.push(j / tubularSegments);
  28646. }
  28647. }
  28648. for (i = 0; i < radialSegments; i++) {
  28649. for (j = 0; j < tubularSegments; j++) {
  28650. var jNext = (j + 1) % tubularSegments;
  28651. var a = i * tubularSegments + j;
  28652. var b = (i + 1) * tubularSegments + j;
  28653. var c = (i + 1) * tubularSegments + jNext;
  28654. var d = i * tubularSegments + jNext;
  28655. indices.push(d);
  28656. indices.push(b);
  28657. indices.push(a);
  28658. indices.push(d);
  28659. indices.push(c);
  28660. indices.push(b);
  28661. }
  28662. }
  28663. // Normals
  28664. VertexData.ComputeNormals(positions, indices, normals);
  28665. // Sides
  28666. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28667. // Result
  28668. var vertexData = new VertexData();
  28669. vertexData.indices = indices;
  28670. vertexData.positions = positions;
  28671. vertexData.normals = normals;
  28672. vertexData.uvs = uvs;
  28673. return vertexData;
  28674. };
  28675. // Tools
  28676. /**
  28677. * @param {any} - positions (number[] or Float32Array)
  28678. * @param {any} - indices (number[] or Uint16Array)
  28679. * @param {any} - normals (number[] or Float32Array)
  28680. * options (optional) :
  28681. * facetPositions : optional array of facet positions (vector3)
  28682. * facetNormals : optional array of facet normals (vector3)
  28683. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28684. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28685. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28686. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28687. * bInfo : optional bounding info, required for facetPartitioning computation
  28688. */
  28689. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28690. // temporary scalar variables
  28691. var index = 0; // facet index
  28692. var p1p2x = 0.0; // p1p2 vector x coordinate
  28693. var p1p2y = 0.0; // p1p2 vector y coordinate
  28694. var p1p2z = 0.0; // p1p2 vector z coordinate
  28695. var p3p2x = 0.0; // p3p2 vector x coordinate
  28696. var p3p2y = 0.0; // p3p2 vector y coordinate
  28697. var p3p2z = 0.0; // p3p2 vector z coordinate
  28698. var faceNormalx = 0.0; // facet normal x coordinate
  28699. var faceNormaly = 0.0; // facet normal y coordinate
  28700. var faceNormalz = 0.0; // facet normal z coordinate
  28701. var length = 0.0; // facet normal length before normalization
  28702. var v1x = 0; // vector1 x index in the positions array
  28703. var v1y = 0; // vector1 y index in the positions array
  28704. var v1z = 0; // vector1 z index in the positions array
  28705. var v2x = 0; // vector2 x index in the positions array
  28706. var v2y = 0; // vector2 y index in the positions array
  28707. var v2z = 0; // vector2 z index in the positions array
  28708. var v3x = 0; // vector3 x index in the positions array
  28709. var v3y = 0; // vector3 y index in the positions array
  28710. var v3z = 0; // vector3 z index in the positions array
  28711. var computeFacetNormals = false;
  28712. var computeFacetPositions = false;
  28713. var computeFacetPartitioning = false;
  28714. var faceNormalSign = 1;
  28715. if (options) {
  28716. computeFacetNormals = (options.facetNormals) ? true : false;
  28717. computeFacetPositions = (options.facetPositions) ? true : false;
  28718. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28719. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28720. }
  28721. // facetPartitioning reinit if needed
  28722. if (computeFacetPartitioning) {
  28723. var ox = 0; // X partitioning index for facet position
  28724. var oy = 0; // Y partinioning index for facet position
  28725. var oz = 0; // Z partinioning index for facet position
  28726. var b1x = 0; // X partitioning index for facet v1 vertex
  28727. var b1y = 0; // Y partitioning index for facet v1 vertex
  28728. var b1z = 0; // z partitioning index for facet v1 vertex
  28729. var b2x = 0; // X partitioning index for facet v2 vertex
  28730. var b2y = 0; // Y partitioning index for facet v2 vertex
  28731. var b2z = 0; // Z partitioning index for facet v2 vertex
  28732. var b3x = 0; // X partitioning index for facet v3 vertex
  28733. var b3y = 0; // Y partitioning index for facet v3 vertex
  28734. var b3z = 0; // Z partitioning index for facet v3 vertex
  28735. var block_idx_o = 0; // facet barycenter block index
  28736. var block_idx_v1 = 0; // v1 vertex block index
  28737. var block_idx_v2 = 0; // v2 vertex block index
  28738. var block_idx_v3 = 0; // v3 vertex block index
  28739. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28740. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28741. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28742. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28743. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28744. var subSq = options.subDiv.max * options.subDiv.max;
  28745. options.facetPartitioning.length = 0;
  28746. }
  28747. // reset the normals
  28748. for (index = 0; index < positions.length; index++) {
  28749. normals[index] = 0.0;
  28750. }
  28751. // Loop : 1 indice triplet = 1 facet
  28752. var nbFaces = indices.length / 3;
  28753. for (index = 0; index < nbFaces; index++) {
  28754. // get the indexes of the coordinates of each vertex of the facet
  28755. v1x = indices[index * 3] * 3;
  28756. v1y = v1x + 1;
  28757. v1z = v1x + 2;
  28758. v2x = indices[index * 3 + 1] * 3;
  28759. v2y = v2x + 1;
  28760. v2z = v2x + 2;
  28761. v3x = indices[index * 3 + 2] * 3;
  28762. v3y = v3x + 1;
  28763. v3z = v3x + 2;
  28764. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28765. p1p2y = positions[v1y] - positions[v2y];
  28766. p1p2z = positions[v1z] - positions[v2z];
  28767. p3p2x = positions[v3x] - positions[v2x];
  28768. p3p2y = positions[v3y] - positions[v2y];
  28769. p3p2z = positions[v3z] - positions[v2z];
  28770. // compute the face normal with the cross product
  28771. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28772. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28773. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28774. // normalize this normal and store it in the array facetData
  28775. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28776. length = (length === 0) ? 1.0 : length;
  28777. faceNormalx /= length;
  28778. faceNormaly /= length;
  28779. faceNormalz /= length;
  28780. if (computeFacetNormals) {
  28781. options.facetNormals[index].x = faceNormalx;
  28782. options.facetNormals[index].y = faceNormaly;
  28783. options.facetNormals[index].z = faceNormalz;
  28784. }
  28785. if (computeFacetPositions) {
  28786. // compute and the facet barycenter coordinates in the array facetPositions
  28787. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28788. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28789. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28790. }
  28791. if (computeFacetPartitioning) {
  28792. // store the facet indexes in arrays in the main facetPartitioning array :
  28793. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28794. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28795. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28796. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28797. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28798. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28799. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28800. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28801. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28802. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28803. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28804. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28805. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28806. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28807. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28808. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28809. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28810. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28811. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28812. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28813. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28814. // push each facet index in each block containing the vertex
  28815. options.facetPartitioning[block_idx_v1].push(index);
  28816. if (block_idx_v2 != block_idx_v1) {
  28817. options.facetPartitioning[block_idx_v2].push(index);
  28818. }
  28819. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28820. options.facetPartitioning[block_idx_v3].push(index);
  28821. }
  28822. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28823. options.facetPartitioning[block_idx_o].push(index);
  28824. }
  28825. }
  28826. // compute the normals anyway
  28827. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28828. normals[v1y] += faceNormaly;
  28829. normals[v1z] += faceNormalz;
  28830. normals[v2x] += faceNormalx;
  28831. normals[v2y] += faceNormaly;
  28832. normals[v2z] += faceNormalz;
  28833. normals[v3x] += faceNormalx;
  28834. normals[v3y] += faceNormaly;
  28835. normals[v3z] += faceNormalz;
  28836. }
  28837. // last normalization of each normal
  28838. for (index = 0; index < normals.length / 3; index++) {
  28839. faceNormalx = normals[index * 3];
  28840. faceNormaly = normals[index * 3 + 1];
  28841. faceNormalz = normals[index * 3 + 2];
  28842. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28843. length = (length === 0) ? 1.0 : length;
  28844. faceNormalx /= length;
  28845. faceNormaly /= length;
  28846. faceNormalz /= length;
  28847. normals[index * 3] = faceNormalx;
  28848. normals[index * 3 + 1] = faceNormaly;
  28849. normals[index * 3 + 2] = faceNormalz;
  28850. }
  28851. };
  28852. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28853. var li = indices.length;
  28854. var ln = normals.length;
  28855. var i;
  28856. var n;
  28857. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28858. switch (sideOrientation) {
  28859. case BABYLON.Mesh.FRONTSIDE:
  28860. // nothing changed
  28861. break;
  28862. case BABYLON.Mesh.BACKSIDE:
  28863. var tmp;
  28864. // indices
  28865. for (i = 0; i < li; i += 3) {
  28866. tmp = indices[i];
  28867. indices[i] = indices[i + 2];
  28868. indices[i + 2] = tmp;
  28869. }
  28870. // normals
  28871. for (n = 0; n < ln; n++) {
  28872. normals[n] = -normals[n];
  28873. }
  28874. break;
  28875. case BABYLON.Mesh.DOUBLESIDE:
  28876. // positions
  28877. var lp = positions.length;
  28878. var l = lp / 3;
  28879. for (var p = 0; p < lp; p++) {
  28880. positions[lp + p] = positions[p];
  28881. }
  28882. // indices
  28883. for (i = 0; i < li; i += 3) {
  28884. indices[i + li] = indices[i + 2] + l;
  28885. indices[i + 1 + li] = indices[i + 1] + l;
  28886. indices[i + 2 + li] = indices[i] + l;
  28887. }
  28888. // normals
  28889. for (n = 0; n < ln; n++) {
  28890. normals[ln + n] = -normals[n];
  28891. }
  28892. // uvs
  28893. var lu = uvs.length;
  28894. var u = 0;
  28895. for (u = 0; u < lu; u++) {
  28896. uvs[u + lu] = uvs[u];
  28897. }
  28898. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28899. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28900. u = 0;
  28901. for (i = 0; i < lu / 2; i++) {
  28902. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28903. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28904. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28905. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28906. u += 2;
  28907. }
  28908. break;
  28909. }
  28910. };
  28911. /**
  28912. * Creates a new VertexData from the imported parameters.
  28913. */
  28914. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28915. var vertexData = new VertexData();
  28916. // positions
  28917. var positions = parsedVertexData.positions;
  28918. if (positions) {
  28919. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28920. }
  28921. // normals
  28922. var normals = parsedVertexData.normals;
  28923. if (normals) {
  28924. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28925. }
  28926. // tangents
  28927. var tangents = parsedVertexData.tangents;
  28928. if (tangents) {
  28929. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28930. }
  28931. // uvs
  28932. var uvs = parsedVertexData.uvs;
  28933. if (uvs) {
  28934. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28935. }
  28936. // uv2s
  28937. var uv2s = parsedVertexData.uv2s;
  28938. if (uv2s) {
  28939. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28940. }
  28941. // uv3s
  28942. var uv3s = parsedVertexData.uv3s;
  28943. if (uv3s) {
  28944. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28945. }
  28946. // uv4s
  28947. var uv4s = parsedVertexData.uv4s;
  28948. if (uv4s) {
  28949. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28950. }
  28951. // uv5s
  28952. var uv5s = parsedVertexData.uv5s;
  28953. if (uv5s) {
  28954. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28955. }
  28956. // uv6s
  28957. var uv6s = parsedVertexData.uv6s;
  28958. if (uv6s) {
  28959. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28960. }
  28961. // colors
  28962. var colors = parsedVertexData.colors;
  28963. if (colors) {
  28964. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28965. }
  28966. // matricesIndices
  28967. var matricesIndices = parsedVertexData.matricesIndices;
  28968. if (matricesIndices) {
  28969. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28970. }
  28971. // matricesWeights
  28972. var matricesWeights = parsedVertexData.matricesWeights;
  28973. if (matricesWeights) {
  28974. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28975. }
  28976. // indices
  28977. var indices = parsedVertexData.indices;
  28978. if (indices) {
  28979. vertexData.indices = indices;
  28980. }
  28981. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28982. };
  28983. return VertexData;
  28984. }());
  28985. BABYLON.VertexData = VertexData;
  28986. })(BABYLON || (BABYLON = {}));
  28987. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28988. var BABYLON;
  28989. (function (BABYLON) {
  28990. var Geometry = (function () {
  28991. function Geometry(id, scene, vertexData, updatable, mesh) {
  28992. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28993. this._totalVertices = 0;
  28994. this._isDisposed = false;
  28995. this.id = id;
  28996. this._engine = scene.getEngine();
  28997. this._meshes = [];
  28998. this._scene = scene;
  28999. //Init vertex buffer cache
  29000. this._vertexBuffers = {};
  29001. this._indices = [];
  29002. this._updatable = updatable;
  29003. // vertexData
  29004. if (vertexData) {
  29005. this.setAllVerticesData(vertexData, updatable);
  29006. }
  29007. else {
  29008. this._totalVertices = 0;
  29009. this._indices = [];
  29010. }
  29011. if (this._engine.getCaps().vertexArrayObject) {
  29012. this._vertexArrayObjects = {};
  29013. }
  29014. // applyToMesh
  29015. if (mesh) {
  29016. if (mesh.getClassName() === "LinesMesh") {
  29017. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  29018. this.updateExtend();
  29019. }
  29020. this.applyToMesh(mesh);
  29021. mesh.computeWorldMatrix(true);
  29022. }
  29023. }
  29024. Object.defineProperty(Geometry.prototype, "boundingBias", {
  29025. /**
  29026. * 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
  29027. * @returns The Bias Vector
  29028. */
  29029. get: function () {
  29030. return this._boundingBias;
  29031. },
  29032. set: function (value) {
  29033. if (this._boundingBias && this._boundingBias.equals(value)) {
  29034. return;
  29035. }
  29036. this._boundingBias = value.clone();
  29037. this.updateBoundingInfo(true, null);
  29038. },
  29039. enumerable: true,
  29040. configurable: true
  29041. });
  29042. Object.defineProperty(Geometry.prototype, "extend", {
  29043. get: function () {
  29044. return this._extend;
  29045. },
  29046. enumerable: true,
  29047. configurable: true
  29048. });
  29049. Geometry.prototype.getScene = function () {
  29050. return this._scene;
  29051. };
  29052. Geometry.prototype.getEngine = function () {
  29053. return this._engine;
  29054. };
  29055. Geometry.prototype.isReady = function () {
  29056. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29057. };
  29058. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  29059. get: function () {
  29060. for (var index = 0; index < this._meshes.length; index++) {
  29061. if (!this._meshes[index].doNotSerialize) {
  29062. return false;
  29063. }
  29064. }
  29065. return true;
  29066. },
  29067. enumerable: true,
  29068. configurable: true
  29069. });
  29070. Geometry.prototype._rebuild = function () {
  29071. if (this._vertexArrayObjects) {
  29072. this._vertexArrayObjects = {};
  29073. }
  29074. // Index buffer
  29075. if (this._meshes.length !== 0 && this._indices) {
  29076. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29077. }
  29078. // Vertex buffers
  29079. for (var key in this._vertexBuffers) {
  29080. var vertexBuffer = this._vertexBuffers[key];
  29081. vertexBuffer._rebuild();
  29082. }
  29083. };
  29084. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29085. vertexData.applyToGeometry(this, updatable);
  29086. this.notifyUpdate();
  29087. };
  29088. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29089. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29090. this.setVerticesBuffer(buffer);
  29091. };
  29092. Geometry.prototype.removeVerticesData = function (kind) {
  29093. if (this._vertexBuffers[kind]) {
  29094. this._vertexBuffers[kind].dispose();
  29095. delete this._vertexBuffers[kind];
  29096. }
  29097. };
  29098. Geometry.prototype.setVerticesBuffer = function (buffer) {
  29099. var kind = buffer.getKind();
  29100. if (this._vertexBuffers[kind]) {
  29101. this._vertexBuffers[kind].dispose();
  29102. }
  29103. this._vertexBuffers[kind] = buffer;
  29104. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29105. var data = buffer.getData();
  29106. var stride = buffer.getStrideSize();
  29107. this._totalVertices = data.length / stride;
  29108. this.updateExtend(data, stride);
  29109. this._resetPointsArrayCache();
  29110. var meshes = this._meshes;
  29111. var numOfMeshes = meshes.length;
  29112. for (var index = 0; index < numOfMeshes; index++) {
  29113. var mesh = meshes[index];
  29114. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29115. mesh._createGlobalSubMesh(false);
  29116. mesh.computeWorldMatrix(true);
  29117. }
  29118. }
  29119. this.notifyUpdate(kind);
  29120. if (this._vertexArrayObjects) {
  29121. this._disposeVertexArrayObjects();
  29122. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  29123. }
  29124. };
  29125. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29126. var vertexBuffer = this.getVertexBuffer(kind);
  29127. if (!vertexBuffer) {
  29128. return;
  29129. }
  29130. vertexBuffer.updateDirectly(data, offset);
  29131. this.notifyUpdate(kind);
  29132. };
  29133. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29134. var vertexBuffer = this.getVertexBuffer(kind);
  29135. if (!vertexBuffer) {
  29136. return;
  29137. }
  29138. vertexBuffer.update(data);
  29139. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29140. var stride = vertexBuffer.getStrideSize();
  29141. this._totalVertices = data.length / stride;
  29142. this.updateBoundingInfo(updateExtends, data);
  29143. }
  29144. this.notifyUpdate(kind);
  29145. };
  29146. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  29147. if (updateExtends) {
  29148. this.updateExtend(data);
  29149. }
  29150. var meshes = this._meshes;
  29151. var numOfMeshes = meshes.length;
  29152. this._resetPointsArrayCache();
  29153. for (var index = 0; index < numOfMeshes; index++) {
  29154. var mesh = meshes[index];
  29155. if (updateExtends) {
  29156. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29157. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29158. var subMesh = mesh.subMeshes[subIndex];
  29159. subMesh.refreshBoundingInfo();
  29160. }
  29161. }
  29162. }
  29163. };
  29164. Geometry.prototype._bind = function (effect, indexToBind) {
  29165. if (indexToBind === void 0) { indexToBind = undefined; }
  29166. if (indexToBind === undefined) {
  29167. indexToBind = this._indexBuffer;
  29168. }
  29169. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  29170. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  29171. return;
  29172. }
  29173. // Using VAO
  29174. if (!this._vertexArrayObjects[effect.key]) {
  29175. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  29176. }
  29177. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  29178. };
  29179. Geometry.prototype.getTotalVertices = function () {
  29180. if (!this.isReady()) {
  29181. return 0;
  29182. }
  29183. return this._totalVertices;
  29184. };
  29185. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29186. var vertexBuffer = this.getVertexBuffer(kind);
  29187. if (!vertexBuffer) {
  29188. return null;
  29189. }
  29190. var orig = vertexBuffer.getData();
  29191. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  29192. return orig;
  29193. }
  29194. else {
  29195. var len = orig.length;
  29196. var copy = [];
  29197. for (var i = 0; i < len; i++) {
  29198. copy.push(orig[i]);
  29199. }
  29200. return copy;
  29201. }
  29202. };
  29203. Geometry.prototype.getVertexBuffer = function (kind) {
  29204. if (!this.isReady()) {
  29205. return null;
  29206. }
  29207. return this._vertexBuffers[kind];
  29208. };
  29209. Geometry.prototype.getVertexBuffers = function () {
  29210. if (!this.isReady()) {
  29211. return null;
  29212. }
  29213. return this._vertexBuffers;
  29214. };
  29215. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29216. if (!this._vertexBuffers) {
  29217. if (this._delayInfo) {
  29218. return this._delayInfo.indexOf(kind) !== -1;
  29219. }
  29220. return false;
  29221. }
  29222. return this._vertexBuffers[kind] !== undefined;
  29223. };
  29224. Geometry.prototype.getVerticesDataKinds = function () {
  29225. var result = [];
  29226. var kind;
  29227. if (!this._vertexBuffers && this._delayInfo) {
  29228. for (kind in this._delayInfo) {
  29229. result.push(kind);
  29230. }
  29231. }
  29232. else {
  29233. for (kind in this._vertexBuffers) {
  29234. result.push(kind);
  29235. }
  29236. }
  29237. return result;
  29238. };
  29239. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29240. if (this._indexBuffer) {
  29241. this._engine._releaseBuffer(this._indexBuffer);
  29242. }
  29243. this._disposeVertexArrayObjects();
  29244. this._indices = indices;
  29245. if (this._meshes.length !== 0 && this._indices) {
  29246. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29247. }
  29248. if (totalVertices !== undefined) {
  29249. this._totalVertices = totalVertices;
  29250. }
  29251. var meshes = this._meshes;
  29252. var numOfMeshes = meshes.length;
  29253. for (var index = 0; index < numOfMeshes; index++) {
  29254. meshes[index]._createGlobalSubMesh(true);
  29255. }
  29256. this.notifyUpdate();
  29257. };
  29258. Geometry.prototype.getTotalIndices = function () {
  29259. if (!this.isReady()) {
  29260. return 0;
  29261. }
  29262. return this._indices.length;
  29263. };
  29264. Geometry.prototype.getIndices = function (copyWhenShared) {
  29265. if (!this.isReady()) {
  29266. return null;
  29267. }
  29268. var orig = this._indices;
  29269. if (!copyWhenShared || this._meshes.length === 1) {
  29270. return orig;
  29271. }
  29272. else {
  29273. var len = orig.length;
  29274. var copy = [];
  29275. for (var i = 0; i < len; i++) {
  29276. copy.push(orig[i]);
  29277. }
  29278. return copy;
  29279. }
  29280. };
  29281. Geometry.prototype.getIndexBuffer = function () {
  29282. if (!this.isReady()) {
  29283. return null;
  29284. }
  29285. return this._indexBuffer;
  29286. };
  29287. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29288. if (!effect || !this._vertexArrayObjects) {
  29289. return;
  29290. }
  29291. if (this._vertexArrayObjects[effect.key]) {
  29292. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29293. delete this._vertexArrayObjects[effect.key];
  29294. }
  29295. };
  29296. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29297. var meshes = this._meshes;
  29298. var index = meshes.indexOf(mesh);
  29299. if (index === -1) {
  29300. return;
  29301. }
  29302. meshes.splice(index, 1);
  29303. mesh._geometry = null;
  29304. if (meshes.length === 0 && shouldDispose) {
  29305. this.dispose();
  29306. }
  29307. };
  29308. Geometry.prototype.applyToMesh = function (mesh) {
  29309. if (mesh._geometry === this) {
  29310. return;
  29311. }
  29312. var previousGeometry = mesh._geometry;
  29313. if (previousGeometry) {
  29314. previousGeometry.releaseForMesh(mesh);
  29315. }
  29316. var meshes = this._meshes;
  29317. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29318. mesh._geometry = this;
  29319. this._scene.pushGeometry(this);
  29320. meshes.push(mesh);
  29321. if (this.isReady()) {
  29322. this._applyToMesh(mesh);
  29323. }
  29324. else {
  29325. mesh._boundingInfo = this._boundingInfo;
  29326. }
  29327. };
  29328. Geometry.prototype.updateExtend = function (data, stride) {
  29329. if (data === void 0) { data = null; }
  29330. if (!data) {
  29331. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29332. }
  29333. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29334. };
  29335. Geometry.prototype._applyToMesh = function (mesh) {
  29336. var numOfMeshes = this._meshes.length;
  29337. // vertexBuffers
  29338. for (var kind in this._vertexBuffers) {
  29339. if (numOfMeshes === 1) {
  29340. this._vertexBuffers[kind].create();
  29341. }
  29342. var buffer = this._vertexBuffers[kind].getBuffer();
  29343. if (buffer)
  29344. buffer.references = numOfMeshes;
  29345. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29346. if (!this._extend) {
  29347. this.updateExtend(this._vertexBuffers[kind].getData());
  29348. }
  29349. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29350. mesh._createGlobalSubMesh(false);
  29351. //bounding info was just created again, world matrix should be applied again.
  29352. mesh._updateBoundingInfo();
  29353. }
  29354. }
  29355. // indexBuffer
  29356. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29357. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29358. }
  29359. if (this._indexBuffer) {
  29360. this._indexBuffer.references = numOfMeshes;
  29361. }
  29362. };
  29363. Geometry.prototype.notifyUpdate = function (kind) {
  29364. if (this.onGeometryUpdated) {
  29365. this.onGeometryUpdated(this, kind);
  29366. }
  29367. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29368. var mesh = _a[_i];
  29369. mesh._markSubMeshesAsAttributesDirty();
  29370. }
  29371. };
  29372. Geometry.prototype.load = function (scene, onLoaded) {
  29373. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29374. return;
  29375. }
  29376. if (this.isReady()) {
  29377. if (onLoaded) {
  29378. onLoaded();
  29379. }
  29380. return;
  29381. }
  29382. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29383. this._queueLoad(scene, onLoaded);
  29384. };
  29385. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29386. var _this = this;
  29387. scene._addPendingData(this);
  29388. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29389. _this._delayLoadingFunction(JSON.parse(data), _this);
  29390. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29391. _this._delayInfo = [];
  29392. scene._removePendingData(_this);
  29393. var meshes = _this._meshes;
  29394. var numOfMeshes = meshes.length;
  29395. for (var index = 0; index < numOfMeshes; index++) {
  29396. _this._applyToMesh(meshes[index]);
  29397. }
  29398. if (onLoaded) {
  29399. onLoaded();
  29400. }
  29401. }, function () { }, scene.database);
  29402. };
  29403. /**
  29404. * Invert the geometry to move from a right handed system to a left handed one.
  29405. */
  29406. Geometry.prototype.toLeftHanded = function () {
  29407. // Flip faces
  29408. var tIndices = this.getIndices(false);
  29409. if (tIndices != null && tIndices.length > 0) {
  29410. for (var i = 0; i < tIndices.length; i += 3) {
  29411. var tTemp = tIndices[i + 0];
  29412. tIndices[i + 0] = tIndices[i + 2];
  29413. tIndices[i + 2] = tTemp;
  29414. }
  29415. this.setIndices(tIndices);
  29416. }
  29417. // Negate position.z
  29418. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29419. if (tPositions != null && tPositions.length > 0) {
  29420. for (var i = 0; i < tPositions.length; i += 3) {
  29421. tPositions[i + 2] = -tPositions[i + 2];
  29422. }
  29423. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29424. }
  29425. // Negate normal.z
  29426. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29427. if (tNormals != null && tNormals.length > 0) {
  29428. for (var i = 0; i < tNormals.length; i += 3) {
  29429. tNormals[i + 2] = -tNormals[i + 2];
  29430. }
  29431. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29432. }
  29433. };
  29434. // Cache
  29435. Geometry.prototype._resetPointsArrayCache = function () {
  29436. this._positions = null;
  29437. };
  29438. Geometry.prototype._generatePointsArray = function () {
  29439. if (this._positions)
  29440. return true;
  29441. this._positions = [];
  29442. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29443. if (!data) {
  29444. return false;
  29445. }
  29446. for (var index = 0; index < data.length; index += 3) {
  29447. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29448. }
  29449. return true;
  29450. };
  29451. Geometry.prototype.isDisposed = function () {
  29452. return this._isDisposed;
  29453. };
  29454. Geometry.prototype._disposeVertexArrayObjects = function () {
  29455. if (this._vertexArrayObjects) {
  29456. for (var kind in this._vertexArrayObjects) {
  29457. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29458. }
  29459. this._vertexArrayObjects = {};
  29460. }
  29461. };
  29462. Geometry.prototype.dispose = function () {
  29463. var meshes = this._meshes;
  29464. var numOfMeshes = meshes.length;
  29465. var index;
  29466. for (index = 0; index < numOfMeshes; index++) {
  29467. this.releaseForMesh(meshes[index]);
  29468. }
  29469. this._meshes = [];
  29470. this._disposeVertexArrayObjects();
  29471. for (var kind in this._vertexBuffers) {
  29472. this._vertexBuffers[kind].dispose();
  29473. }
  29474. this._vertexBuffers = {};
  29475. this._totalVertices = 0;
  29476. if (this._indexBuffer) {
  29477. this._engine._releaseBuffer(this._indexBuffer);
  29478. }
  29479. this._indexBuffer = null;
  29480. this._indices = [];
  29481. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29482. this.delayLoadingFile = null;
  29483. this._delayLoadingFunction = null;
  29484. this._delayInfo = [];
  29485. this._boundingInfo = null;
  29486. this._scene.removeGeometry(this);
  29487. this._isDisposed = true;
  29488. };
  29489. Geometry.prototype.copy = function (id) {
  29490. var vertexData = new BABYLON.VertexData();
  29491. vertexData.indices = [];
  29492. var indices = this.getIndices();
  29493. for (var index = 0; index < indices.length; index++) {
  29494. vertexData.indices.push(indices[index]);
  29495. }
  29496. var updatable = false;
  29497. var stopChecking = false;
  29498. var kind;
  29499. for (kind in this._vertexBuffers) {
  29500. // using slice() to make a copy of the array and not just reference it
  29501. var data = this.getVerticesData(kind);
  29502. if (data instanceof Float32Array) {
  29503. vertexData.set(new Float32Array(data), kind);
  29504. }
  29505. else {
  29506. vertexData.set(data.slice(0), kind);
  29507. }
  29508. if (!stopChecking) {
  29509. updatable = this.getVertexBuffer(kind).isUpdatable();
  29510. stopChecking = !updatable;
  29511. }
  29512. }
  29513. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29514. geometry.delayLoadState = this.delayLoadState;
  29515. geometry.delayLoadingFile = this.delayLoadingFile;
  29516. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29517. for (kind in this._delayInfo) {
  29518. geometry._delayInfo = geometry._delayInfo || [];
  29519. geometry._delayInfo.push(kind);
  29520. }
  29521. // Bounding info
  29522. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29523. return geometry;
  29524. };
  29525. Geometry.prototype.serialize = function () {
  29526. var serializationObject = {};
  29527. serializationObject.id = this.id;
  29528. serializationObject.updatable = this._updatable;
  29529. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29530. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29531. }
  29532. return serializationObject;
  29533. };
  29534. Geometry.prototype.toNumberArray = function (origin) {
  29535. if (Array.isArray(origin)) {
  29536. return origin;
  29537. }
  29538. else {
  29539. return Array.prototype.slice.call(origin);
  29540. }
  29541. };
  29542. Geometry.prototype.serializeVerticeData = function () {
  29543. var serializationObject = this.serialize();
  29544. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29545. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29546. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29547. serializationObject.positions._updatable = true;
  29548. }
  29549. }
  29550. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29551. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29552. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29553. serializationObject.normals._updatable = true;
  29554. }
  29555. }
  29556. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29557. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29558. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29559. serializationObject.uvs._updatable = true;
  29560. }
  29561. }
  29562. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29563. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29564. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29565. serializationObject.uv2s._updatable = true;
  29566. }
  29567. }
  29568. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29569. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29570. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29571. serializationObject.uv3s._updatable = true;
  29572. }
  29573. }
  29574. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29575. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29576. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29577. serializationObject.uv4s._updatable = true;
  29578. }
  29579. }
  29580. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29581. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29582. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29583. serializationObject.uv5s._updatable = true;
  29584. }
  29585. }
  29586. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29587. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29588. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29589. serializationObject.uv6s._updatable = true;
  29590. }
  29591. }
  29592. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29593. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29594. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29595. serializationObject.colors._updatable = true;
  29596. }
  29597. }
  29598. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29599. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29600. serializationObject.matricesIndices._isExpanded = true;
  29601. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29602. serializationObject.matricesIndices._updatable = true;
  29603. }
  29604. }
  29605. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29606. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29607. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29608. serializationObject.matricesWeights._updatable = true;
  29609. }
  29610. }
  29611. serializationObject.indices = this.toNumberArray(this.getIndices());
  29612. return serializationObject;
  29613. };
  29614. // Statics
  29615. Geometry.ExtractFromMesh = function (mesh, id) {
  29616. var geometry = mesh._geometry;
  29617. if (!geometry) {
  29618. return null;
  29619. }
  29620. return geometry.copy(id);
  29621. };
  29622. /**
  29623. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29624. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29625. * Be aware Math.random() could cause collisions, but:
  29626. * "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"
  29627. */
  29628. Geometry.RandomId = function () {
  29629. return BABYLON.Tools.RandomId();
  29630. };
  29631. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29632. var scene = mesh.getScene();
  29633. // Geometry
  29634. var geometryId = parsedGeometry.geometryId;
  29635. if (geometryId) {
  29636. var geometry = scene.getGeometryByID(geometryId);
  29637. if (geometry) {
  29638. geometry.applyToMesh(mesh);
  29639. }
  29640. }
  29641. else if (parsedGeometry instanceof ArrayBuffer) {
  29642. var binaryInfo = mesh._binaryInfo;
  29643. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29644. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29645. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29646. }
  29647. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29648. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29649. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29650. }
  29651. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29652. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29653. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29654. }
  29655. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29656. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29657. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29658. }
  29659. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29660. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29661. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29662. }
  29663. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29664. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29665. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29666. }
  29667. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29668. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29669. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29670. }
  29671. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29672. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29673. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29674. }
  29675. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29676. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29677. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29678. }
  29679. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29680. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29681. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29682. }
  29683. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29684. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29685. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29686. }
  29687. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29688. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29689. mesh.setIndices(indicesData);
  29690. }
  29691. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29692. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29693. mesh.subMeshes = [];
  29694. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29695. var materialIndex = subMeshesData[(i * 5) + 0];
  29696. var verticesStart = subMeshesData[(i * 5) + 1];
  29697. var verticesCount = subMeshesData[(i * 5) + 2];
  29698. var indexStart = subMeshesData[(i * 5) + 3];
  29699. var indexCount = subMeshesData[(i * 5) + 4];
  29700. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29701. }
  29702. }
  29703. }
  29704. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29705. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29706. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29707. if (parsedGeometry.uvs) {
  29708. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29709. }
  29710. if (parsedGeometry.uvs2) {
  29711. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29712. }
  29713. if (parsedGeometry.uvs3) {
  29714. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29715. }
  29716. if (parsedGeometry.uvs4) {
  29717. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29718. }
  29719. if (parsedGeometry.uvs5) {
  29720. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29721. }
  29722. if (parsedGeometry.uvs6) {
  29723. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29724. }
  29725. if (parsedGeometry.colors) {
  29726. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29727. }
  29728. if (parsedGeometry.matricesIndices) {
  29729. if (!parsedGeometry.matricesIndices._isExpanded) {
  29730. var floatIndices = [];
  29731. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29732. var matricesIndex = parsedGeometry.matricesIndices[i];
  29733. floatIndices.push(matricesIndex & 0x000000FF);
  29734. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29735. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29736. floatIndices.push(matricesIndex >> 24);
  29737. }
  29738. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29739. }
  29740. else {
  29741. delete parsedGeometry.matricesIndices._isExpanded;
  29742. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29743. }
  29744. }
  29745. if (parsedGeometry.matricesIndicesExtra) {
  29746. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29747. var floatIndices = [];
  29748. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29749. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29750. floatIndices.push(matricesIndex & 0x000000FF);
  29751. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29752. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29753. floatIndices.push(matricesIndex >> 24);
  29754. }
  29755. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29756. }
  29757. else {
  29758. delete parsedGeometry.matricesIndices._isExpanded;
  29759. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29760. }
  29761. }
  29762. if (parsedGeometry.matricesWeights) {
  29763. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  29764. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29765. }
  29766. if (parsedGeometry.matricesWeightsExtra) {
  29767. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29768. }
  29769. mesh.setIndices(parsedGeometry.indices);
  29770. }
  29771. // SubMeshes
  29772. if (parsedGeometry.subMeshes) {
  29773. mesh.subMeshes = [];
  29774. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29775. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29776. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29777. }
  29778. }
  29779. // Flat shading
  29780. if (mesh._shouldGenerateFlatShading) {
  29781. mesh.convertToFlatShadedMesh();
  29782. delete mesh._shouldGenerateFlatShading;
  29783. }
  29784. // Update
  29785. mesh.computeWorldMatrix(true);
  29786. // Octree
  29787. if (scene['_selectionOctree']) {
  29788. scene['_selectionOctree'].addMesh(mesh);
  29789. }
  29790. };
  29791. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  29792. var epsilon = 1e-3;
  29793. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29794. return;
  29795. }
  29796. var noInfluenceBoneIndex = 0.0;
  29797. if (parsedGeometry.skeletonId > -1) {
  29798. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  29799. noInfluenceBoneIndex = skeleton.bones.length;
  29800. }
  29801. else {
  29802. return;
  29803. }
  29804. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29805. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  29806. var matricesWeights = parsedGeometry.matricesWeights;
  29807. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  29808. var influencers = parsedGeometry.numBoneInfluencer;
  29809. var size = matricesWeights.length;
  29810. for (var i = 0; i < size; i += 4) {
  29811. var weight = 0.0;
  29812. var firstZeroWeight = -1;
  29813. for (var j = 0; j < 4; j++) {
  29814. var w = matricesWeights[i + j];
  29815. weight += w;
  29816. if (w < epsilon && firstZeroWeight < 0) {
  29817. firstZeroWeight = j;
  29818. }
  29819. }
  29820. if (matricesWeightsExtra) {
  29821. for (var j = 0; j < 4; j++) {
  29822. var w = matricesWeightsExtra[i + j];
  29823. weight += w;
  29824. if (w < epsilon && firstZeroWeight < 0) {
  29825. firstZeroWeight = j + 4;
  29826. }
  29827. }
  29828. }
  29829. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  29830. firstZeroWeight = influencers - 1;
  29831. }
  29832. if (weight > epsilon) {
  29833. var mweight = 1.0 / weight;
  29834. for (var j = 0; j < 4; j++) {
  29835. matricesWeights[i + j] *= mweight;
  29836. }
  29837. if (matricesWeightsExtra) {
  29838. for (var j = 0; j < 4; j++) {
  29839. matricesWeightsExtra[i + j] *= mweight;
  29840. }
  29841. }
  29842. }
  29843. else {
  29844. if (firstZeroWeight >= 4) {
  29845. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  29846. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  29847. }
  29848. else {
  29849. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  29850. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  29851. }
  29852. }
  29853. }
  29854. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  29855. if (parsedGeometry.matricesWeightsExtra) {
  29856. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  29857. }
  29858. };
  29859. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29860. if (scene.getGeometryByID(parsedVertexData.id)) {
  29861. return null; // null since geometry could be something else than a box...
  29862. }
  29863. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29864. if (BABYLON.Tags) {
  29865. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29866. }
  29867. if (parsedVertexData.delayLoadingFile) {
  29868. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29869. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29870. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29871. geometry._delayInfo = [];
  29872. if (parsedVertexData.hasUVs) {
  29873. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29874. }
  29875. if (parsedVertexData.hasUVs2) {
  29876. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29877. }
  29878. if (parsedVertexData.hasUVs3) {
  29879. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29880. }
  29881. if (parsedVertexData.hasUVs4) {
  29882. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29883. }
  29884. if (parsedVertexData.hasUVs5) {
  29885. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29886. }
  29887. if (parsedVertexData.hasUVs6) {
  29888. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29889. }
  29890. if (parsedVertexData.hasColors) {
  29891. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29892. }
  29893. if (parsedVertexData.hasMatricesIndices) {
  29894. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29895. }
  29896. if (parsedVertexData.hasMatricesWeights) {
  29897. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29898. }
  29899. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29900. }
  29901. else {
  29902. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29903. }
  29904. scene.pushGeometry(geometry, true);
  29905. return geometry;
  29906. };
  29907. return Geometry;
  29908. }());
  29909. BABYLON.Geometry = Geometry;
  29910. /////// Primitives //////////////////////////////////////////////
  29911. (function (Geometry) {
  29912. var Primitives;
  29913. (function (Primitives) {
  29914. /// Abstract class
  29915. var _Primitive = (function (_super) {
  29916. __extends(_Primitive, _super);
  29917. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29918. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29919. _this._canBeRegenerated = _canBeRegenerated;
  29920. _this._beingRegenerated = true;
  29921. _this.regenerate();
  29922. _this._beingRegenerated = false;
  29923. return _this;
  29924. }
  29925. _Primitive.prototype.canBeRegenerated = function () {
  29926. return this._canBeRegenerated;
  29927. };
  29928. _Primitive.prototype.regenerate = function () {
  29929. if (!this._canBeRegenerated) {
  29930. return;
  29931. }
  29932. this._beingRegenerated = true;
  29933. this.setAllVerticesData(this._regenerateVertexData(), false);
  29934. this._beingRegenerated = false;
  29935. };
  29936. _Primitive.prototype.asNewGeometry = function (id) {
  29937. return _super.prototype.copy.call(this, id);
  29938. };
  29939. // overrides
  29940. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29941. if (!this._beingRegenerated) {
  29942. return;
  29943. }
  29944. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29945. };
  29946. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29947. if (!this._beingRegenerated) {
  29948. return;
  29949. }
  29950. _super.prototype.setVerticesData.call(this, kind, data, false);
  29951. };
  29952. // to override
  29953. // protected
  29954. _Primitive.prototype._regenerateVertexData = function () {
  29955. throw new Error("Abstract method");
  29956. };
  29957. _Primitive.prototype.copy = function (id) {
  29958. throw new Error("Must be overriden in sub-classes.");
  29959. };
  29960. _Primitive.prototype.serialize = function () {
  29961. var serializationObject = _super.prototype.serialize.call(this);
  29962. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29963. return serializationObject;
  29964. };
  29965. return _Primitive;
  29966. }(Geometry));
  29967. Primitives._Primitive = _Primitive;
  29968. var Ribbon = (function (_super) {
  29969. __extends(Ribbon, _super);
  29970. // Members
  29971. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29972. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29973. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29974. _this.pathArray = pathArray;
  29975. _this.closeArray = closeArray;
  29976. _this.closePath = closePath;
  29977. _this.offset = offset;
  29978. _this.side = side;
  29979. return _this;
  29980. }
  29981. Ribbon.prototype._regenerateVertexData = function () {
  29982. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29983. };
  29984. Ribbon.prototype.copy = function (id) {
  29985. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29986. };
  29987. return Ribbon;
  29988. }(_Primitive));
  29989. Primitives.Ribbon = Ribbon;
  29990. var Box = (function (_super) {
  29991. __extends(Box, _super);
  29992. // Members
  29993. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29994. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29995. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29996. _this.size = size;
  29997. _this.side = side;
  29998. return _this;
  29999. }
  30000. Box.prototype._regenerateVertexData = function () {
  30001. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  30002. };
  30003. Box.prototype.copy = function (id) {
  30004. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30005. };
  30006. Box.prototype.serialize = function () {
  30007. var serializationObject = _super.prototype.serialize.call(this);
  30008. serializationObject.size = this.size;
  30009. return serializationObject;
  30010. };
  30011. Box.Parse = function (parsedBox, scene) {
  30012. if (scene.getGeometryByID(parsedBox.id)) {
  30013. return null; // null since geometry could be something else than a box...
  30014. }
  30015. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  30016. if (BABYLON.Tags) {
  30017. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  30018. }
  30019. scene.pushGeometry(box, true);
  30020. return box;
  30021. };
  30022. return Box;
  30023. }(_Primitive));
  30024. Primitives.Box = Box;
  30025. var Sphere = (function (_super) {
  30026. __extends(Sphere, _super);
  30027. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  30028. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30029. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30030. _this.segments = segments;
  30031. _this.diameter = diameter;
  30032. _this.side = side;
  30033. return _this;
  30034. }
  30035. Sphere.prototype._regenerateVertexData = function () {
  30036. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  30037. };
  30038. Sphere.prototype.copy = function (id) {
  30039. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  30040. };
  30041. Sphere.prototype.serialize = function () {
  30042. var serializationObject = _super.prototype.serialize.call(this);
  30043. serializationObject.segments = this.segments;
  30044. serializationObject.diameter = this.diameter;
  30045. return serializationObject;
  30046. };
  30047. Sphere.Parse = function (parsedSphere, scene) {
  30048. if (scene.getGeometryByID(parsedSphere.id)) {
  30049. return null; // null since geometry could be something else than a sphere...
  30050. }
  30051. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  30052. if (BABYLON.Tags) {
  30053. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  30054. }
  30055. scene.pushGeometry(sphere, true);
  30056. return sphere;
  30057. };
  30058. return Sphere;
  30059. }(_Primitive));
  30060. Primitives.Sphere = Sphere;
  30061. var Disc = (function (_super) {
  30062. __extends(Disc, _super);
  30063. // Members
  30064. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30065. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30066. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30067. _this.radius = radius;
  30068. _this.tessellation = tessellation;
  30069. _this.side = side;
  30070. return _this;
  30071. }
  30072. Disc.prototype._regenerateVertexData = function () {
  30073. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30074. };
  30075. Disc.prototype.copy = function (id) {
  30076. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30077. };
  30078. return Disc;
  30079. }(_Primitive));
  30080. Primitives.Disc = Disc;
  30081. var Cylinder = (function (_super) {
  30082. __extends(Cylinder, _super);
  30083. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30084. if (subdivisions === void 0) { subdivisions = 1; }
  30085. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30086. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30087. _this.height = height;
  30088. _this.diameterTop = diameterTop;
  30089. _this.diameterBottom = diameterBottom;
  30090. _this.tessellation = tessellation;
  30091. _this.subdivisions = subdivisions;
  30092. _this.side = side;
  30093. return _this;
  30094. }
  30095. Cylinder.prototype._regenerateVertexData = function () {
  30096. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30097. };
  30098. Cylinder.prototype.copy = function (id) {
  30099. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30100. };
  30101. Cylinder.prototype.serialize = function () {
  30102. var serializationObject = _super.prototype.serialize.call(this);
  30103. serializationObject.height = this.height;
  30104. serializationObject.diameterTop = this.diameterTop;
  30105. serializationObject.diameterBottom = this.diameterBottom;
  30106. serializationObject.tessellation = this.tessellation;
  30107. return serializationObject;
  30108. };
  30109. Cylinder.Parse = function (parsedCylinder, scene) {
  30110. if (scene.getGeometryByID(parsedCylinder.id)) {
  30111. return null; // null since geometry could be something else than a cylinder...
  30112. }
  30113. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30114. if (BABYLON.Tags) {
  30115. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30116. }
  30117. scene.pushGeometry(cylinder, true);
  30118. return cylinder;
  30119. };
  30120. return Cylinder;
  30121. }(_Primitive));
  30122. Primitives.Cylinder = Cylinder;
  30123. var Torus = (function (_super) {
  30124. __extends(Torus, _super);
  30125. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30126. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30127. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30128. _this.diameter = diameter;
  30129. _this.thickness = thickness;
  30130. _this.tessellation = tessellation;
  30131. _this.side = side;
  30132. return _this;
  30133. }
  30134. Torus.prototype._regenerateVertexData = function () {
  30135. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30136. };
  30137. Torus.prototype.copy = function (id) {
  30138. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30139. };
  30140. Torus.prototype.serialize = function () {
  30141. var serializationObject = _super.prototype.serialize.call(this);
  30142. serializationObject.diameter = this.diameter;
  30143. serializationObject.thickness = this.thickness;
  30144. serializationObject.tessellation = this.tessellation;
  30145. return serializationObject;
  30146. };
  30147. Torus.Parse = function (parsedTorus, scene) {
  30148. if (scene.getGeometryByID(parsedTorus.id)) {
  30149. return null; // null since geometry could be something else than a torus...
  30150. }
  30151. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30152. if (BABYLON.Tags) {
  30153. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30154. }
  30155. scene.pushGeometry(torus, true);
  30156. return torus;
  30157. };
  30158. return Torus;
  30159. }(_Primitive));
  30160. Primitives.Torus = Torus;
  30161. var Ground = (function (_super) {
  30162. __extends(Ground, _super);
  30163. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30164. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30165. _this.width = width;
  30166. _this.height = height;
  30167. _this.subdivisions = subdivisions;
  30168. return _this;
  30169. }
  30170. Ground.prototype._regenerateVertexData = function () {
  30171. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30172. };
  30173. Ground.prototype.copy = function (id) {
  30174. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30175. };
  30176. Ground.prototype.serialize = function () {
  30177. var serializationObject = _super.prototype.serialize.call(this);
  30178. serializationObject.width = this.width;
  30179. serializationObject.height = this.height;
  30180. serializationObject.subdivisions = this.subdivisions;
  30181. return serializationObject;
  30182. };
  30183. Ground.Parse = function (parsedGround, scene) {
  30184. if (scene.getGeometryByID(parsedGround.id)) {
  30185. return null; // null since geometry could be something else than a ground...
  30186. }
  30187. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30188. if (BABYLON.Tags) {
  30189. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30190. }
  30191. scene.pushGeometry(ground, true);
  30192. return ground;
  30193. };
  30194. return Ground;
  30195. }(_Primitive));
  30196. Primitives.Ground = Ground;
  30197. var TiledGround = (function (_super) {
  30198. __extends(TiledGround, _super);
  30199. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30200. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30201. _this.xmin = xmin;
  30202. _this.zmin = zmin;
  30203. _this.xmax = xmax;
  30204. _this.zmax = zmax;
  30205. _this.subdivisions = subdivisions;
  30206. _this.precision = precision;
  30207. return _this;
  30208. }
  30209. TiledGround.prototype._regenerateVertexData = function () {
  30210. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30211. };
  30212. TiledGround.prototype.copy = function (id) {
  30213. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30214. };
  30215. return TiledGround;
  30216. }(_Primitive));
  30217. Primitives.TiledGround = TiledGround;
  30218. var Plane = (function (_super) {
  30219. __extends(Plane, _super);
  30220. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30221. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30222. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30223. _this.size = size;
  30224. _this.side = side;
  30225. return _this;
  30226. }
  30227. Plane.prototype._regenerateVertexData = function () {
  30228. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30229. };
  30230. Plane.prototype.copy = function (id) {
  30231. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30232. };
  30233. Plane.prototype.serialize = function () {
  30234. var serializationObject = _super.prototype.serialize.call(this);
  30235. serializationObject.size = this.size;
  30236. return serializationObject;
  30237. };
  30238. Plane.Parse = function (parsedPlane, scene) {
  30239. if (scene.getGeometryByID(parsedPlane.id)) {
  30240. return null; // null since geometry could be something else than a ground...
  30241. }
  30242. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30243. if (BABYLON.Tags) {
  30244. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30245. }
  30246. scene.pushGeometry(plane, true);
  30247. return plane;
  30248. };
  30249. return Plane;
  30250. }(_Primitive));
  30251. Primitives.Plane = Plane;
  30252. var TorusKnot = (function (_super) {
  30253. __extends(TorusKnot, _super);
  30254. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30255. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30256. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30257. _this.radius = radius;
  30258. _this.tube = tube;
  30259. _this.radialSegments = radialSegments;
  30260. _this.tubularSegments = tubularSegments;
  30261. _this.p = p;
  30262. _this.q = q;
  30263. _this.side = side;
  30264. return _this;
  30265. }
  30266. TorusKnot.prototype._regenerateVertexData = function () {
  30267. 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 });
  30268. };
  30269. TorusKnot.prototype.copy = function (id) {
  30270. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30271. };
  30272. TorusKnot.prototype.serialize = function () {
  30273. var serializationObject = _super.prototype.serialize.call(this);
  30274. serializationObject.radius = this.radius;
  30275. serializationObject.tube = this.tube;
  30276. serializationObject.radialSegments = this.radialSegments;
  30277. serializationObject.tubularSegments = this.tubularSegments;
  30278. serializationObject.p = this.p;
  30279. serializationObject.q = this.q;
  30280. return serializationObject;
  30281. };
  30282. ;
  30283. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30284. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30285. return null; // null since geometry could be something else than a ground...
  30286. }
  30287. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30288. if (BABYLON.Tags) {
  30289. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30290. }
  30291. scene.pushGeometry(torusKnot, true);
  30292. return torusKnot;
  30293. };
  30294. return TorusKnot;
  30295. }(_Primitive));
  30296. Primitives.TorusKnot = TorusKnot;
  30297. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30298. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30299. })(BABYLON || (BABYLON = {}));
  30300. //# sourceMappingURL=babylon.geometry.js.map
  30301. var BABYLON;
  30302. (function (BABYLON) {
  30303. var PostProcessManager = (function () {
  30304. function PostProcessManager(scene) {
  30305. this._vertexBuffers = {};
  30306. this._scene = scene;
  30307. }
  30308. PostProcessManager.prototype._prepareBuffers = function () {
  30309. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30310. return;
  30311. }
  30312. // VBO
  30313. var vertices = [];
  30314. vertices.push(1, 1);
  30315. vertices.push(-1, 1);
  30316. vertices.push(-1, -1);
  30317. vertices.push(1, -1);
  30318. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30319. this._buildIndexBuffer();
  30320. };
  30321. PostProcessManager.prototype._buildIndexBuffer = function () {
  30322. // Indices
  30323. var indices = [];
  30324. indices.push(0);
  30325. indices.push(1);
  30326. indices.push(2);
  30327. indices.push(0);
  30328. indices.push(2);
  30329. indices.push(3);
  30330. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30331. };
  30332. PostProcessManager.prototype._rebuild = function () {
  30333. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30334. return;
  30335. }
  30336. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30337. this._buildIndexBuffer();
  30338. };
  30339. // Methods
  30340. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30341. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30342. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30343. return false;
  30344. }
  30345. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30346. return true;
  30347. };
  30348. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30349. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30350. var engine = this._scene.getEngine();
  30351. for (var index = 0; index < postProcesses.length; index++) {
  30352. if (index < postProcesses.length - 1) {
  30353. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30354. }
  30355. else {
  30356. if (targetTexture) {
  30357. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30358. }
  30359. else {
  30360. engine.restoreDefaultFramebuffer();
  30361. }
  30362. }
  30363. var pp = postProcesses[index];
  30364. var effect = pp.apply();
  30365. if (effect) {
  30366. pp.onBeforeRenderObservable.notifyObservers(effect);
  30367. // VBOs
  30368. this._prepareBuffers();
  30369. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30370. // Draw order
  30371. engine.draw(true, 0, 6);
  30372. pp.onAfterRenderObservable.notifyObservers(effect);
  30373. }
  30374. }
  30375. // Restore depth buffer
  30376. engine.setDepthBuffer(true);
  30377. engine.setDepthWrite(true);
  30378. };
  30379. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  30380. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30381. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30382. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30383. return;
  30384. }
  30385. var engine = this._scene.getEngine();
  30386. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30387. if (index < len - 1) {
  30388. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30389. }
  30390. else {
  30391. if (targetTexture) {
  30392. engine.bindFramebuffer(targetTexture, faceIndex, null, null, forceFullscreenViewport);
  30393. }
  30394. else {
  30395. engine.restoreDefaultFramebuffer();
  30396. }
  30397. }
  30398. if (doNotPresent) {
  30399. break;
  30400. }
  30401. var pp = postProcesses[index];
  30402. var effect = pp.apply();
  30403. if (effect) {
  30404. pp.onBeforeRenderObservable.notifyObservers(effect);
  30405. // VBOs
  30406. this._prepareBuffers();
  30407. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30408. // Draw order
  30409. engine.draw(true, 0, 6);
  30410. pp.onAfterRenderObservable.notifyObservers(effect);
  30411. }
  30412. }
  30413. // Restore states
  30414. engine.setDepthBuffer(true);
  30415. engine.setDepthWrite(true);
  30416. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30417. };
  30418. PostProcessManager.prototype.dispose = function () {
  30419. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30420. if (buffer) {
  30421. buffer.dispose();
  30422. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30423. }
  30424. if (this._indexBuffer) {
  30425. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30426. this._indexBuffer = null;
  30427. }
  30428. };
  30429. return PostProcessManager;
  30430. }());
  30431. BABYLON.PostProcessManager = PostProcessManager;
  30432. })(BABYLON || (BABYLON = {}));
  30433. //# sourceMappingURL=babylon.postProcessManager.js.map
  30434. var BABYLON;
  30435. (function (BABYLON) {
  30436. /**
  30437. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30438. */
  30439. var PerformanceMonitor = (function () {
  30440. /**
  30441. * constructor
  30442. * @param frameSampleSize The number of samples required to saturate the sliding window
  30443. */
  30444. function PerformanceMonitor(frameSampleSize) {
  30445. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30446. this._enabled = true;
  30447. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30448. }
  30449. /**
  30450. * Samples current frame
  30451. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30452. */
  30453. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30454. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30455. if (!this._enabled)
  30456. return;
  30457. if (this._lastFrameTimeMs != null) {
  30458. var dt = timeMs - this._lastFrameTimeMs;
  30459. this._rollingFrameTime.add(dt);
  30460. }
  30461. this._lastFrameTimeMs = timeMs;
  30462. };
  30463. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30464. /**
  30465. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30466. * @return Average frame time in milliseconds
  30467. */
  30468. get: function () {
  30469. return this._rollingFrameTime.average;
  30470. },
  30471. enumerable: true,
  30472. configurable: true
  30473. });
  30474. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30475. /**
  30476. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30477. * @return Frame time variance in milliseconds squared
  30478. */
  30479. get: function () {
  30480. return this._rollingFrameTime.variance;
  30481. },
  30482. enumerable: true,
  30483. configurable: true
  30484. });
  30485. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30486. /**
  30487. * Returns the frame time of the most recent frame
  30488. * @return Frame time in milliseconds
  30489. */
  30490. get: function () {
  30491. return this._rollingFrameTime.history(0);
  30492. },
  30493. enumerable: true,
  30494. configurable: true
  30495. });
  30496. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30497. /**
  30498. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30499. * @return Framerate in frames per second
  30500. */
  30501. get: function () {
  30502. return 1000.0 / this._rollingFrameTime.average;
  30503. },
  30504. enumerable: true,
  30505. configurable: true
  30506. });
  30507. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30508. /**
  30509. * Returns the average framerate in frames per second using the most recent frame time
  30510. * @return Framerate in frames per second
  30511. */
  30512. get: function () {
  30513. return 1000.0 / this._rollingFrameTime.history(0);
  30514. },
  30515. enumerable: true,
  30516. configurable: true
  30517. });
  30518. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30519. /**
  30520. * Returns true if enough samples have been taken to completely fill the sliding window
  30521. * @return true if saturated
  30522. */
  30523. get: function () {
  30524. return this._rollingFrameTime.isSaturated();
  30525. },
  30526. enumerable: true,
  30527. configurable: true
  30528. });
  30529. /**
  30530. * Enables contributions to the sliding window sample set
  30531. */
  30532. PerformanceMonitor.prototype.enable = function () {
  30533. this._enabled = true;
  30534. };
  30535. /**
  30536. * Disables contributions to the sliding window sample set
  30537. * Samples will not be interpolated over the disabled period
  30538. */
  30539. PerformanceMonitor.prototype.disable = function () {
  30540. this._enabled = false;
  30541. //clear last sample to avoid interpolating over the disabled period when next enabled
  30542. this._lastFrameTimeMs = null;
  30543. this._lastChangeTimeMs = null;
  30544. };
  30545. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30546. /**
  30547. * Returns true if sampling is enabled
  30548. * @return true if enabled
  30549. */
  30550. get: function () {
  30551. return this._enabled;
  30552. },
  30553. enumerable: true,
  30554. configurable: true
  30555. });
  30556. /**
  30557. * Resets performance monitor
  30558. */
  30559. PerformanceMonitor.prototype.reset = function () {
  30560. //clear last sample to avoid interpolating over the disabled period when next enabled
  30561. this._lastFrameTimeMs = null;
  30562. this._lastChangeTimeMs = null;
  30563. //wipe record
  30564. this._rollingFrameTime.reset();
  30565. };
  30566. return PerformanceMonitor;
  30567. }());
  30568. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30569. /**
  30570. * RollingAverage
  30571. *
  30572. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30573. */
  30574. var RollingAverage = (function () {
  30575. /**
  30576. * constructor
  30577. * @param length The number of samples required to saturate the sliding window
  30578. */
  30579. function RollingAverage(length) {
  30580. this._samples = new Array(length);
  30581. this.reset();
  30582. }
  30583. /**
  30584. * Adds a sample to the sample set
  30585. * @param v The sample value
  30586. */
  30587. RollingAverage.prototype.add = function (v) {
  30588. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30589. var delta;
  30590. //we need to check if we've already wrapped round
  30591. if (this.isSaturated()) {
  30592. //remove bottom of stack from mean
  30593. var bottomValue = this._samples[this._pos];
  30594. delta = bottomValue - this.average;
  30595. this.average -= delta / (this._sampleCount - 1);
  30596. this._m2 -= delta * (bottomValue - this.average);
  30597. }
  30598. else {
  30599. this._sampleCount++;
  30600. }
  30601. //add new value to mean
  30602. delta = v - this.average;
  30603. this.average += delta / (this._sampleCount);
  30604. this._m2 += delta * (v - this.average);
  30605. //set the new variance
  30606. this.variance = this._m2 / (this._sampleCount - 1);
  30607. this._samples[this._pos] = v;
  30608. this._pos++;
  30609. this._pos %= this._samples.length; //positive wrap around
  30610. };
  30611. /**
  30612. * Returns previously added values or null if outside of history or outside the sliding window domain
  30613. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30614. * @return Value previously recorded with add() or null if outside of range
  30615. */
  30616. RollingAverage.prototype.history = function (i) {
  30617. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30618. return null;
  30619. }
  30620. var i0 = this._wrapPosition(this._pos - 1.0);
  30621. return this._samples[this._wrapPosition(i0 - i)];
  30622. };
  30623. /**
  30624. * Returns true if enough samples have been taken to completely fill the sliding window
  30625. * @return true if sample-set saturated
  30626. */
  30627. RollingAverage.prototype.isSaturated = function () {
  30628. return this._sampleCount >= this._samples.length;
  30629. };
  30630. /**
  30631. * Resets the rolling average (equivalent to 0 samples taken so far)
  30632. */
  30633. RollingAverage.prototype.reset = function () {
  30634. this.average = 0;
  30635. this.variance = 0;
  30636. this._sampleCount = 0;
  30637. this._pos = 0;
  30638. this._m2 = 0;
  30639. };
  30640. /**
  30641. * Wraps a value around the sample range boundaries
  30642. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30643. * @return Wrapped position in sample range
  30644. */
  30645. RollingAverage.prototype._wrapPosition = function (i) {
  30646. var max = this._samples.length;
  30647. return ((i % max) + max) % max;
  30648. };
  30649. return RollingAverage;
  30650. }());
  30651. BABYLON.RollingAverage = RollingAverage;
  30652. })(BABYLON || (BABYLON = {}));
  30653. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30654. var BABYLON;
  30655. (function (BABYLON) {
  30656. var StandardMaterialDefines = (function (_super) {
  30657. __extends(StandardMaterialDefines, _super);
  30658. function StandardMaterialDefines() {
  30659. var _this = _super.call(this) || this;
  30660. _this.MAINUV1 = false;
  30661. _this.MAINUV2 = false;
  30662. _this.DIFFUSE = false;
  30663. _this.DIFFUSEDIRECTUV = 0;
  30664. _this.AMBIENT = false;
  30665. _this.AMBIENTDIRECTUV = 0;
  30666. _this.OPACITY = false;
  30667. _this.OPACITYDIRECTUV = 0;
  30668. _this.OPACITYRGB = false;
  30669. _this.REFLECTION = false;
  30670. _this.EMISSIVE = false;
  30671. _this.EMISSIVEDIRECTUV = 0;
  30672. _this.SPECULAR = false;
  30673. _this.SPECULARDIRECTUV = 0;
  30674. _this.BUMP = false;
  30675. _this.BUMPDIRECTUV = 0;
  30676. _this.PARALLAX = false;
  30677. _this.PARALLAXOCCLUSION = false;
  30678. _this.SPECULAROVERALPHA = false;
  30679. _this.CLIPPLANE = false;
  30680. _this.ALPHATEST = false;
  30681. _this.DEPTHPREPASS = false;
  30682. _this.ALPHAFROMDIFFUSE = false;
  30683. _this.POINTSIZE = false;
  30684. _this.FOG = false;
  30685. _this.SPECULARTERM = false;
  30686. _this.DIFFUSEFRESNEL = false;
  30687. _this.OPACITYFRESNEL = false;
  30688. _this.REFLECTIONFRESNEL = false;
  30689. _this.REFRACTIONFRESNEL = false;
  30690. _this.EMISSIVEFRESNEL = false;
  30691. _this.FRESNEL = false;
  30692. _this.NORMAL = false;
  30693. _this.UV1 = false;
  30694. _this.UV2 = false;
  30695. _this.VERTEXCOLOR = false;
  30696. _this.VERTEXALPHA = false;
  30697. _this.NUM_BONE_INFLUENCERS = 0;
  30698. _this.BonesPerMesh = 0;
  30699. _this.INSTANCES = false;
  30700. _this.GLOSSINESS = false;
  30701. _this.ROUGHNESS = false;
  30702. _this.EMISSIVEASILLUMINATION = false;
  30703. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30704. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30705. _this.LIGHTMAP = false;
  30706. _this.LIGHTMAPDIRECTUV = 0;
  30707. _this.USELIGHTMAPASSHADOWMAP = false;
  30708. _this.REFLECTIONMAP_3D = false;
  30709. _this.REFLECTIONMAP_SPHERICAL = false;
  30710. _this.REFLECTIONMAP_PLANAR = false;
  30711. _this.REFLECTIONMAP_CUBIC = false;
  30712. _this.REFLECTIONMAP_PROJECTION = false;
  30713. _this.REFLECTIONMAP_SKYBOX = false;
  30714. _this.REFLECTIONMAP_EXPLICIT = false;
  30715. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30716. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30717. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30718. _this.INVERTCUBICMAP = false;
  30719. _this.LOGARITHMICDEPTH = false;
  30720. _this.REFRACTION = false;
  30721. _this.REFRACTIONMAP_3D = false;
  30722. _this.REFLECTIONOVERALPHA = false;
  30723. _this.TWOSIDEDLIGHTING = false;
  30724. _this.SHADOWFLOAT = false;
  30725. _this.MORPHTARGETS = false;
  30726. _this.MORPHTARGETS_NORMAL = false;
  30727. _this.MORPHTARGETS_TANGENT = false;
  30728. _this.NUM_MORPH_INFLUENCERS = 0;
  30729. _this.IMAGEPROCESSING = false;
  30730. _this.VIGNETTE = false;
  30731. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30732. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30733. _this.TONEMAPPING = false;
  30734. _this.CONTRAST = false;
  30735. _this.COLORCURVES = false;
  30736. _this.COLORGRADING = false;
  30737. _this.SAMPLER3DGREENDEPTH = false;
  30738. _this.SAMPLER3DBGRMAP = false;
  30739. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30740. _this.EXPOSURE = false;
  30741. _this.rebuild();
  30742. return _this;
  30743. }
  30744. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30745. var modes = [
  30746. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30747. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30748. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30749. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30750. ];
  30751. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30752. var mode = modes_1[_i];
  30753. this[mode] = (mode === modeToEnable);
  30754. }
  30755. };
  30756. return StandardMaterialDefines;
  30757. }(BABYLON.MaterialDefines));
  30758. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30759. var StandardMaterial = (function (_super) {
  30760. __extends(StandardMaterial, _super);
  30761. function StandardMaterial(name, scene) {
  30762. var _this = _super.call(this, name, scene) || this;
  30763. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30764. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30765. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30766. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30767. _this.specularPower = 64;
  30768. _this._useAlphaFromDiffuseTexture = false;
  30769. _this._useEmissiveAsIllumination = false;
  30770. _this._linkEmissiveWithDiffuse = false;
  30771. _this._useSpecularOverAlpha = false;
  30772. _this._useReflectionOverAlpha = false;
  30773. _this._disableLighting = false;
  30774. _this._useParallax = false;
  30775. _this._useParallaxOcclusion = false;
  30776. _this.parallaxScaleBias = 0.05;
  30777. _this._roughness = 0;
  30778. _this.indexOfRefraction = 0.98;
  30779. _this.invertRefractionY = true;
  30780. _this._useLightmapAsShadowmap = false;
  30781. _this._useReflectionFresnelFromSpecular = false;
  30782. _this._useGlossinessFromSpecularMapAlpha = false;
  30783. _this._maxSimultaneousLights = 4;
  30784. /**
  30785. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30786. */
  30787. _this._invertNormalMapX = false;
  30788. /**
  30789. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30790. */
  30791. _this._invertNormalMapY = false;
  30792. /**
  30793. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30794. */
  30795. _this._twoSidedLighting = false;
  30796. _this._renderTargets = new BABYLON.SmartArray(16);
  30797. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30798. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30799. // Setup the default processing configuration to the scene.
  30800. _this._attachImageProcessingConfiguration(null);
  30801. _this.getRenderTargetTextures = function () {
  30802. _this._renderTargets.reset();
  30803. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30804. _this._renderTargets.push(_this._reflectionTexture);
  30805. }
  30806. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30807. _this._renderTargets.push(_this._refractionTexture);
  30808. }
  30809. return _this._renderTargets;
  30810. };
  30811. return _this;
  30812. }
  30813. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30814. /**
  30815. * Gets the image processing configuration used either in this material.
  30816. */
  30817. get: function () {
  30818. return this._imageProcessingConfiguration;
  30819. },
  30820. /**
  30821. * Sets the Default image processing configuration used either in the this material.
  30822. *
  30823. * If sets to null, the scene one is in use.
  30824. */
  30825. set: function (value) {
  30826. this._attachImageProcessingConfiguration(value);
  30827. // Ensure the effect will be rebuilt.
  30828. this._markAllSubMeshesAsTexturesDirty();
  30829. },
  30830. enumerable: true,
  30831. configurable: true
  30832. });
  30833. /**
  30834. * Attaches a new image processing configuration to the Standard Material.
  30835. * @param configuration
  30836. */
  30837. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30838. var _this = this;
  30839. if (configuration === this._imageProcessingConfiguration) {
  30840. return;
  30841. }
  30842. // Detaches observer.
  30843. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30844. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30845. }
  30846. // Pick the scene configuration if needed.
  30847. if (!configuration) {
  30848. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30849. }
  30850. else {
  30851. this._imageProcessingConfiguration = configuration;
  30852. }
  30853. // Attaches observer.
  30854. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30855. _this._markAllSubMeshesAsImageProcessingDirty();
  30856. });
  30857. };
  30858. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30859. /**
  30860. * Gets wether the color curves effect is enabled.
  30861. */
  30862. get: function () {
  30863. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30864. },
  30865. /**
  30866. * Sets wether the color curves effect is enabled.
  30867. */
  30868. set: function (value) {
  30869. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30870. },
  30871. enumerable: true,
  30872. configurable: true
  30873. });
  30874. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30875. /**
  30876. * Gets wether the color grading effect is enabled.
  30877. */
  30878. get: function () {
  30879. return this.imageProcessingConfiguration.colorGradingEnabled;
  30880. },
  30881. /**
  30882. * Gets wether the color grading effect is enabled.
  30883. */
  30884. set: function (value) {
  30885. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30886. },
  30887. enumerable: true,
  30888. configurable: true
  30889. });
  30890. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30891. /**
  30892. * Gets wether tonemapping is enabled or not.
  30893. */
  30894. get: function () {
  30895. return this._imageProcessingConfiguration.toneMappingEnabled;
  30896. },
  30897. /**
  30898. * Sets wether tonemapping is enabled or not
  30899. */
  30900. set: function (value) {
  30901. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30902. },
  30903. enumerable: true,
  30904. configurable: true
  30905. });
  30906. ;
  30907. ;
  30908. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30909. /**
  30910. * The camera exposure used on this material.
  30911. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30912. * This corresponds to a photographic exposure.
  30913. */
  30914. get: function () {
  30915. return this._imageProcessingConfiguration.exposure;
  30916. },
  30917. /**
  30918. * The camera exposure used on this material.
  30919. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30920. * This corresponds to a photographic exposure.
  30921. */
  30922. set: function (value) {
  30923. this._imageProcessingConfiguration.exposure = value;
  30924. },
  30925. enumerable: true,
  30926. configurable: true
  30927. });
  30928. ;
  30929. ;
  30930. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30931. /**
  30932. * Gets The camera contrast used on this material.
  30933. */
  30934. get: function () {
  30935. return this._imageProcessingConfiguration.contrast;
  30936. },
  30937. /**
  30938. * Sets The camera contrast used on this material.
  30939. */
  30940. set: function (value) {
  30941. this._imageProcessingConfiguration.contrast = value;
  30942. },
  30943. enumerable: true,
  30944. configurable: true
  30945. });
  30946. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30947. /**
  30948. * Gets the Color Grading 2D Lookup Texture.
  30949. */
  30950. get: function () {
  30951. return this._imageProcessingConfiguration.colorGradingTexture;
  30952. },
  30953. /**
  30954. * Sets the Color Grading 2D Lookup Texture.
  30955. */
  30956. set: function (value) {
  30957. this._imageProcessingConfiguration.colorGradingTexture = value;
  30958. },
  30959. enumerable: true,
  30960. configurable: true
  30961. });
  30962. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  30963. /**
  30964. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30965. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30966. * 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;
  30967. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30968. */
  30969. get: function () {
  30970. return this._imageProcessingConfiguration.colorCurves;
  30971. },
  30972. /**
  30973. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30974. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30975. * 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;
  30976. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30977. */
  30978. set: function (value) {
  30979. this._imageProcessingConfiguration.colorCurves = value;
  30980. },
  30981. enumerable: true,
  30982. configurable: true
  30983. });
  30984. StandardMaterial.prototype.getClassName = function () {
  30985. return "StandardMaterial";
  30986. };
  30987. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30988. get: function () {
  30989. return this._useLogarithmicDepth;
  30990. },
  30991. set: function (value) {
  30992. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30993. this._markAllSubMeshesAsMiscDirty();
  30994. },
  30995. enumerable: true,
  30996. configurable: true
  30997. });
  30998. StandardMaterial.prototype.needAlphaBlending = function () {
  30999. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  31000. };
  31001. StandardMaterial.prototype.needAlphaTesting = function () {
  31002. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  31003. };
  31004. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  31005. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  31006. };
  31007. StandardMaterial.prototype.getAlphaTestTexture = function () {
  31008. return this._diffuseTexture;
  31009. };
  31010. /**
  31011. * Child classes can use it to update shaders
  31012. */
  31013. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31014. if (this.isFrozen) {
  31015. if (this._wasPreviouslyReady && subMesh.effect) {
  31016. return true;
  31017. }
  31018. }
  31019. if (!subMesh._materialDefines) {
  31020. subMesh._materialDefines = new StandardMaterialDefines();
  31021. }
  31022. var scene = this.getScene();
  31023. var defines = subMesh._materialDefines;
  31024. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  31025. if (defines._renderId === scene.getRenderId()) {
  31026. return true;
  31027. }
  31028. }
  31029. var engine = scene.getEngine();
  31030. // Lights
  31031. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  31032. // Textures
  31033. if (defines._areTexturesDirty) {
  31034. defines._needUVs = false;
  31035. defines.MAINUV1 = false;
  31036. defines.MAINUV2 = false;
  31037. if (scene.texturesEnabled) {
  31038. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31039. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  31040. return false;
  31041. }
  31042. else {
  31043. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  31044. }
  31045. }
  31046. else {
  31047. defines.DIFFUSE = false;
  31048. }
  31049. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31050. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  31051. return false;
  31052. }
  31053. else {
  31054. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  31055. }
  31056. }
  31057. else {
  31058. defines.AMBIENT = false;
  31059. }
  31060. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31061. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  31062. return false;
  31063. }
  31064. else {
  31065. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  31066. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31067. }
  31068. }
  31069. else {
  31070. defines.OPACITY = false;
  31071. }
  31072. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31073. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  31074. return false;
  31075. }
  31076. else {
  31077. defines._needNormals = true;
  31078. defines.REFLECTION = true;
  31079. defines.ROUGHNESS = (this._roughness > 0);
  31080. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  31081. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  31082. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  31083. switch (this._reflectionTexture.coordinatesMode) {
  31084. case BABYLON.Texture.CUBIC_MODE:
  31085. case BABYLON.Texture.INVCUBIC_MODE:
  31086. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  31087. break;
  31088. case BABYLON.Texture.EXPLICIT_MODE:
  31089. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  31090. break;
  31091. case BABYLON.Texture.PLANAR_MODE:
  31092. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  31093. break;
  31094. case BABYLON.Texture.PROJECTION_MODE:
  31095. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  31096. break;
  31097. case BABYLON.Texture.SKYBOX_MODE:
  31098. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  31099. break;
  31100. case BABYLON.Texture.SPHERICAL_MODE:
  31101. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  31102. break;
  31103. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31104. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  31105. break;
  31106. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31107. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  31108. break;
  31109. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31110. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  31111. break;
  31112. }
  31113. }
  31114. }
  31115. else {
  31116. defines.REFLECTION = false;
  31117. }
  31118. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31119. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  31120. return false;
  31121. }
  31122. else {
  31123. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  31124. }
  31125. }
  31126. else {
  31127. defines.EMISSIVE = false;
  31128. }
  31129. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31130. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  31131. return false;
  31132. }
  31133. else {
  31134. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  31135. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31136. }
  31137. }
  31138. else {
  31139. defines.LIGHTMAP = false;
  31140. }
  31141. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31142. if (!this._specularTexture.isReadyOrNotBlocking()) {
  31143. return false;
  31144. }
  31145. else {
  31146. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  31147. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  31148. }
  31149. }
  31150. else {
  31151. defines.SPECULAR = false;
  31152. }
  31153. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  31154. // Bump texure can not be not blocking.
  31155. if (!this._bumpTexture.isReady()) {
  31156. return false;
  31157. }
  31158. else {
  31159. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  31160. defines.PARALLAX = this._useParallax;
  31161. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  31162. }
  31163. }
  31164. else {
  31165. defines.BUMP = false;
  31166. }
  31167. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31168. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  31169. return false;
  31170. }
  31171. else {
  31172. defines._needUVs = true;
  31173. defines.REFRACTION = true;
  31174. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  31175. }
  31176. }
  31177. else {
  31178. defines.REFRACTION = false;
  31179. }
  31180. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  31181. }
  31182. else {
  31183. defines.DIFFUSE = false;
  31184. defines.AMBIENT = false;
  31185. defines.OPACITY = false;
  31186. defines.REFLECTION = false;
  31187. defines.EMISSIVE = false;
  31188. defines.LIGHTMAP = false;
  31189. defines.BUMP = false;
  31190. defines.REFRACTION = false;
  31191. }
  31192. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  31193. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  31194. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  31195. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  31196. }
  31197. if (defines._areImageProcessingDirty) {
  31198. if (!this._imageProcessingConfiguration.isReady()) {
  31199. return false;
  31200. }
  31201. this._imageProcessingConfiguration.prepareDefines(defines);
  31202. }
  31203. if (defines._areFresnelDirty) {
  31204. if (StandardMaterial.FresnelEnabled) {
  31205. // Fresnel
  31206. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  31207. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  31208. this._reflectionFresnelParameters) {
  31209. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  31210. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  31211. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  31212. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  31213. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  31214. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  31215. defines._needNormals = true;
  31216. defines.FRESNEL = true;
  31217. }
  31218. }
  31219. else {
  31220. defines.FRESNEL = false;
  31221. }
  31222. }
  31223. // Misc.
  31224. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31225. // Attribs
  31226. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  31227. // Values that need to be evaluated on every frame
  31228. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  31229. // Get correct effect
  31230. if (defines.isDirty) {
  31231. defines.markAsProcessed();
  31232. scene.resetCachedMaterial();
  31233. // Fallbacks
  31234. var fallbacks = new BABYLON.EffectFallbacks();
  31235. if (defines.REFLECTION) {
  31236. fallbacks.addFallback(0, "REFLECTION");
  31237. }
  31238. if (defines.SPECULAR) {
  31239. fallbacks.addFallback(0, "SPECULAR");
  31240. }
  31241. if (defines.BUMP) {
  31242. fallbacks.addFallback(0, "BUMP");
  31243. }
  31244. if (defines.PARALLAX) {
  31245. fallbacks.addFallback(1, "PARALLAX");
  31246. }
  31247. if (defines.PARALLAXOCCLUSION) {
  31248. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  31249. }
  31250. if (defines.SPECULAROVERALPHA) {
  31251. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  31252. }
  31253. if (defines.FOG) {
  31254. fallbacks.addFallback(1, "FOG");
  31255. }
  31256. if (defines.POINTSIZE) {
  31257. fallbacks.addFallback(0, "POINTSIZE");
  31258. }
  31259. if (defines.LOGARITHMICDEPTH) {
  31260. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  31261. }
  31262. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  31263. if (defines.SPECULARTERM) {
  31264. fallbacks.addFallback(0, "SPECULARTERM");
  31265. }
  31266. if (defines.DIFFUSEFRESNEL) {
  31267. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  31268. }
  31269. if (defines.OPACITYFRESNEL) {
  31270. fallbacks.addFallback(2, "OPACITYFRESNEL");
  31271. }
  31272. if (defines.REFLECTIONFRESNEL) {
  31273. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  31274. }
  31275. if (defines.EMISSIVEFRESNEL) {
  31276. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  31277. }
  31278. if (defines.FRESNEL) {
  31279. fallbacks.addFallback(4, "FRESNEL");
  31280. }
  31281. //Attributes
  31282. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31283. if (defines.NORMAL) {
  31284. attribs.push(BABYLON.VertexBuffer.NormalKind);
  31285. }
  31286. if (defines.UV1) {
  31287. attribs.push(BABYLON.VertexBuffer.UVKind);
  31288. }
  31289. if (defines.UV2) {
  31290. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31291. }
  31292. if (defines.VERTEXCOLOR) {
  31293. attribs.push(BABYLON.VertexBuffer.ColorKind);
  31294. }
  31295. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  31296. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  31297. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  31298. var shaderName = "default";
  31299. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  31300. "vFogInfos", "vFogColor", "pointSize",
  31301. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  31302. "mBones",
  31303. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  31304. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  31305. "logarithmicDepthConstant", "vTangentSpaceParams"
  31306. ];
  31307. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  31308. var uniformBuffers = ["Material", "Scene"];
  31309. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  31310. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  31311. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  31312. uniformsNames: uniforms,
  31313. uniformBuffersNames: uniformBuffers,
  31314. samplers: samplers,
  31315. defines: defines,
  31316. maxSimultaneousLights: this._maxSimultaneousLights
  31317. });
  31318. if (this.customShaderNameResolve) {
  31319. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  31320. }
  31321. var join = defines.toString();
  31322. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  31323. attributes: attribs,
  31324. uniformsNames: uniforms,
  31325. uniformBuffersNames: uniformBuffers,
  31326. samplers: samplers,
  31327. defines: join,
  31328. fallbacks: fallbacks,
  31329. onCompiled: this.onCompiled,
  31330. onError: this.onError,
  31331. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31332. }, engine), defines);
  31333. this.buildUniformLayout();
  31334. }
  31335. if (!subMesh.effect.isReady()) {
  31336. return false;
  31337. }
  31338. defines._renderId = scene.getRenderId();
  31339. this._wasPreviouslyReady = true;
  31340. return true;
  31341. };
  31342. StandardMaterial.prototype.buildUniformLayout = function () {
  31343. // Order is important !
  31344. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  31345. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  31346. this._uniformBuffer.addUniform("opacityParts", 4);
  31347. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  31348. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  31349. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  31350. this._uniformBuffer.addUniform("refractionRightColor", 4);
  31351. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  31352. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  31353. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  31354. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  31355. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31356. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31357. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31358. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31359. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  31360. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31361. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  31362. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31363. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31364. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31365. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31366. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31367. this._uniformBuffer.addUniform("specularMatrix", 16);
  31368. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31369. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  31370. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31371. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31372. this._uniformBuffer.addUniform("vSpecularColor", 4);
  31373. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31374. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  31375. this._uniformBuffer.addUniform("pointSize", 1);
  31376. this._uniformBuffer.create();
  31377. };
  31378. StandardMaterial.prototype.unbind = function () {
  31379. if (this._activeEffect) {
  31380. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31381. this._activeEffect.setTexture("reflection2DSampler", null);
  31382. }
  31383. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31384. this._activeEffect.setTexture("refraction2DSampler", null);
  31385. }
  31386. }
  31387. _super.prototype.unbind.call(this);
  31388. };
  31389. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31390. var scene = this.getScene();
  31391. var defines = subMesh._materialDefines;
  31392. if (!defines) {
  31393. return;
  31394. }
  31395. var effect = subMesh.effect;
  31396. this._activeEffect = effect;
  31397. // Matrices
  31398. this.bindOnlyWorldMatrix(world);
  31399. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  31400. // Bones
  31401. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  31402. if (mustRebind) {
  31403. this._uniformBuffer.bindToEffect(effect, "Material");
  31404. this.bindViewProjection(effect);
  31405. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31406. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  31407. // Fresnel
  31408. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  31409. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  31410. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  31411. }
  31412. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  31413. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  31414. }
  31415. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  31416. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  31417. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  31418. }
  31419. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  31420. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  31421. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  31422. }
  31423. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  31424. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  31425. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  31426. }
  31427. }
  31428. // Textures
  31429. if (scene.texturesEnabled) {
  31430. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31431. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  31432. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  31433. }
  31434. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31435. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  31436. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31437. }
  31438. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31439. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31440. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31441. }
  31442. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31443. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  31444. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  31445. }
  31446. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31447. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31448. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31449. }
  31450. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31451. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31452. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31453. }
  31454. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31455. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  31456. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  31457. }
  31458. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31459. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  31460. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31461. if (scene._mirroredCameraPosition) {
  31462. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 1.0 : -1.0);
  31463. }
  31464. else {
  31465. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? -1.0 : 1.0);
  31466. }
  31467. }
  31468. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31469. var depth = 1.0;
  31470. if (!this._refractionTexture.isCube) {
  31471. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  31472. if (this._refractionTexture.depth) {
  31473. depth = this._refractionTexture.depth;
  31474. }
  31475. }
  31476. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  31477. }
  31478. }
  31479. // Point size
  31480. if (this.pointsCloud) {
  31481. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31482. }
  31483. if (defines.SPECULARTERM) {
  31484. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  31485. }
  31486. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  31487. // Diffuse
  31488. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  31489. }
  31490. // Textures
  31491. if (scene.texturesEnabled) {
  31492. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31493. effect.setTexture("diffuseSampler", this._diffuseTexture);
  31494. }
  31495. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31496. effect.setTexture("ambientSampler", this._ambientTexture);
  31497. }
  31498. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31499. effect.setTexture("opacitySampler", this._opacityTexture);
  31500. }
  31501. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31502. if (this._reflectionTexture.isCube) {
  31503. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  31504. }
  31505. else {
  31506. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  31507. }
  31508. }
  31509. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31510. effect.setTexture("emissiveSampler", this._emissiveTexture);
  31511. }
  31512. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31513. effect.setTexture("lightmapSampler", this._lightmapTexture);
  31514. }
  31515. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31516. effect.setTexture("specularSampler", this._specularTexture);
  31517. }
  31518. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31519. effect.setTexture("bumpSampler", this._bumpTexture);
  31520. }
  31521. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31522. var depth = 1.0;
  31523. if (this._refractionTexture.isCube) {
  31524. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  31525. }
  31526. else {
  31527. effect.setTexture("refraction2DSampler", this._refractionTexture);
  31528. }
  31529. }
  31530. }
  31531. // Clip plane
  31532. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  31533. // Colors
  31534. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  31535. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  31536. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31537. }
  31538. if (mustRebind || !this.isFrozen) {
  31539. // Lights
  31540. if (scene.lightsEnabled && !this._disableLighting) {
  31541. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  31542. }
  31543. // View
  31544. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  31545. this.bindView(effect);
  31546. }
  31547. // Fog
  31548. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  31549. // Morph targets
  31550. if (defines.NUM_MORPH_INFLUENCERS) {
  31551. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  31552. }
  31553. // Log. depth
  31554. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  31555. // image processing
  31556. this._imageProcessingConfiguration.bind(this._activeEffect);
  31557. }
  31558. this._uniformBuffer.update();
  31559. this._afterBind(mesh, this._activeEffect);
  31560. };
  31561. StandardMaterial.prototype.getAnimatables = function () {
  31562. var results = [];
  31563. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  31564. results.push(this._diffuseTexture);
  31565. }
  31566. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31567. results.push(this._ambientTexture);
  31568. }
  31569. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31570. results.push(this._opacityTexture);
  31571. }
  31572. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31573. results.push(this._reflectionTexture);
  31574. }
  31575. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31576. results.push(this._emissiveTexture);
  31577. }
  31578. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  31579. results.push(this._specularTexture);
  31580. }
  31581. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31582. results.push(this._bumpTexture);
  31583. }
  31584. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31585. results.push(this._lightmapTexture);
  31586. }
  31587. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31588. results.push(this._refractionTexture);
  31589. }
  31590. return results;
  31591. };
  31592. StandardMaterial.prototype.getActiveTextures = function () {
  31593. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31594. if (this._diffuseTexture) {
  31595. activeTextures.push(this._diffuseTexture);
  31596. }
  31597. if (this._ambientTexture) {
  31598. activeTextures.push(this._ambientTexture);
  31599. }
  31600. if (this._opacityTexture) {
  31601. activeTextures.push(this._opacityTexture);
  31602. }
  31603. if (this._reflectionTexture) {
  31604. activeTextures.push(this._reflectionTexture);
  31605. }
  31606. if (this._emissiveTexture) {
  31607. activeTextures.push(this._emissiveTexture);
  31608. }
  31609. if (this._specularTexture) {
  31610. activeTextures.push(this._specularTexture);
  31611. }
  31612. if (this._bumpTexture) {
  31613. activeTextures.push(this._bumpTexture);
  31614. }
  31615. if (this._lightmapTexture) {
  31616. activeTextures.push(this._lightmapTexture);
  31617. }
  31618. if (this._refractionTexture) {
  31619. activeTextures.push(this._refractionTexture);
  31620. }
  31621. return activeTextures;
  31622. };
  31623. StandardMaterial.prototype.hasTexture = function (texture) {
  31624. if (_super.prototype.hasTexture.call(this, texture)) {
  31625. return true;
  31626. }
  31627. if (this._diffuseTexture === texture) {
  31628. return true;
  31629. }
  31630. if (this._ambientTexture === texture) {
  31631. return true;
  31632. }
  31633. if (this._opacityTexture === texture) {
  31634. return true;
  31635. }
  31636. if (this._reflectionTexture === texture) {
  31637. return true;
  31638. }
  31639. if (this._emissiveTexture === texture) {
  31640. return true;
  31641. }
  31642. if (this._specularTexture === texture) {
  31643. return true;
  31644. }
  31645. if (this._bumpTexture === texture) {
  31646. return true;
  31647. }
  31648. if (this._lightmapTexture === texture) {
  31649. return true;
  31650. }
  31651. if (this._refractionTexture === texture) {
  31652. return true;
  31653. }
  31654. return false;
  31655. };
  31656. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31657. if (forceDisposeTextures) {
  31658. if (this._diffuseTexture) {
  31659. this._diffuseTexture.dispose();
  31660. }
  31661. if (this._ambientTexture) {
  31662. this._ambientTexture.dispose();
  31663. }
  31664. if (this._opacityTexture) {
  31665. this._opacityTexture.dispose();
  31666. }
  31667. if (this._reflectionTexture) {
  31668. this._reflectionTexture.dispose();
  31669. }
  31670. if (this._emissiveTexture) {
  31671. this._emissiveTexture.dispose();
  31672. }
  31673. if (this._specularTexture) {
  31674. this._specularTexture.dispose();
  31675. }
  31676. if (this._bumpTexture) {
  31677. this._bumpTexture.dispose();
  31678. }
  31679. if (this._lightmapTexture) {
  31680. this._lightmapTexture.dispose();
  31681. }
  31682. if (this._refractionTexture) {
  31683. this._refractionTexture.dispose();
  31684. }
  31685. }
  31686. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31687. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31688. }
  31689. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31690. };
  31691. StandardMaterial.prototype.clone = function (name) {
  31692. var _this = this;
  31693. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31694. result.name = name;
  31695. result.id = name;
  31696. return result;
  31697. };
  31698. StandardMaterial.prototype.serialize = function () {
  31699. return BABYLON.SerializationHelper.Serialize(this);
  31700. };
  31701. // Statics
  31702. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31703. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31704. };
  31705. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31706. get: function () {
  31707. return StandardMaterial._DiffuseTextureEnabled;
  31708. },
  31709. set: function (value) {
  31710. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31711. return;
  31712. }
  31713. StandardMaterial._DiffuseTextureEnabled = value;
  31714. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31715. },
  31716. enumerable: true,
  31717. configurable: true
  31718. });
  31719. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31720. get: function () {
  31721. return StandardMaterial._AmbientTextureEnabled;
  31722. },
  31723. set: function (value) {
  31724. if (StandardMaterial._AmbientTextureEnabled === value) {
  31725. return;
  31726. }
  31727. StandardMaterial._AmbientTextureEnabled = value;
  31728. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31729. },
  31730. enumerable: true,
  31731. configurable: true
  31732. });
  31733. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31734. get: function () {
  31735. return StandardMaterial._OpacityTextureEnabled;
  31736. },
  31737. set: function (value) {
  31738. if (StandardMaterial._OpacityTextureEnabled === value) {
  31739. return;
  31740. }
  31741. StandardMaterial._OpacityTextureEnabled = value;
  31742. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31743. },
  31744. enumerable: true,
  31745. configurable: true
  31746. });
  31747. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31748. get: function () {
  31749. return StandardMaterial._ReflectionTextureEnabled;
  31750. },
  31751. set: function (value) {
  31752. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31753. return;
  31754. }
  31755. StandardMaterial._ReflectionTextureEnabled = value;
  31756. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31757. },
  31758. enumerable: true,
  31759. configurable: true
  31760. });
  31761. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31762. get: function () {
  31763. return StandardMaterial._EmissiveTextureEnabled;
  31764. },
  31765. set: function (value) {
  31766. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31767. return;
  31768. }
  31769. StandardMaterial._EmissiveTextureEnabled = value;
  31770. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31771. },
  31772. enumerable: true,
  31773. configurable: true
  31774. });
  31775. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31776. get: function () {
  31777. return StandardMaterial._SpecularTextureEnabled;
  31778. },
  31779. set: function (value) {
  31780. if (StandardMaterial._SpecularTextureEnabled === value) {
  31781. return;
  31782. }
  31783. StandardMaterial._SpecularTextureEnabled = value;
  31784. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31785. },
  31786. enumerable: true,
  31787. configurable: true
  31788. });
  31789. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31790. get: function () {
  31791. return StandardMaterial._BumpTextureEnabled;
  31792. },
  31793. set: function (value) {
  31794. if (StandardMaterial._BumpTextureEnabled === value) {
  31795. return;
  31796. }
  31797. StandardMaterial._BumpTextureEnabled = value;
  31798. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31799. },
  31800. enumerable: true,
  31801. configurable: true
  31802. });
  31803. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31804. get: function () {
  31805. return StandardMaterial._LightmapTextureEnabled;
  31806. },
  31807. set: function (value) {
  31808. if (StandardMaterial._LightmapTextureEnabled === value) {
  31809. return;
  31810. }
  31811. StandardMaterial._LightmapTextureEnabled = value;
  31812. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31813. },
  31814. enumerable: true,
  31815. configurable: true
  31816. });
  31817. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31818. get: function () {
  31819. return StandardMaterial._RefractionTextureEnabled;
  31820. },
  31821. set: function (value) {
  31822. if (StandardMaterial._RefractionTextureEnabled === value) {
  31823. return;
  31824. }
  31825. StandardMaterial._RefractionTextureEnabled = value;
  31826. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31827. },
  31828. enumerable: true,
  31829. configurable: true
  31830. });
  31831. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31832. get: function () {
  31833. return StandardMaterial._ColorGradingTextureEnabled;
  31834. },
  31835. set: function (value) {
  31836. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31837. return;
  31838. }
  31839. StandardMaterial._ColorGradingTextureEnabled = value;
  31840. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31841. },
  31842. enumerable: true,
  31843. configurable: true
  31844. });
  31845. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31846. get: function () {
  31847. return StandardMaterial._FresnelEnabled;
  31848. },
  31849. set: function (value) {
  31850. if (StandardMaterial._FresnelEnabled === value) {
  31851. return;
  31852. }
  31853. StandardMaterial._FresnelEnabled = value;
  31854. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31855. },
  31856. enumerable: true,
  31857. configurable: true
  31858. });
  31859. // Flags used to enable or disable a type of texture for all Standard Materials
  31860. StandardMaterial._DiffuseTextureEnabled = true;
  31861. StandardMaterial._AmbientTextureEnabled = true;
  31862. StandardMaterial._OpacityTextureEnabled = true;
  31863. StandardMaterial._ReflectionTextureEnabled = true;
  31864. StandardMaterial._EmissiveTextureEnabled = true;
  31865. StandardMaterial._SpecularTextureEnabled = true;
  31866. StandardMaterial._BumpTextureEnabled = true;
  31867. StandardMaterial._LightmapTextureEnabled = true;
  31868. StandardMaterial._RefractionTextureEnabled = true;
  31869. StandardMaterial._ColorGradingTextureEnabled = true;
  31870. StandardMaterial._FresnelEnabled = true;
  31871. __decorate([
  31872. BABYLON.serializeAsTexture("diffuseTexture")
  31873. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31874. __decorate([
  31875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31876. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31877. __decorate([
  31878. BABYLON.serializeAsTexture("ambientTexture")
  31879. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31880. __decorate([
  31881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31882. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31883. __decorate([
  31884. BABYLON.serializeAsTexture("opacityTexture")
  31885. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31886. __decorate([
  31887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31888. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31889. __decorate([
  31890. BABYLON.serializeAsTexture("reflectionTexture")
  31891. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31892. __decorate([
  31893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31894. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31895. __decorate([
  31896. BABYLON.serializeAsTexture("emissiveTexture")
  31897. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31898. __decorate([
  31899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31900. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31901. __decorate([
  31902. BABYLON.serializeAsTexture("specularTexture")
  31903. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31904. __decorate([
  31905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31906. ], StandardMaterial.prototype, "specularTexture", void 0);
  31907. __decorate([
  31908. BABYLON.serializeAsTexture("bumpTexture")
  31909. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31910. __decorate([
  31911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31912. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31913. __decorate([
  31914. BABYLON.serializeAsTexture("lightmapTexture")
  31915. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31916. __decorate([
  31917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31918. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31919. __decorate([
  31920. BABYLON.serializeAsTexture("refractionTexture")
  31921. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31922. __decorate([
  31923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31924. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31925. __decorate([
  31926. BABYLON.serializeAsColor3("ambient")
  31927. ], StandardMaterial.prototype, "ambientColor", void 0);
  31928. __decorate([
  31929. BABYLON.serializeAsColor3("diffuse")
  31930. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31931. __decorate([
  31932. BABYLON.serializeAsColor3("specular")
  31933. ], StandardMaterial.prototype, "specularColor", void 0);
  31934. __decorate([
  31935. BABYLON.serializeAsColor3("emissive")
  31936. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31937. __decorate([
  31938. BABYLON.serialize()
  31939. ], StandardMaterial.prototype, "specularPower", void 0);
  31940. __decorate([
  31941. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31942. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31943. __decorate([
  31944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31945. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31946. __decorate([
  31947. BABYLON.serialize("useEmissiveAsIllumination")
  31948. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31949. __decorate([
  31950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31951. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31952. __decorate([
  31953. BABYLON.serialize("linkEmissiveWithDiffuse")
  31954. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31955. __decorate([
  31956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31957. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31958. __decorate([
  31959. BABYLON.serialize("useSpecularOverAlpha")
  31960. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31961. __decorate([
  31962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31963. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31964. __decorate([
  31965. BABYLON.serialize("useReflectionOverAlpha")
  31966. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31967. __decorate([
  31968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31969. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31970. __decorate([
  31971. BABYLON.serialize("disableLighting")
  31972. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31973. __decorate([
  31974. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31975. ], StandardMaterial.prototype, "disableLighting", void 0);
  31976. __decorate([
  31977. BABYLON.serialize("useParallax")
  31978. ], StandardMaterial.prototype, "_useParallax", void 0);
  31979. __decorate([
  31980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31981. ], StandardMaterial.prototype, "useParallax", void 0);
  31982. __decorate([
  31983. BABYLON.serialize("useParallaxOcclusion")
  31984. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31985. __decorate([
  31986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31987. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31988. __decorate([
  31989. BABYLON.serialize()
  31990. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31991. __decorate([
  31992. BABYLON.serialize("roughness")
  31993. ], StandardMaterial.prototype, "_roughness", void 0);
  31994. __decorate([
  31995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31996. ], StandardMaterial.prototype, "roughness", void 0);
  31997. __decorate([
  31998. BABYLON.serialize()
  31999. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  32000. __decorate([
  32001. BABYLON.serialize()
  32002. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  32003. __decorate([
  32004. BABYLON.serialize("useLightmapAsShadowmap")
  32005. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  32006. __decorate([
  32007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32008. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  32009. __decorate([
  32010. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  32011. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  32012. __decorate([
  32013. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32014. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  32015. __decorate([
  32016. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  32017. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  32018. __decorate([
  32019. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32020. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  32021. __decorate([
  32022. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  32023. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  32024. __decorate([
  32025. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32026. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  32027. __decorate([
  32028. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  32029. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  32030. __decorate([
  32031. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32032. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  32033. __decorate([
  32034. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  32035. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  32036. __decorate([
  32037. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32038. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  32039. __decorate([
  32040. BABYLON.serialize("useReflectionFresnelFromSpecular")
  32041. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  32042. __decorate([
  32043. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32044. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  32045. __decorate([
  32046. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  32047. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  32048. __decorate([
  32049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32050. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  32051. __decorate([
  32052. BABYLON.serialize("maxSimultaneousLights")
  32053. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  32054. __decorate([
  32055. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32056. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  32057. __decorate([
  32058. BABYLON.serialize("invertNormalMapX")
  32059. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  32060. __decorate([
  32061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32062. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  32063. __decorate([
  32064. BABYLON.serialize("invertNormalMapY")
  32065. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  32066. __decorate([
  32067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32068. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  32069. __decorate([
  32070. BABYLON.serialize("twoSidedLighting")
  32071. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  32072. __decorate([
  32073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32074. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  32075. __decorate([
  32076. BABYLON.serialize()
  32077. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  32078. return StandardMaterial;
  32079. }(BABYLON.PushMaterial));
  32080. BABYLON.StandardMaterial = StandardMaterial;
  32081. })(BABYLON || (BABYLON = {}));
  32082. //# sourceMappingURL=babylon.standardMaterial.js.map
  32083. var BABYLON;
  32084. (function (BABYLON) {
  32085. var PBRMaterialDefines = (function (_super) {
  32086. __extends(PBRMaterialDefines, _super);
  32087. function PBRMaterialDefines() {
  32088. var _this = _super.call(this) || this;
  32089. _this.PBR = true;
  32090. _this.MAINUV1 = false;
  32091. _this.MAINUV2 = false;
  32092. _this.UV1 = false;
  32093. _this.UV2 = false;
  32094. _this.ALBEDO = false;
  32095. _this.ALBEDODIRECTUV = 0;
  32096. _this.VERTEXCOLOR = false;
  32097. _this.AMBIENT = false;
  32098. _this.AMBIENTDIRECTUV = 0;
  32099. _this.AMBIENTINGRAYSCALE = false;
  32100. _this.OPACITY = false;
  32101. _this.VERTEXALPHA = false;
  32102. _this.OPACITYDIRECTUV = 0;
  32103. _this.OPACITYRGB = false;
  32104. _this.ALPHATEST = false;
  32105. _this.DEPTHPREPASS = false;
  32106. _this.ALPHABLEND = false;
  32107. _this.ALPHAFROMALBEDO = false;
  32108. _this.ALPHATESTVALUE = 0.5;
  32109. _this.SPECULAROVERALPHA = false;
  32110. _this.RADIANCEOVERALPHA = false;
  32111. _this.ALPHAFRESNEL = false;
  32112. _this.PREMULTIPLYALPHA = false;
  32113. _this.EMISSIVE = false;
  32114. _this.EMISSIVEDIRECTUV = 0;
  32115. _this.REFLECTIVITY = false;
  32116. _this.REFLECTIVITYDIRECTUV = 0;
  32117. _this.SPECULARTERM = false;
  32118. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  32119. _this.MICROSURFACEAUTOMATIC = false;
  32120. _this.LODBASEDMICROSFURACE = false;
  32121. _this.MICROSURFACEMAP = false;
  32122. _this.MICROSURFACEMAPDIRECTUV = 0;
  32123. _this.METALLICWORKFLOW = false;
  32124. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  32125. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  32126. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  32127. _this.AOSTOREINMETALMAPRED = false;
  32128. _this.ENVIRONMENTBRDF = false;
  32129. _this.NORMAL = false;
  32130. _this.TANGENT = false;
  32131. _this.BUMP = false;
  32132. _this.BUMPDIRECTUV = 0;
  32133. _this.PARALLAX = false;
  32134. _this.PARALLAXOCCLUSION = false;
  32135. _this.NORMALXYSCALE = true;
  32136. _this.LIGHTMAP = false;
  32137. _this.LIGHTMAPDIRECTUV = 0;
  32138. _this.USELIGHTMAPASSHADOWMAP = false;
  32139. _this.REFLECTION = false;
  32140. _this.REFLECTIONMAP_3D = false;
  32141. _this.REFLECTIONMAP_SPHERICAL = false;
  32142. _this.REFLECTIONMAP_PLANAR = false;
  32143. _this.REFLECTIONMAP_CUBIC = false;
  32144. _this.REFLECTIONMAP_PROJECTION = false;
  32145. _this.REFLECTIONMAP_SKYBOX = false;
  32146. _this.REFLECTIONMAP_EXPLICIT = false;
  32147. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32148. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32149. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32150. _this.INVERTCUBICMAP = false;
  32151. _this.USESPHERICALFROMREFLECTIONMAP = false;
  32152. _this.USESPHERICALINFRAGMENT = false;
  32153. _this.REFLECTIONMAP_OPPOSITEZ = false;
  32154. _this.LODINREFLECTIONALPHA = false;
  32155. _this.GAMMAREFLECTION = false;
  32156. _this.REFRACTION = false;
  32157. _this.REFRACTIONMAP_3D = false;
  32158. _this.REFRACTIONMAP_OPPOSITEZ = false;
  32159. _this.LODINREFRACTIONALPHA = false;
  32160. _this.GAMMAREFRACTION = false;
  32161. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  32162. _this.INSTANCES = false;
  32163. _this.NUM_BONE_INFLUENCERS = 0;
  32164. _this.BonesPerMesh = 0;
  32165. _this.MORPHTARGETS = false;
  32166. _this.MORPHTARGETS_NORMAL = false;
  32167. _this.MORPHTARGETS_TANGENT = false;
  32168. _this.NUM_MORPH_INFLUENCERS = 0;
  32169. _this.IMAGEPROCESSING = false;
  32170. _this.VIGNETTE = false;
  32171. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  32172. _this.VIGNETTEBLENDMODEOPAQUE = false;
  32173. _this.TONEMAPPING = false;
  32174. _this.CONTRAST = false;
  32175. _this.COLORCURVES = false;
  32176. _this.COLORGRADING = false;
  32177. _this.SAMPLER3DGREENDEPTH = false;
  32178. _this.SAMPLER3DBGRMAP = false;
  32179. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  32180. _this.EXPOSURE = false;
  32181. _this.USEPHYSICALLIGHTFALLOFF = false;
  32182. _this.TWOSIDEDLIGHTING = false;
  32183. _this.SHADOWFLOAT = false;
  32184. _this.CLIPPLANE = false;
  32185. _this.POINTSIZE = false;
  32186. _this.FOG = false;
  32187. _this.LOGARITHMICDEPTH = false;
  32188. _this.FORCENORMALFORWARD = false;
  32189. _this.rebuild();
  32190. return _this;
  32191. }
  32192. PBRMaterialDefines.prototype.reset = function () {
  32193. _super.prototype.reset.call(this);
  32194. this.ALPHATESTVALUE = 0.5;
  32195. this.PBR = true;
  32196. };
  32197. return PBRMaterialDefines;
  32198. }(BABYLON.MaterialDefines));
  32199. /**
  32200. * The Physically based material base class of BJS.
  32201. *
  32202. * This offers the main features of a standard PBR material.
  32203. * For more information, please refer to the documentation :
  32204. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  32205. */
  32206. var PBRBaseMaterial = (function (_super) {
  32207. __extends(PBRBaseMaterial, _super);
  32208. /**
  32209. * Instantiates a new PBRMaterial instance.
  32210. *
  32211. * @param name The material name
  32212. * @param scene The scene the material will be use in.
  32213. */
  32214. function PBRBaseMaterial(name, scene) {
  32215. var _this = _super.call(this, name, scene) || this;
  32216. /**
  32217. * Intensity of the direct lights e.g. the four lights available in your scene.
  32218. * This impacts both the direct diffuse and specular highlights.
  32219. */
  32220. _this._directIntensity = 1.0;
  32221. /**
  32222. * Intensity of the emissive part of the material.
  32223. * This helps controlling the emissive effect without modifying the emissive color.
  32224. */
  32225. _this._emissiveIntensity = 1.0;
  32226. /**
  32227. * Intensity of the environment e.g. how much the environment will light the object
  32228. * either through harmonics for rough material or through the refelction for shiny ones.
  32229. */
  32230. _this._environmentIntensity = 1.0;
  32231. /**
  32232. * This is a special control allowing the reduction of the specular highlights coming from the
  32233. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32234. */
  32235. _this._specularIntensity = 1.0;
  32236. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  32237. /**
  32238. * Debug Control allowing disabling the bump map on this material.
  32239. */
  32240. _this._disableBumpMap = false;
  32241. /**
  32242. * AKA Occlusion Texture Intensity in other nomenclature.
  32243. */
  32244. _this._ambientTextureStrength = 1.0;
  32245. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  32246. /**
  32247. * AKA Diffuse Color in other nomenclature.
  32248. */
  32249. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  32250. /**
  32251. * AKA Specular Color in other nomenclature.
  32252. */
  32253. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32254. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  32255. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  32256. /**
  32257. * AKA Glossiness in other nomenclature.
  32258. */
  32259. _this._microSurface = 0.9;
  32260. /**
  32261. * source material index of refraction (IOR)' / 'destination material IOR.
  32262. */
  32263. _this._indexOfRefraction = 0.66;
  32264. /**
  32265. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32266. */
  32267. _this._invertRefractionY = false;
  32268. /**
  32269. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32270. * Materials half opaque for instance using refraction could benefit from this control.
  32271. */
  32272. _this._linkRefractionWithTransparency = false;
  32273. _this._useLightmapAsShadowmap = false;
  32274. /**
  32275. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32276. */
  32277. _this._useAlphaFromAlbedoTexture = false;
  32278. /**
  32279. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32280. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32281. */
  32282. _this._useSpecularOverAlpha = true;
  32283. /**
  32284. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32285. */
  32286. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  32287. /**
  32288. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32289. */
  32290. _this._useRoughnessFromMetallicTextureAlpha = true;
  32291. /**
  32292. * Specifies if the metallic texture contains the roughness information in its green channel.
  32293. */
  32294. _this._useRoughnessFromMetallicTextureGreen = false;
  32295. /**
  32296. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32297. */
  32298. _this._useMetallnessFromMetallicTextureBlue = false;
  32299. /**
  32300. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32301. */
  32302. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  32303. /**
  32304. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32305. */
  32306. _this._useAmbientInGrayScale = false;
  32307. /**
  32308. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32309. * The material will try to infer what glossiness each pixel should be.
  32310. */
  32311. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  32312. /**
  32313. * BJS is using an harcoded light falloff based on a manually sets up range.
  32314. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32315. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32316. */
  32317. _this._usePhysicalLightFalloff = true;
  32318. /**
  32319. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32320. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32321. */
  32322. _this._useRadianceOverAlpha = true;
  32323. /**
  32324. * Allows using the bump map in parallax mode.
  32325. */
  32326. _this._useParallax = false;
  32327. /**
  32328. * Allows using the bump map in parallax occlusion mode.
  32329. */
  32330. _this._useParallaxOcclusion = false;
  32331. /**
  32332. * Controls the scale bias of the parallax mode.
  32333. */
  32334. _this._parallaxScaleBias = 0.05;
  32335. /**
  32336. * If sets to true, disables all the lights affecting the material.
  32337. */
  32338. _this._disableLighting = false;
  32339. /**
  32340. * Number of Simultaneous lights allowed on the material.
  32341. */
  32342. _this._maxSimultaneousLights = 4;
  32343. /**
  32344. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  32345. */
  32346. _this._invertNormalMapX = false;
  32347. /**
  32348. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  32349. */
  32350. _this._invertNormalMapY = false;
  32351. /**
  32352. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32353. */
  32354. _this._twoSidedLighting = false;
  32355. /**
  32356. * Defines the alpha limits in alpha test mode.
  32357. */
  32358. _this._alphaCutOff = 0.4;
  32359. /**
  32360. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32361. */
  32362. _this._forceAlphaTest = false;
  32363. /**
  32364. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32365. * in your scene composition.
  32366. */
  32367. _this._preMultiplyAlpha = false;
  32368. /**
  32369. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32370. * And/Or occlude the blended part.
  32371. */
  32372. _this._useAlphaFresnel = false;
  32373. /**
  32374. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  32375. * from cos thetav and roughness:
  32376. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  32377. */
  32378. _this._environmentBRDFTexture = null;
  32379. /**
  32380. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32381. */
  32382. _this._forceIrradianceInFragment = false;
  32383. /**
  32384. * Force normal to face away from face.
  32385. * (Temporary internal fix to remove before 3.1)
  32386. */
  32387. _this._forceNormalForward = false;
  32388. _this._renderTargets = new BABYLON.SmartArray(16);
  32389. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32390. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32391. _this._tempColor = new BABYLON.Color3();
  32392. // Setup the default processing configuration to the scene.
  32393. _this._attachImageProcessingConfiguration(null);
  32394. _this.getRenderTargetTextures = function () {
  32395. _this._renderTargets.reset();
  32396. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32397. _this._renderTargets.push(_this._reflectionTexture);
  32398. }
  32399. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32400. _this._renderTargets.push(_this._refractionTexture);
  32401. }
  32402. return _this._renderTargets;
  32403. };
  32404. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32405. return _this;
  32406. }
  32407. /**
  32408. * Attaches a new image processing configuration to the PBR Material.
  32409. * @param configuration
  32410. */
  32411. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32412. var _this = this;
  32413. if (configuration === this._imageProcessingConfiguration) {
  32414. return;
  32415. }
  32416. // Detaches observer.
  32417. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32418. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32419. }
  32420. // Pick the scene configuration if needed.
  32421. if (!configuration) {
  32422. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32423. }
  32424. else {
  32425. this._imageProcessingConfiguration = configuration;
  32426. }
  32427. // Attaches observer.
  32428. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32429. _this._markAllSubMeshesAsImageProcessingDirty();
  32430. });
  32431. };
  32432. PBRBaseMaterial.prototype.getClassName = function () {
  32433. return "PBRBaseMaterial";
  32434. };
  32435. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  32436. get: function () {
  32437. return this._useLogarithmicDepth;
  32438. },
  32439. set: function (value) {
  32440. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32441. },
  32442. enumerable: true,
  32443. configurable: true
  32444. });
  32445. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  32446. if (this._linkRefractionWithTransparency) {
  32447. return false;
  32448. }
  32449. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  32450. };
  32451. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  32452. if (this._forceAlphaTest) {
  32453. return true;
  32454. }
  32455. if (this._linkRefractionWithTransparency) {
  32456. return false;
  32457. }
  32458. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  32459. };
  32460. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32461. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  32462. };
  32463. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  32464. return this._albedoTexture;
  32465. };
  32466. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32467. if (this.isFrozen) {
  32468. if (this._wasPreviouslyReady) {
  32469. return true;
  32470. }
  32471. }
  32472. if (!subMesh._materialDefines) {
  32473. subMesh._materialDefines = new PBRMaterialDefines();
  32474. }
  32475. var scene = this.getScene();
  32476. var defines = subMesh._materialDefines;
  32477. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32478. if (defines._renderId === scene.getRenderId()) {
  32479. return true;
  32480. }
  32481. }
  32482. var engine = scene.getEngine();
  32483. // Lights
  32484. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32485. defines._needNormals = true;
  32486. // Textures
  32487. if (defines._areTexturesDirty) {
  32488. defines._needUVs = false;
  32489. if (scene.texturesEnabled) {
  32490. if (scene.getEngine().getCaps().textureLOD) {
  32491. defines.LODBASEDMICROSFURACE = true;
  32492. }
  32493. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32494. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  32495. return false;
  32496. }
  32497. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  32498. }
  32499. else {
  32500. defines.ALBEDO = false;
  32501. }
  32502. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32503. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32504. return false;
  32505. }
  32506. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32507. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  32508. }
  32509. else {
  32510. defines.AMBIENT = false;
  32511. }
  32512. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32513. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32514. return false;
  32515. }
  32516. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32517. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32518. }
  32519. else {
  32520. defines.OPACITY = false;
  32521. }
  32522. var reflectionTexture = this._getReflectionTexture();
  32523. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32524. if (!reflectionTexture.isReadyOrNotBlocking()) {
  32525. return false;
  32526. }
  32527. defines.REFLECTION = true;
  32528. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  32529. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  32530. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32531. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  32532. defines.INVERTCUBICMAP = true;
  32533. }
  32534. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  32535. switch (reflectionTexture.coordinatesMode) {
  32536. case BABYLON.Texture.CUBIC_MODE:
  32537. case BABYLON.Texture.INVCUBIC_MODE:
  32538. defines.REFLECTIONMAP_CUBIC = true;
  32539. break;
  32540. case BABYLON.Texture.EXPLICIT_MODE:
  32541. defines.REFLECTIONMAP_EXPLICIT = true;
  32542. break;
  32543. case BABYLON.Texture.PLANAR_MODE:
  32544. defines.REFLECTIONMAP_PLANAR = true;
  32545. break;
  32546. case BABYLON.Texture.PROJECTION_MODE:
  32547. defines.REFLECTIONMAP_PROJECTION = true;
  32548. break;
  32549. case BABYLON.Texture.SKYBOX_MODE:
  32550. defines.REFLECTIONMAP_SKYBOX = true;
  32551. break;
  32552. case BABYLON.Texture.SPHERICAL_MODE:
  32553. defines.REFLECTIONMAP_SPHERICAL = true;
  32554. break;
  32555. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32556. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  32557. break;
  32558. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32559. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  32560. break;
  32561. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32562. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  32563. break;
  32564. }
  32565. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  32566. if (reflectionTexture.sphericalPolynomial) {
  32567. defines.USESPHERICALFROMREFLECTIONMAP = true;
  32568. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  32569. defines.USESPHERICALINFRAGMENT = true;
  32570. }
  32571. }
  32572. }
  32573. }
  32574. else {
  32575. defines.REFLECTION = false;
  32576. defines.REFLECTIONMAP_3D = false;
  32577. defines.REFLECTIONMAP_SPHERICAL = false;
  32578. defines.REFLECTIONMAP_PLANAR = false;
  32579. defines.REFLECTIONMAP_CUBIC = false;
  32580. defines.REFLECTIONMAP_PROJECTION = false;
  32581. defines.REFLECTIONMAP_SKYBOX = false;
  32582. defines.REFLECTIONMAP_EXPLICIT = false;
  32583. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32584. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32585. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32586. defines.INVERTCUBICMAP = false;
  32587. defines.USESPHERICALFROMREFLECTIONMAP = false;
  32588. defines.USESPHERICALINFRAGMENT = false;
  32589. defines.REFLECTIONMAP_OPPOSITEZ = false;
  32590. defines.LODINREFLECTIONALPHA = false;
  32591. defines.GAMMAREFLECTION = false;
  32592. }
  32593. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32594. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32595. return false;
  32596. }
  32597. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32598. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32599. }
  32600. else {
  32601. defines.LIGHTMAP = false;
  32602. }
  32603. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32604. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32605. return false;
  32606. }
  32607. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32608. }
  32609. else {
  32610. defines.EMISSIVE = false;
  32611. }
  32612. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32613. if (this._metallicTexture) {
  32614. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  32615. return false;
  32616. }
  32617. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  32618. defines.METALLICWORKFLOW = true;
  32619. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  32620. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  32621. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  32622. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  32623. }
  32624. else if (this._reflectivityTexture) {
  32625. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  32626. return false;
  32627. }
  32628. defines.METALLICWORKFLOW = false;
  32629. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  32630. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  32631. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  32632. }
  32633. else {
  32634. defines.METALLICWORKFLOW = false;
  32635. defines.REFLECTIVITY = false;
  32636. }
  32637. if (this._microSurfaceTexture) {
  32638. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  32639. return false;
  32640. }
  32641. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  32642. }
  32643. else {
  32644. defines.MICROSURFACEMAP = false;
  32645. }
  32646. }
  32647. else {
  32648. defines.REFLECTIVITY = false;
  32649. defines.MICROSURFACEMAP = false;
  32650. }
  32651. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32652. // Bump texure can not be none blocking.
  32653. if (!this._bumpTexture.isReady()) {
  32654. return false;
  32655. }
  32656. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32657. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32658. defines.PARALLAX = true;
  32659. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  32660. }
  32661. else {
  32662. defines.PARALLAX = false;
  32663. }
  32664. }
  32665. else {
  32666. defines.BUMP = false;
  32667. }
  32668. var refractionTexture = this._getRefractionTexture();
  32669. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32670. if (!refractionTexture.isReadyOrNotBlocking()) {
  32671. return false;
  32672. }
  32673. defines.REFRACTION = true;
  32674. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32675. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32676. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32677. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32678. if (this._linkRefractionWithTransparency) {
  32679. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32680. }
  32681. }
  32682. else {
  32683. defines.REFRACTION = false;
  32684. }
  32685. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32686. // This is blocking.
  32687. if (!this._environmentBRDFTexture.isReady()) {
  32688. return false;
  32689. }
  32690. defines.ENVIRONMENTBRDF = true;
  32691. }
  32692. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32693. defines.ALPHAFROMALBEDO = true;
  32694. }
  32695. }
  32696. if (this._useSpecularOverAlpha) {
  32697. defines.SPECULAROVERALPHA = true;
  32698. }
  32699. if (this._usePhysicalLightFalloff) {
  32700. defines.USEPHYSICALLIGHTFALLOFF = true;
  32701. }
  32702. if (this._useRadianceOverAlpha) {
  32703. defines.RADIANCEOVERALPHA = true;
  32704. }
  32705. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32706. defines.METALLICWORKFLOW = true;
  32707. }
  32708. if (!this.backFaceCulling && this._twoSidedLighting) {
  32709. defines.TWOSIDEDLIGHTING = true;
  32710. }
  32711. defines.ALPHATESTVALUE = this._alphaCutOff;
  32712. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32713. defines.ALPHABLEND = this.needAlphaBlending();
  32714. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32715. }
  32716. if (defines._areImageProcessingDirty) {
  32717. if (!this._imageProcessingConfiguration.isReady()) {
  32718. return false;
  32719. }
  32720. this._imageProcessingConfiguration.prepareDefines(defines);
  32721. }
  32722. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32723. // Misc.
  32724. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32725. // Values that need to be evaluated on every frame
  32726. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32727. // Attribs
  32728. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32729. if (mesh) {
  32730. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32731. mesh.createNormals(true);
  32732. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32733. }
  32734. }
  32735. }
  32736. // Get correct effect
  32737. if (defines.isDirty) {
  32738. defines.markAsProcessed();
  32739. scene.resetCachedMaterial();
  32740. // Fallbacks
  32741. var fallbacks = new BABYLON.EffectFallbacks();
  32742. if (defines.ENVIRONMENTBRDF) {
  32743. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32744. }
  32745. if (defines.REFLECTION) {
  32746. fallbacks.addFallback(0, "REFLECTION");
  32747. }
  32748. if (defines.REFRACTION) {
  32749. fallbacks.addFallback(0, "REFRACTION");
  32750. }
  32751. if (defines.REFLECTIVITY) {
  32752. fallbacks.addFallback(0, "REFLECTIVITY");
  32753. }
  32754. if (defines.BUMP) {
  32755. fallbacks.addFallback(0, "BUMP");
  32756. }
  32757. if (defines.PARALLAX) {
  32758. fallbacks.addFallback(1, "PARALLAX");
  32759. }
  32760. if (defines.PARALLAXOCCLUSION) {
  32761. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32762. }
  32763. if (defines.SPECULAROVERALPHA) {
  32764. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32765. }
  32766. if (defines.FOG) {
  32767. fallbacks.addFallback(1, "FOG");
  32768. }
  32769. if (defines.POINTSIZE) {
  32770. fallbacks.addFallback(0, "POINTSIZE");
  32771. }
  32772. if (defines.LOGARITHMICDEPTH) {
  32773. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32774. }
  32775. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32776. if (defines.SPECULARTERM) {
  32777. fallbacks.addFallback(0, "SPECULARTERM");
  32778. }
  32779. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32780. fallbacks.addCPUSkinningFallback(0, mesh);
  32781. }
  32782. //Attributes
  32783. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32784. if (defines.NORMAL) {
  32785. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32786. }
  32787. if (defines.TANGENT) {
  32788. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32789. }
  32790. if (defines.UV1) {
  32791. attribs.push(BABYLON.VertexBuffer.UVKind);
  32792. }
  32793. if (defines.UV2) {
  32794. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32795. }
  32796. if (defines.VERTEXCOLOR) {
  32797. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32798. }
  32799. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32800. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32801. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32802. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32803. "vFogInfos", "vFogColor", "pointSize",
  32804. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32805. "mBones",
  32806. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32807. "vLightingIntensity",
  32808. "logarithmicDepthConstant",
  32809. "vSphericalX", "vSphericalY", "vSphericalZ",
  32810. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32811. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32812. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32813. "vTangentSpaceParams"
  32814. ];
  32815. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32816. "bumpSampler", "lightmapSampler", "opacitySampler",
  32817. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32818. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32819. "microSurfaceSampler", "environmentBrdfSampler"];
  32820. var uniformBuffers = ["Material", "Scene"];
  32821. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32822. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32823. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32824. uniformsNames: uniforms,
  32825. uniformBuffersNames: uniformBuffers,
  32826. samplers: samplers,
  32827. defines: defines,
  32828. maxSimultaneousLights: this._maxSimultaneousLights
  32829. });
  32830. var onCompiled = function (effect) {
  32831. if (this.onCompiled) {
  32832. this.onCompiled(effect);
  32833. }
  32834. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32835. }.bind(this);
  32836. var join = defines.toString();
  32837. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32838. attributes: attribs,
  32839. uniformsNames: uniforms,
  32840. uniformBuffersNames: uniformBuffers,
  32841. samplers: samplers,
  32842. defines: join,
  32843. fallbacks: fallbacks,
  32844. onCompiled: onCompiled,
  32845. onError: this.onError,
  32846. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32847. }, engine), defines);
  32848. this.buildUniformLayout();
  32849. }
  32850. if (!subMesh.effect.isReady()) {
  32851. return false;
  32852. }
  32853. defines._renderId = scene.getRenderId();
  32854. this._wasPreviouslyReady = true;
  32855. return true;
  32856. };
  32857. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32858. // Order is important !
  32859. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32860. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32861. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32862. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32863. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32864. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32865. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32866. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32867. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32868. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32869. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32870. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32871. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32872. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32873. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32874. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32875. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32876. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32877. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  32878. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32879. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32880. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32881. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32882. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32883. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32884. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32885. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32886. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32887. this._uniformBuffer.addUniform("pointSize", 1);
  32888. this._uniformBuffer.create();
  32889. };
  32890. PBRBaseMaterial.prototype.unbind = function () {
  32891. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32892. this._uniformBuffer.setTexture("reflectionSampler", null);
  32893. }
  32894. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32895. this._uniformBuffer.setTexture("refractionSampler", null);
  32896. }
  32897. _super.prototype.unbind.call(this);
  32898. };
  32899. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32900. this._activeEffect.setMatrix("world", world);
  32901. };
  32902. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32903. var scene = this.getScene();
  32904. var defines = subMesh._materialDefines;
  32905. if (!defines) {
  32906. return;
  32907. }
  32908. var effect = subMesh.effect;
  32909. this._activeEffect = effect;
  32910. // Matrices
  32911. this.bindOnlyWorldMatrix(world);
  32912. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32913. // Bones
  32914. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32915. if (mustRebind) {
  32916. this._uniformBuffer.bindToEffect(effect, "Material");
  32917. this.bindViewProjection(effect);
  32918. var reflectionTexture = this._getReflectionTexture();
  32919. var refractionTexture = this._getRefractionTexture();
  32920. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32921. // Texture uniforms
  32922. if (scene.texturesEnabled) {
  32923. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32924. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32925. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32926. }
  32927. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32928. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32929. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32930. }
  32931. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32932. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32933. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32934. }
  32935. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32936. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32937. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32938. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32939. var polynomials = reflectionTexture.sphericalPolynomial;
  32940. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32941. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32942. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32943. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32944. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32945. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32946. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32947. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32948. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32949. }
  32950. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32951. }
  32952. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32953. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32954. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32955. }
  32956. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32957. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32958. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32959. }
  32960. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32961. if (this._metallicTexture) {
  32962. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32963. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32964. }
  32965. else if (this._reflectivityTexture) {
  32966. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32967. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32968. }
  32969. if (this._microSurfaceTexture) {
  32970. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32971. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32972. }
  32973. }
  32974. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32975. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32976. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32977. if (scene._mirroredCameraPosition) {
  32978. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  32979. }
  32980. else {
  32981. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  32982. }
  32983. }
  32984. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32985. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32986. var depth = 1.0;
  32987. if (!refractionTexture.isCube) {
  32988. if (refractionTexture.depth) {
  32989. depth = refractionTexture.depth;
  32990. }
  32991. }
  32992. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32993. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32994. }
  32995. }
  32996. // Point size
  32997. if (this.pointsCloud) {
  32998. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32999. }
  33000. // Colors
  33001. if (defines.METALLICWORKFLOW) {
  33002. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  33003. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  33004. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  33005. }
  33006. else {
  33007. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  33008. }
  33009. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  33010. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  33011. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  33012. // Misc
  33013. this._lightingInfos.x = this._directIntensity;
  33014. this._lightingInfos.y = this._emissiveIntensity;
  33015. this._lightingInfos.z = this._environmentIntensity;
  33016. this._lightingInfos.w = this._specularIntensity;
  33017. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  33018. }
  33019. // Textures
  33020. if (scene.texturesEnabled) {
  33021. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  33022. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  33023. }
  33024. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  33025. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  33026. }
  33027. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  33028. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  33029. }
  33030. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  33031. if (defines.LODBASEDMICROSFURACE) {
  33032. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  33033. }
  33034. else {
  33035. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  33036. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  33037. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  33038. }
  33039. }
  33040. if (defines.ENVIRONMENTBRDF) {
  33041. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  33042. }
  33043. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  33044. if (defines.LODBASEDMICROSFURACE) {
  33045. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  33046. }
  33047. else {
  33048. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  33049. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  33050. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  33051. }
  33052. }
  33053. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  33054. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  33055. }
  33056. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  33057. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  33058. }
  33059. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  33060. if (this._metallicTexture) {
  33061. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  33062. }
  33063. else if (this._reflectivityTexture) {
  33064. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  33065. }
  33066. if (this._microSurfaceTexture) {
  33067. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  33068. }
  33069. }
  33070. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  33071. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  33072. }
  33073. }
  33074. // Clip plane
  33075. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  33076. // Colors
  33077. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  33078. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  33079. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  33080. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  33081. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  33082. }
  33083. if (mustRebind || !this.isFrozen) {
  33084. // Lights
  33085. if (scene.lightsEnabled && !this._disableLighting) {
  33086. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  33087. }
  33088. // View
  33089. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  33090. this.bindView(effect);
  33091. }
  33092. // Fog
  33093. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  33094. // Morph targets
  33095. if (defines.NUM_MORPH_INFLUENCERS) {
  33096. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  33097. }
  33098. // image processing
  33099. this._imageProcessingConfiguration.bind(this._activeEffect);
  33100. // Log. depth
  33101. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  33102. }
  33103. this._uniformBuffer.update();
  33104. this._afterBind(mesh);
  33105. scene = null;
  33106. };
  33107. PBRBaseMaterial.prototype.getAnimatables = function () {
  33108. var results = [];
  33109. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  33110. results.push(this._albedoTexture);
  33111. }
  33112. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  33113. results.push(this._ambientTexture);
  33114. }
  33115. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  33116. results.push(this._opacityTexture);
  33117. }
  33118. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  33119. results.push(this._reflectionTexture);
  33120. }
  33121. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  33122. results.push(this._emissiveTexture);
  33123. }
  33124. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  33125. results.push(this._metallicTexture);
  33126. }
  33127. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  33128. results.push(this._reflectivityTexture);
  33129. }
  33130. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  33131. results.push(this._bumpTexture);
  33132. }
  33133. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  33134. results.push(this._lightmapTexture);
  33135. }
  33136. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  33137. results.push(this._refractionTexture);
  33138. }
  33139. return results;
  33140. };
  33141. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  33142. if (this._reflectionTexture) {
  33143. return this._reflectionTexture;
  33144. }
  33145. return this.getScene().environmentTexture;
  33146. };
  33147. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  33148. if (this._refractionTexture) {
  33149. return this._refractionTexture;
  33150. }
  33151. if (this._linkRefractionWithTransparency) {
  33152. return this.getScene().environmentTexture;
  33153. }
  33154. return null;
  33155. };
  33156. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  33157. if (forceDisposeTextures) {
  33158. if (this._albedoTexture) {
  33159. this._albedoTexture.dispose();
  33160. }
  33161. if (this._ambientTexture) {
  33162. this._ambientTexture.dispose();
  33163. }
  33164. if (this._opacityTexture) {
  33165. this._opacityTexture.dispose();
  33166. }
  33167. if (this._reflectionTexture) {
  33168. this._reflectionTexture.dispose();
  33169. }
  33170. if (this._environmentBRDFTexture) {
  33171. this._environmentBRDFTexture.dispose();
  33172. }
  33173. if (this._emissiveTexture) {
  33174. this._emissiveTexture.dispose();
  33175. }
  33176. if (this._metallicTexture) {
  33177. this._metallicTexture.dispose();
  33178. }
  33179. if (this._reflectivityTexture) {
  33180. this._reflectivityTexture.dispose();
  33181. }
  33182. if (this._bumpTexture) {
  33183. this._bumpTexture.dispose();
  33184. }
  33185. if (this._lightmapTexture) {
  33186. this._lightmapTexture.dispose();
  33187. }
  33188. if (this._refractionTexture) {
  33189. this._refractionTexture.dispose();
  33190. }
  33191. }
  33192. this._renderTargets.dispose();
  33193. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33194. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33195. }
  33196. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  33197. };
  33198. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  33199. __decorate([
  33200. BABYLON.serializeAsImageProcessingConfiguration()
  33201. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  33202. __decorate([
  33203. BABYLON.serialize()
  33204. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  33205. return PBRBaseMaterial;
  33206. }(BABYLON.PushMaterial));
  33207. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  33208. })(BABYLON || (BABYLON = {}));
  33209. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  33210. var BABYLON;
  33211. (function (BABYLON) {
  33212. var Internals;
  33213. (function (Internals) {
  33214. /**
  33215. * The Physically based simple base material of BJS.
  33216. *
  33217. * This enables better naming and convention enforcements on top of the pbrMaterial.
  33218. * It is used as the base class for both the specGloss and metalRough conventions.
  33219. */
  33220. var PBRBaseSimpleMaterial = (function (_super) {
  33221. __extends(PBRBaseSimpleMaterial, _super);
  33222. /**
  33223. * Instantiates a new PBRMaterial instance.
  33224. *
  33225. * @param name The material name
  33226. * @param scene The scene the material will be use in.
  33227. */
  33228. function PBRBaseSimpleMaterial(name, scene) {
  33229. var _this = _super.call(this, name, scene) || this;
  33230. /**
  33231. * Number of Simultaneous lights allowed on the material.
  33232. */
  33233. _this.maxSimultaneousLights = 4;
  33234. /**
  33235. * If sets to true, disables all the lights affecting the material.
  33236. */
  33237. _this.disableLighting = false;
  33238. /**
  33239. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33240. */
  33241. _this.invertNormalMapX = false;
  33242. /**
  33243. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33244. */
  33245. _this.invertNormalMapY = false;
  33246. /**
  33247. * Emissivie color used to self-illuminate the model.
  33248. */
  33249. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33250. /**
  33251. * Occlusion Channel Strenght.
  33252. */
  33253. _this.occlusionStrength = 1.0;
  33254. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33255. _this._useAmbientInGrayScale = true;
  33256. return _this;
  33257. }
  33258. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  33259. /**
  33260. * Gets the current transparency mode.
  33261. */
  33262. get: function () {
  33263. return this._transparencyMode;
  33264. },
  33265. /**
  33266. * Sets the transparency mode of the material.
  33267. */
  33268. set: function (value) {
  33269. if (this._transparencyMode === value) {
  33270. return;
  33271. }
  33272. this._transparencyMode = value;
  33273. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  33274. this._forceAlphaTest = true;
  33275. }
  33276. else {
  33277. this._forceAlphaTest = false;
  33278. }
  33279. this._markAllSubMeshesAsTexturesDirty();
  33280. },
  33281. enumerable: true,
  33282. configurable: true
  33283. });
  33284. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  33285. /**
  33286. * Gets the current double sided mode.
  33287. */
  33288. get: function () {
  33289. return this._twoSidedLighting;
  33290. },
  33291. /**
  33292. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33293. */
  33294. set: function (value) {
  33295. if (this._twoSidedLighting === value) {
  33296. return;
  33297. }
  33298. this._twoSidedLighting = value;
  33299. this.backFaceCulling = !value;
  33300. this._markAllSubMeshesAsTexturesDirty();
  33301. },
  33302. enumerable: true,
  33303. configurable: true
  33304. });
  33305. /**
  33306. * Specifies wether or not the alpha value of the albedo texture should be used.
  33307. */
  33308. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  33309. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  33310. };
  33311. /**
  33312. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  33313. */
  33314. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  33315. if (this._linkRefractionWithTransparency) {
  33316. return false;
  33317. }
  33318. return (this.alpha < 1.0) ||
  33319. (this._shouldUseAlphaFromAlbedoTexture() &&
  33320. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  33321. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  33322. };
  33323. /**
  33324. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  33325. */
  33326. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  33327. if (this._linkRefractionWithTransparency) {
  33328. return false;
  33329. }
  33330. return this._shouldUseAlphaFromAlbedoTexture() &&
  33331. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  33332. };
  33333. /**
  33334. * Return the active textures of the material.
  33335. */
  33336. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  33337. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33338. if (this.environmentTexture) {
  33339. activeTextures.push(this.environmentTexture);
  33340. }
  33341. if (this.normalTexture) {
  33342. activeTextures.push(this.normalTexture);
  33343. }
  33344. if (this.emissiveTexture) {
  33345. activeTextures.push(this.emissiveTexture);
  33346. }
  33347. if (this.occlusionTexture) {
  33348. activeTextures.push(this.occlusionTexture);
  33349. }
  33350. return activeTextures;
  33351. };
  33352. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  33353. return "PBRBaseSimpleMaterial";
  33354. };
  33355. __decorate([
  33356. BABYLON.serialize(),
  33357. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33358. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  33359. __decorate([
  33360. BABYLON.serialize(),
  33361. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33362. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  33363. __decorate([
  33364. BABYLON.serializeAsTexture(),
  33365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  33366. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  33367. __decorate([
  33368. BABYLON.serialize(),
  33369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33370. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  33371. __decorate([
  33372. BABYLON.serialize(),
  33373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33374. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  33375. __decorate([
  33376. BABYLON.serializeAsTexture(),
  33377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  33378. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  33379. __decorate([
  33380. BABYLON.serializeAsColor3("emissive"),
  33381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33382. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  33383. __decorate([
  33384. BABYLON.serializeAsTexture(),
  33385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33386. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  33387. __decorate([
  33388. BABYLON.serialize(),
  33389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  33390. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  33391. __decorate([
  33392. BABYLON.serializeAsTexture(),
  33393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  33394. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  33395. __decorate([
  33396. BABYLON.serialize(),
  33397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  33398. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  33399. __decorate([
  33400. BABYLON.serialize()
  33401. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  33402. __decorate([
  33403. BABYLON.serialize()
  33404. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  33405. return PBRBaseSimpleMaterial;
  33406. }(BABYLON.PBRBaseMaterial));
  33407. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  33408. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33409. })(BABYLON || (BABYLON = {}));
  33410. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  33411. var BABYLON;
  33412. (function (BABYLON) {
  33413. /**
  33414. * The Physically based material of BJS.
  33415. *
  33416. * This offers the main features of a standard PBR material.
  33417. * For more information, please refer to the documentation :
  33418. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33419. */
  33420. var PBRMaterial = (function (_super) {
  33421. __extends(PBRMaterial, _super);
  33422. /**
  33423. * Instantiates a new PBRMaterial instance.
  33424. *
  33425. * @param name The material name
  33426. * @param scene The scene the material will be use in.
  33427. */
  33428. function PBRMaterial(name, scene) {
  33429. var _this = _super.call(this, name, scene) || this;
  33430. /**
  33431. * Intensity of the direct lights e.g. the four lights available in your scene.
  33432. * This impacts both the direct diffuse and specular highlights.
  33433. */
  33434. _this.directIntensity = 1.0;
  33435. /**
  33436. * Intensity of the emissive part of the material.
  33437. * This helps controlling the emissive effect without modifying the emissive color.
  33438. */
  33439. _this.emissiveIntensity = 1.0;
  33440. /**
  33441. * Intensity of the environment e.g. how much the environment will light the object
  33442. * either through harmonics for rough material or through the refelction for shiny ones.
  33443. */
  33444. _this.environmentIntensity = 1.0;
  33445. /**
  33446. * This is a special control allowing the reduction of the specular highlights coming from the
  33447. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33448. */
  33449. _this.specularIntensity = 1.0;
  33450. /**
  33451. * Debug Control allowing disabling the bump map on this material.
  33452. */
  33453. _this.disableBumpMap = false;
  33454. /**
  33455. * AKA Occlusion Texture Intensity in other nomenclature.
  33456. */
  33457. _this.ambientTextureStrength = 1.0;
  33458. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33459. /**
  33460. * AKA Diffuse Color in other nomenclature.
  33461. */
  33462. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  33463. /**
  33464. * AKA Specular Color in other nomenclature.
  33465. */
  33466. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33467. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  33468. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33469. /**
  33470. * AKA Glossiness in other nomenclature.
  33471. */
  33472. _this.microSurface = 1.0;
  33473. /**
  33474. * source material index of refraction (IOR)' / 'destination material IOR.
  33475. */
  33476. _this.indexOfRefraction = 0.66;
  33477. /**
  33478. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33479. */
  33480. _this.invertRefractionY = false;
  33481. /**
  33482. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33483. * Materials half opaque for instance using refraction could benefit from this control.
  33484. */
  33485. _this.linkRefractionWithTransparency = false;
  33486. _this.useLightmapAsShadowmap = false;
  33487. /**
  33488. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33489. */
  33490. _this.useAlphaFromAlbedoTexture = false;
  33491. /**
  33492. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33493. */
  33494. _this.forceAlphaTest = false;
  33495. /**
  33496. * Defines the alpha limits in alpha test mode.
  33497. */
  33498. _this.alphaCutOff = 0.4;
  33499. /**
  33500. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33501. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33502. */
  33503. _this.useSpecularOverAlpha = true;
  33504. /**
  33505. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33506. */
  33507. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  33508. /**
  33509. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33510. */
  33511. _this.useRoughnessFromMetallicTextureAlpha = true;
  33512. /**
  33513. * Specifies if the metallic texture contains the roughness information in its green channel.
  33514. */
  33515. _this.useRoughnessFromMetallicTextureGreen = false;
  33516. /**
  33517. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33518. */
  33519. _this.useMetallnessFromMetallicTextureBlue = false;
  33520. /**
  33521. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33522. */
  33523. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  33524. /**
  33525. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33526. */
  33527. _this.useAmbientInGrayScale = false;
  33528. /**
  33529. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33530. * The material will try to infer what glossiness each pixel should be.
  33531. */
  33532. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  33533. /**
  33534. * BJS is using an harcoded light falloff based on a manually sets up range.
  33535. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33536. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33537. */
  33538. _this.usePhysicalLightFalloff = true;
  33539. /**
  33540. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33541. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33542. */
  33543. _this.useRadianceOverAlpha = true;
  33544. /**
  33545. * Allows using the bump map in parallax mode.
  33546. */
  33547. _this.useParallax = false;
  33548. /**
  33549. * Allows using the bump map in parallax occlusion mode.
  33550. */
  33551. _this.useParallaxOcclusion = false;
  33552. /**
  33553. * Controls the scale bias of the parallax mode.
  33554. */
  33555. _this.parallaxScaleBias = 0.05;
  33556. /**
  33557. * If sets to true, disables all the lights affecting the material.
  33558. */
  33559. _this.disableLighting = false;
  33560. /**
  33561. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33562. */
  33563. _this.forceIrradianceInFragment = false;
  33564. /**
  33565. * Number of Simultaneous lights allowed on the material.
  33566. */
  33567. _this.maxSimultaneousLights = 4;
  33568. /**
  33569. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33570. */
  33571. _this.invertNormalMapX = false;
  33572. /**
  33573. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33574. */
  33575. _this.invertNormalMapY = false;
  33576. /**
  33577. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33578. */
  33579. _this.twoSidedLighting = false;
  33580. /**
  33581. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33582. * in your scene composition.
  33583. */
  33584. _this.preMultiplyAlpha = false;
  33585. /**
  33586. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33587. * And/Or occlude the blended part.
  33588. */
  33589. _this.useAlphaFresnel = false;
  33590. /**
  33591. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33592. * And/Or occlude the blended part.
  33593. */
  33594. _this.environmentBRDFTexture = null;
  33595. /**
  33596. * Force normal to face away from face.
  33597. * (Temporary internal fix to remove before 3.1)
  33598. */
  33599. _this.forceNormalForward = false;
  33600. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33601. return _this;
  33602. }
  33603. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  33604. /**
  33605. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  33606. */
  33607. get: function () {
  33608. return this._PBRMATERIAL_OPAQUE;
  33609. },
  33610. enumerable: true,
  33611. configurable: true
  33612. });
  33613. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  33614. /**
  33615. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  33616. */
  33617. get: function () {
  33618. return this._PBRMATERIAL_ALPHATEST;
  33619. },
  33620. enumerable: true,
  33621. configurable: true
  33622. });
  33623. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  33624. /**
  33625. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33626. */
  33627. get: function () {
  33628. return this._PBRMATERIAL_ALPHABLEND;
  33629. },
  33630. enumerable: true,
  33631. configurable: true
  33632. });
  33633. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  33634. /**
  33635. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33636. * They are also discarded below the alpha cutoff threshold to improve performances.
  33637. */
  33638. get: function () {
  33639. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  33640. },
  33641. enumerable: true,
  33642. configurable: true
  33643. });
  33644. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  33645. /**
  33646. * Gets the image processing configuration used either in this material.
  33647. */
  33648. get: function () {
  33649. return this._imageProcessingConfiguration;
  33650. },
  33651. /**
  33652. * Sets the Default image processing configuration used either in the this material.
  33653. *
  33654. * If sets to null, the scene one is in use.
  33655. */
  33656. set: function (value) {
  33657. this._attachImageProcessingConfiguration(value);
  33658. // Ensure the effect will be rebuilt.
  33659. this._markAllSubMeshesAsTexturesDirty();
  33660. },
  33661. enumerable: true,
  33662. configurable: true
  33663. });
  33664. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  33665. /**
  33666. * Gets wether the color curves effect is enabled.
  33667. */
  33668. get: function () {
  33669. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33670. },
  33671. /**
  33672. * Sets wether the color curves effect is enabled.
  33673. */
  33674. set: function (value) {
  33675. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33676. },
  33677. enumerable: true,
  33678. configurable: true
  33679. });
  33680. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33681. /**
  33682. * Gets wether the color grading effect is enabled.
  33683. */
  33684. get: function () {
  33685. return this.imageProcessingConfiguration.colorGradingEnabled;
  33686. },
  33687. /**
  33688. * Gets wether the color grading effect is enabled.
  33689. */
  33690. set: function (value) {
  33691. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33692. },
  33693. enumerable: true,
  33694. configurable: true
  33695. });
  33696. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33697. /**
  33698. * Gets wether tonemapping is enabled or not.
  33699. */
  33700. get: function () {
  33701. return this._imageProcessingConfiguration.toneMappingEnabled;
  33702. },
  33703. /**
  33704. * Sets wether tonemapping is enabled or not
  33705. */
  33706. set: function (value) {
  33707. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33708. },
  33709. enumerable: true,
  33710. configurable: true
  33711. });
  33712. ;
  33713. ;
  33714. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33715. /**
  33716. * The camera exposure used on this material.
  33717. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33718. * This corresponds to a photographic exposure.
  33719. */
  33720. get: function () {
  33721. return this._imageProcessingConfiguration.exposure;
  33722. },
  33723. /**
  33724. * The camera exposure used on this material.
  33725. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33726. * This corresponds to a photographic exposure.
  33727. */
  33728. set: function (value) {
  33729. this._imageProcessingConfiguration.exposure = value;
  33730. },
  33731. enumerable: true,
  33732. configurable: true
  33733. });
  33734. ;
  33735. ;
  33736. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33737. /**
  33738. * Gets The camera contrast used on this material.
  33739. */
  33740. get: function () {
  33741. return this._imageProcessingConfiguration.contrast;
  33742. },
  33743. /**
  33744. * Sets The camera contrast used on this material.
  33745. */
  33746. set: function (value) {
  33747. this._imageProcessingConfiguration.contrast = value;
  33748. },
  33749. enumerable: true,
  33750. configurable: true
  33751. });
  33752. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33753. /**
  33754. * Gets the Color Grading 2D Lookup Texture.
  33755. */
  33756. get: function () {
  33757. return this._imageProcessingConfiguration.colorGradingTexture;
  33758. },
  33759. /**
  33760. * Sets the Color Grading 2D Lookup Texture.
  33761. */
  33762. set: function (value) {
  33763. this._imageProcessingConfiguration.colorGradingTexture = value;
  33764. },
  33765. enumerable: true,
  33766. configurable: true
  33767. });
  33768. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33769. /**
  33770. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33771. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33772. * 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;
  33773. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33774. */
  33775. get: function () {
  33776. return this._imageProcessingConfiguration.colorCurves;
  33777. },
  33778. /**
  33779. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33780. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33781. * 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;
  33782. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33783. */
  33784. set: function (value) {
  33785. this._imageProcessingConfiguration.colorCurves = value;
  33786. },
  33787. enumerable: true,
  33788. configurable: true
  33789. });
  33790. PBRMaterial.prototype.getClassName = function () {
  33791. return "PBRMaterial";
  33792. };
  33793. PBRMaterial.prototype.getActiveTextures = function () {
  33794. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33795. if (this._albedoTexture) {
  33796. activeTextures.push(this._albedoTexture);
  33797. }
  33798. if (this._ambientTexture) {
  33799. activeTextures.push(this._ambientTexture);
  33800. }
  33801. if (this._opacityTexture) {
  33802. activeTextures.push(this._opacityTexture);
  33803. }
  33804. if (this._reflectionTexture) {
  33805. activeTextures.push(this._reflectionTexture);
  33806. }
  33807. if (this._emissiveTexture) {
  33808. activeTextures.push(this._emissiveTexture);
  33809. }
  33810. if (this._reflectivityTexture) {
  33811. activeTextures.push(this._reflectivityTexture);
  33812. }
  33813. if (this._metallicTexture) {
  33814. activeTextures.push(this._metallicTexture);
  33815. }
  33816. if (this._microSurfaceTexture) {
  33817. activeTextures.push(this._microSurfaceTexture);
  33818. }
  33819. if (this._bumpTexture) {
  33820. activeTextures.push(this._bumpTexture);
  33821. }
  33822. if (this._lightmapTexture) {
  33823. activeTextures.push(this._lightmapTexture);
  33824. }
  33825. if (this._refractionTexture) {
  33826. activeTextures.push(this._refractionTexture);
  33827. }
  33828. return activeTextures;
  33829. };
  33830. PBRMaterial.prototype.hasTexture = function (texture) {
  33831. if (_super.prototype.hasTexture.call(this, texture)) {
  33832. return true;
  33833. }
  33834. if (this._albedoTexture === texture) {
  33835. return true;
  33836. }
  33837. if (this._ambientTexture === texture) {
  33838. return true;
  33839. }
  33840. if (this._opacityTexture === texture) {
  33841. return true;
  33842. }
  33843. if (this._reflectionTexture === texture) {
  33844. return true;
  33845. }
  33846. if (this._reflectivityTexture === texture) {
  33847. return true;
  33848. }
  33849. if (this._metallicTexture === texture) {
  33850. return true;
  33851. }
  33852. if (this._microSurfaceTexture === texture) {
  33853. return true;
  33854. }
  33855. if (this._bumpTexture === texture) {
  33856. return true;
  33857. }
  33858. if (this._lightmapTexture === texture) {
  33859. return true;
  33860. }
  33861. if (this._refractionTexture === texture) {
  33862. return true;
  33863. }
  33864. return false;
  33865. };
  33866. PBRMaterial.prototype.clone = function (name) {
  33867. var _this = this;
  33868. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33869. clone.id = name;
  33870. clone.name = name;
  33871. return clone;
  33872. };
  33873. PBRMaterial.prototype.serialize = function () {
  33874. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33875. serializationObject.customType = "BABYLON.PBRMaterial";
  33876. return serializationObject;
  33877. };
  33878. // Statics
  33879. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33880. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33881. };
  33882. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33883. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33884. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33885. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33886. __decorate([
  33887. BABYLON.serialize(),
  33888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33889. ], PBRMaterial.prototype, "directIntensity", void 0);
  33890. __decorate([
  33891. BABYLON.serialize(),
  33892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33893. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33894. __decorate([
  33895. BABYLON.serialize(),
  33896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33897. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33898. __decorate([
  33899. BABYLON.serialize(),
  33900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33901. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33902. __decorate([
  33903. BABYLON.serialize(),
  33904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33905. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33906. __decorate([
  33907. BABYLON.serializeAsTexture(),
  33908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33909. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33910. __decorate([
  33911. BABYLON.serializeAsTexture(),
  33912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33913. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33914. __decorate([
  33915. BABYLON.serialize(),
  33916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33917. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33918. __decorate([
  33919. BABYLON.serializeAsTexture(),
  33920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33921. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33922. __decorate([
  33923. BABYLON.serializeAsTexture(),
  33924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33925. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33926. __decorate([
  33927. BABYLON.serializeAsTexture(),
  33928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33929. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33930. __decorate([
  33931. BABYLON.serializeAsTexture(),
  33932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33933. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33934. __decorate([
  33935. BABYLON.serializeAsTexture(),
  33936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33937. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33938. __decorate([
  33939. BABYLON.serialize(),
  33940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33941. ], PBRMaterial.prototype, "metallic", void 0);
  33942. __decorate([
  33943. BABYLON.serialize(),
  33944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33945. ], PBRMaterial.prototype, "roughness", void 0);
  33946. __decorate([
  33947. BABYLON.serializeAsTexture(),
  33948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33949. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33950. __decorate([
  33951. BABYLON.serializeAsTexture(),
  33952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33953. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33954. __decorate([
  33955. BABYLON.serializeAsTexture(),
  33956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33957. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33958. __decorate([
  33959. BABYLON.serializeAsTexture(),
  33960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33961. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33962. __decorate([
  33963. BABYLON.serializeAsColor3("ambient"),
  33964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33965. ], PBRMaterial.prototype, "ambientColor", void 0);
  33966. __decorate([
  33967. BABYLON.serializeAsColor3("albedo"),
  33968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33969. ], PBRMaterial.prototype, "albedoColor", void 0);
  33970. __decorate([
  33971. BABYLON.serializeAsColor3("reflectivity"),
  33972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33973. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33974. __decorate([
  33975. BABYLON.serializeAsColor3("reflection"),
  33976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33977. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33978. __decorate([
  33979. BABYLON.serializeAsColor3("emissive"),
  33980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33981. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33982. __decorate([
  33983. BABYLON.serialize(),
  33984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33985. ], PBRMaterial.prototype, "microSurface", void 0);
  33986. __decorate([
  33987. BABYLON.serialize(),
  33988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33989. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33990. __decorate([
  33991. BABYLON.serialize(),
  33992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33993. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33994. __decorate([
  33995. BABYLON.serialize(),
  33996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33997. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33998. __decorate([
  33999. BABYLON.serialize(),
  34000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34001. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34002. __decorate([
  34003. BABYLON.serialize(),
  34004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34005. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  34006. __decorate([
  34007. BABYLON.serialize(),
  34008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34009. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  34010. __decorate([
  34011. BABYLON.serialize(),
  34012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34013. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  34014. __decorate([
  34015. BABYLON.serialize(),
  34016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34017. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  34018. __decorate([
  34019. BABYLON.serialize(),
  34020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34021. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  34022. __decorate([
  34023. BABYLON.serialize(),
  34024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34025. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  34026. __decorate([
  34027. BABYLON.serialize(),
  34028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34029. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  34030. __decorate([
  34031. BABYLON.serialize(),
  34032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34033. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  34034. __decorate([
  34035. BABYLON.serialize(),
  34036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34037. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  34038. __decorate([
  34039. BABYLON.serialize(),
  34040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34041. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  34042. __decorate([
  34043. BABYLON.serialize(),
  34044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34045. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  34046. __decorate([
  34047. BABYLON.serialize(),
  34048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34049. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  34050. __decorate([
  34051. BABYLON.serialize(),
  34052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34053. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  34054. __decorate([
  34055. BABYLON.serialize(),
  34056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34057. ], PBRMaterial.prototype, "useParallax", void 0);
  34058. __decorate([
  34059. BABYLON.serialize(),
  34060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34061. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  34062. __decorate([
  34063. BABYLON.serialize(),
  34064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34065. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  34066. __decorate([
  34067. BABYLON.serialize(),
  34068. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34069. ], PBRMaterial.prototype, "disableLighting", void 0);
  34070. __decorate([
  34071. BABYLON.serialize(),
  34072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34073. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  34074. __decorate([
  34075. BABYLON.serialize(),
  34076. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34077. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  34078. __decorate([
  34079. BABYLON.serialize(),
  34080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34081. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  34082. __decorate([
  34083. BABYLON.serialize(),
  34084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34085. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  34086. __decorate([
  34087. BABYLON.serialize(),
  34088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34089. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  34090. __decorate([
  34091. BABYLON.serialize(),
  34092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34093. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  34094. __decorate([
  34095. BABYLON.serialize(),
  34096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34097. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  34098. __decorate([
  34099. BABYLON.serializeAsTexture(),
  34100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34101. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  34102. __decorate([
  34103. BABYLON.serialize(),
  34104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34105. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  34106. return PBRMaterial;
  34107. }(BABYLON.PBRBaseMaterial));
  34108. BABYLON.PBRMaterial = PBRMaterial;
  34109. })(BABYLON || (BABYLON = {}));
  34110. //# sourceMappingURL=babylon.pbrMaterial.js.map
  34111. var BABYLON;
  34112. (function (BABYLON) {
  34113. /**
  34114. * The PBR material of BJS following the metal roughness convention.
  34115. *
  34116. * This fits to the PBR convention in the GLTF definition:
  34117. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  34118. */
  34119. var PBRMetallicRoughnessMaterial = (function (_super) {
  34120. __extends(PBRMetallicRoughnessMaterial, _super);
  34121. /**
  34122. * Instantiates a new PBRMetalRoughnessMaterial instance.
  34123. *
  34124. * @param name The material name
  34125. * @param scene The scene the material will be use in.
  34126. */
  34127. function PBRMetallicRoughnessMaterial(name, scene) {
  34128. var _this = _super.call(this, name, scene) || this;
  34129. _this._useRoughnessFromMetallicTextureAlpha = false;
  34130. _this._useRoughnessFromMetallicTextureGreen = true;
  34131. _this._useMetallnessFromMetallicTextureBlue = true;
  34132. return _this;
  34133. }
  34134. /**
  34135. * Return the currrent class name of the material.
  34136. */
  34137. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  34138. return "PBRMetallicRoughnessMaterial";
  34139. };
  34140. /**
  34141. * Return the active textures of the material.
  34142. */
  34143. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  34144. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34145. if (this.baseTexture) {
  34146. activeTextures.push(this.baseTexture);
  34147. }
  34148. if (this.metallicRoughnessTexture) {
  34149. activeTextures.push(this.metallicRoughnessTexture);
  34150. }
  34151. return activeTextures;
  34152. };
  34153. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  34154. if (_super.prototype.hasTexture.call(this, texture)) {
  34155. return true;
  34156. }
  34157. if (this.baseTexture === texture) {
  34158. return true;
  34159. }
  34160. if (this.metallicRoughnessTexture === texture) {
  34161. return true;
  34162. }
  34163. return false;
  34164. };
  34165. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  34166. var _this = this;
  34167. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  34168. clone.id = name;
  34169. clone.name = name;
  34170. return clone;
  34171. };
  34172. /**
  34173. * Serialize the material to a parsable JSON object.
  34174. */
  34175. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  34176. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34177. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  34178. return serializationObject;
  34179. };
  34180. /**
  34181. * Parses a JSON object correponding to the serialize function.
  34182. */
  34183. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  34184. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  34185. };
  34186. __decorate([
  34187. BABYLON.serializeAsColor3(),
  34188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  34189. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  34190. __decorate([
  34191. BABYLON.serializeAsTexture(),
  34192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  34193. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  34194. __decorate([
  34195. BABYLON.serialize(),
  34196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34197. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  34198. __decorate([
  34199. BABYLON.serialize(),
  34200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34201. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  34202. __decorate([
  34203. BABYLON.serializeAsTexture(),
  34204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  34205. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  34206. return PBRMetallicRoughnessMaterial;
  34207. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  34208. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  34209. })(BABYLON || (BABYLON = {}));
  34210. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  34211. var BABYLON;
  34212. (function (BABYLON) {
  34213. /**
  34214. * The PBR material of BJS following the specular glossiness convention.
  34215. *
  34216. * This fits to the PBR convention in the GLTF definition:
  34217. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  34218. */
  34219. var PBRSpecularGlossinessMaterial = (function (_super) {
  34220. __extends(PBRSpecularGlossinessMaterial, _super);
  34221. /**
  34222. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  34223. *
  34224. * @param name The material name
  34225. * @param scene The scene the material will be use in.
  34226. */
  34227. function PBRSpecularGlossinessMaterial(name, scene) {
  34228. var _this = _super.call(this, name, scene) || this;
  34229. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  34230. return _this;
  34231. }
  34232. /**
  34233. * Return the currrent class name of the material.
  34234. */
  34235. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  34236. return "PBRSpecularGlossinessMaterial";
  34237. };
  34238. /**
  34239. * Return the active textures of the material.
  34240. */
  34241. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  34242. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34243. if (this.diffuseTexture) {
  34244. activeTextures.push(this.diffuseTexture);
  34245. }
  34246. if (this.specularGlossinessTexture) {
  34247. activeTextures.push(this.specularGlossinessTexture);
  34248. }
  34249. return activeTextures;
  34250. };
  34251. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  34252. if (_super.prototype.hasTexture.call(this, texture)) {
  34253. return true;
  34254. }
  34255. if (this.diffuseTexture === texture) {
  34256. return true;
  34257. }
  34258. if (this.specularGlossinessTexture === texture) {
  34259. return true;
  34260. }
  34261. return false;
  34262. };
  34263. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  34264. var _this = this;
  34265. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  34266. clone.id = name;
  34267. clone.name = name;
  34268. return clone;
  34269. };
  34270. /**
  34271. * Serialize the material to a parsable JSON object.
  34272. */
  34273. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  34274. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34275. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  34276. return serializationObject;
  34277. };
  34278. /**
  34279. * Parses a JSON object correponding to the serialize function.
  34280. */
  34281. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  34282. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  34283. };
  34284. __decorate([
  34285. BABYLON.serializeAsColor3("diffuse"),
  34286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  34287. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  34288. __decorate([
  34289. BABYLON.serializeAsTexture(),
  34290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  34291. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  34292. __decorate([
  34293. BABYLON.serializeAsColor3("specular"),
  34294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  34295. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  34296. __decorate([
  34297. BABYLON.serialize(),
  34298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  34299. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  34300. __decorate([
  34301. BABYLON.serializeAsTexture(),
  34302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  34303. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  34304. return PBRSpecularGlossinessMaterial;
  34305. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  34306. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  34307. })(BABYLON || (BABYLON = {}));
  34308. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  34309. var BABYLON;
  34310. (function (BABYLON) {
  34311. BABYLON.CameraInputTypes = {};
  34312. var CameraInputsManager = (function () {
  34313. function CameraInputsManager(camera) {
  34314. this.attached = {};
  34315. this.camera = camera;
  34316. this.checkInputs = function () { };
  34317. }
  34318. CameraInputsManager.prototype.add = function (input) {
  34319. var type = input.getSimpleName();
  34320. if (this.attached[type]) {
  34321. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  34322. return;
  34323. }
  34324. this.attached[type] = input;
  34325. input.camera = this.camera;
  34326. //for checkInputs, we are dynamically creating a function
  34327. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  34328. if (input.checkInputs) {
  34329. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34330. }
  34331. if (this.attachedElement) {
  34332. input.attachControl(this.attachedElement);
  34333. }
  34334. };
  34335. CameraInputsManager.prototype.remove = function (inputToRemove) {
  34336. for (var cam in this.attached) {
  34337. var input = this.attached[cam];
  34338. if (input === inputToRemove) {
  34339. input.detachControl(this.attachedElement);
  34340. input.camera = null;
  34341. delete this.attached[cam];
  34342. this.rebuildInputCheck();
  34343. }
  34344. }
  34345. };
  34346. CameraInputsManager.prototype.removeByType = function (inputType) {
  34347. for (var cam in this.attached) {
  34348. var input = this.attached[cam];
  34349. if (input.getClassName() === inputType) {
  34350. input.detachControl(this.attachedElement);
  34351. input.camera = null;
  34352. delete this.attached[cam];
  34353. this.rebuildInputCheck();
  34354. }
  34355. }
  34356. };
  34357. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  34358. var current = this.checkInputs;
  34359. return function () {
  34360. current();
  34361. fn();
  34362. };
  34363. };
  34364. CameraInputsManager.prototype.attachInput = function (input) {
  34365. input.attachControl(this.attachedElement, this.noPreventDefault);
  34366. };
  34367. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  34368. if (this.attachedElement) {
  34369. return;
  34370. }
  34371. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  34372. this.attachedElement = element;
  34373. this.noPreventDefault = noPreventDefault;
  34374. for (var cam in this.attached) {
  34375. var input = this.attached[cam];
  34376. this.attached[cam].attachControl(element, noPreventDefault);
  34377. }
  34378. };
  34379. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  34380. if (disconnect === void 0) { disconnect = false; }
  34381. if (this.attachedElement !== element) {
  34382. return;
  34383. }
  34384. for (var cam in this.attached) {
  34385. var input = this.attached[cam];
  34386. this.attached[cam].detachControl(element);
  34387. if (disconnect) {
  34388. this.attached[cam].camera = null;
  34389. }
  34390. }
  34391. this.attachedElement = null;
  34392. };
  34393. CameraInputsManager.prototype.rebuildInputCheck = function () {
  34394. this.checkInputs = function () { };
  34395. for (var cam in this.attached) {
  34396. var input = this.attached[cam];
  34397. if (input.checkInputs) {
  34398. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34399. }
  34400. }
  34401. };
  34402. CameraInputsManager.prototype.clear = function () {
  34403. if (this.attachedElement) {
  34404. this.detachElement(this.attachedElement, true);
  34405. }
  34406. this.attached = {};
  34407. this.attachedElement = null;
  34408. this.checkInputs = function () { };
  34409. };
  34410. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  34411. var inputs = {};
  34412. for (var cam in this.attached) {
  34413. var input = this.attached[cam];
  34414. var res = BABYLON.SerializationHelper.Serialize(input);
  34415. inputs[input.getClassName()] = res;
  34416. }
  34417. serializedCamera.inputsmgr = inputs;
  34418. };
  34419. CameraInputsManager.prototype.parse = function (parsedCamera) {
  34420. var parsedInputs = parsedCamera.inputsmgr;
  34421. if (parsedInputs) {
  34422. this.clear();
  34423. for (var n in parsedInputs) {
  34424. var construct = BABYLON.CameraInputTypes[n];
  34425. if (construct) {
  34426. var parsedinput = parsedInputs[n];
  34427. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  34428. this.add(input);
  34429. }
  34430. }
  34431. }
  34432. else {
  34433. //2016-03-08 this part is for managing backward compatibility
  34434. for (var n in this.attached) {
  34435. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  34436. if (construct) {
  34437. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  34438. this.remove(this.attached[n]);
  34439. this.add(input);
  34440. }
  34441. }
  34442. }
  34443. };
  34444. return CameraInputsManager;
  34445. }());
  34446. BABYLON.CameraInputsManager = CameraInputsManager;
  34447. })(BABYLON || (BABYLON = {}));
  34448. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  34449. var BABYLON;
  34450. (function (BABYLON) {
  34451. var FreeCameraMouseInput = (function () {
  34452. function FreeCameraMouseInput(touchEnabled) {
  34453. if (touchEnabled === void 0) { touchEnabled = true; }
  34454. this.touchEnabled = touchEnabled;
  34455. this.buttons = [0, 1, 2];
  34456. this.angularSensibility = 2000.0;
  34457. }
  34458. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  34459. var _this = this;
  34460. var engine = this.camera.getEngine();
  34461. if (!this._pointerInput) {
  34462. this._pointerInput = function (p, s) {
  34463. var evt = p.event;
  34464. if (engine.isInVRExclusivePointerMode) {
  34465. return;
  34466. }
  34467. if (!_this.touchEnabled && evt.pointerType === "touch") {
  34468. return;
  34469. }
  34470. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34471. return;
  34472. }
  34473. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34474. try {
  34475. evt.srcElement.setPointerCapture(evt.pointerId);
  34476. }
  34477. catch (e) {
  34478. //Nothing to do with the error. Execution will continue.
  34479. }
  34480. _this.previousPosition = {
  34481. x: evt.clientX,
  34482. y: evt.clientY
  34483. };
  34484. if (!noPreventDefault) {
  34485. evt.preventDefault();
  34486. element.focus();
  34487. }
  34488. }
  34489. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34490. try {
  34491. evt.srcElement.releasePointerCapture(evt.pointerId);
  34492. }
  34493. catch (e) {
  34494. //Nothing to do with the error.
  34495. }
  34496. _this.previousPosition = null;
  34497. if (!noPreventDefault) {
  34498. evt.preventDefault();
  34499. }
  34500. }
  34501. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34502. if (!_this.previousPosition || engine.isPointerLock) {
  34503. return;
  34504. }
  34505. var offsetX = evt.clientX - _this.previousPosition.x;
  34506. var offsetY = evt.clientY - _this.previousPosition.y;
  34507. if (_this.camera.getScene().useRightHandedSystem) {
  34508. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34509. }
  34510. else {
  34511. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34512. }
  34513. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34514. _this.previousPosition = {
  34515. x: evt.clientX,
  34516. y: evt.clientY
  34517. };
  34518. if (!noPreventDefault) {
  34519. evt.preventDefault();
  34520. }
  34521. }
  34522. };
  34523. }
  34524. this._onMouseMove = function (evt) {
  34525. if (!engine.isPointerLock) {
  34526. return;
  34527. }
  34528. if (engine.isInVRExclusivePointerMode) {
  34529. return;
  34530. }
  34531. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34532. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34533. if (_this.camera.getScene().useRightHandedSystem) {
  34534. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34535. }
  34536. else {
  34537. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34538. }
  34539. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34540. _this.previousPosition = null;
  34541. if (!noPreventDefault) {
  34542. evt.preventDefault();
  34543. }
  34544. };
  34545. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34546. element.addEventListener("mousemove", this._onMouseMove, false);
  34547. };
  34548. FreeCameraMouseInput.prototype.detachControl = function (element) {
  34549. if (this._observer && element) {
  34550. this.camera.getScene().onPointerObservable.remove(this._observer);
  34551. element.removeEventListener("mousemove", this._onMouseMove);
  34552. this._observer = null;
  34553. this._onMouseMove = null;
  34554. this.previousPosition = null;
  34555. }
  34556. };
  34557. FreeCameraMouseInput.prototype.getClassName = function () {
  34558. return "FreeCameraMouseInput";
  34559. };
  34560. FreeCameraMouseInput.prototype.getSimpleName = function () {
  34561. return "mouse";
  34562. };
  34563. __decorate([
  34564. BABYLON.serialize()
  34565. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  34566. __decorate([
  34567. BABYLON.serialize()
  34568. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  34569. return FreeCameraMouseInput;
  34570. }());
  34571. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  34572. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  34573. })(BABYLON || (BABYLON = {}));
  34574. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  34575. var BABYLON;
  34576. (function (BABYLON) {
  34577. var FreeCameraKeyboardMoveInput = (function () {
  34578. function FreeCameraKeyboardMoveInput() {
  34579. this._keys = [];
  34580. this.keysUp = [38];
  34581. this.keysDown = [40];
  34582. this.keysLeft = [37];
  34583. this.keysRight = [39];
  34584. }
  34585. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34586. var _this = this;
  34587. if (this._onCanvasBlurObserver) {
  34588. return;
  34589. }
  34590. this._scene = this.camera.getScene();
  34591. this._engine = this._scene.getEngine();
  34592. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  34593. _this._keys = [];
  34594. });
  34595. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  34596. var evt = info.event;
  34597. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  34598. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34599. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34600. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34601. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34602. var index = _this._keys.indexOf(evt.keyCode);
  34603. if (index === -1) {
  34604. _this._keys.push(evt.keyCode);
  34605. }
  34606. if (!noPreventDefault) {
  34607. evt.preventDefault();
  34608. }
  34609. }
  34610. }
  34611. else {
  34612. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34613. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34614. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34615. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34616. var index = _this._keys.indexOf(evt.keyCode);
  34617. if (index >= 0) {
  34618. _this._keys.splice(index, 1);
  34619. }
  34620. if (!noPreventDefault) {
  34621. evt.preventDefault();
  34622. }
  34623. }
  34624. }
  34625. });
  34626. };
  34627. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34628. if (this._scene) {
  34629. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  34630. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  34631. this._onKeyboardObserver = null;
  34632. this._onCanvasBlurObserver = null;
  34633. }
  34634. this._keys = [];
  34635. };
  34636. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34637. if (this._onKeyboardObserver) {
  34638. var camera = this.camera;
  34639. // Keyboard
  34640. for (var index = 0; index < this._keys.length; index++) {
  34641. var keyCode = this._keys[index];
  34642. var speed = camera._computeLocalCameraSpeed();
  34643. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34644. camera._localDirection.copyFromFloats(-speed, 0, 0);
  34645. }
  34646. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34647. camera._localDirection.copyFromFloats(0, 0, speed);
  34648. }
  34649. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34650. camera._localDirection.copyFromFloats(speed, 0, 0);
  34651. }
  34652. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34653. camera._localDirection.copyFromFloats(0, 0, -speed);
  34654. }
  34655. if (camera.getScene().useRightHandedSystem) {
  34656. camera._localDirection.z *= -1;
  34657. }
  34658. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  34659. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  34660. camera.cameraDirection.addInPlace(camera._transformedDirection);
  34661. }
  34662. }
  34663. };
  34664. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  34665. return "FreeCameraKeyboardMoveInput";
  34666. };
  34667. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  34668. this._keys = [];
  34669. };
  34670. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34671. return "keyboard";
  34672. };
  34673. __decorate([
  34674. BABYLON.serialize()
  34675. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34676. __decorate([
  34677. BABYLON.serialize()
  34678. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34679. __decorate([
  34680. BABYLON.serialize()
  34681. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34682. __decorate([
  34683. BABYLON.serialize()
  34684. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34685. return FreeCameraKeyboardMoveInput;
  34686. }());
  34687. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  34688. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  34689. })(BABYLON || (BABYLON = {}));
  34690. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34691. var BABYLON;
  34692. (function (BABYLON) {
  34693. var FreeCameraInputsManager = (function (_super) {
  34694. __extends(FreeCameraInputsManager, _super);
  34695. function FreeCameraInputsManager(camera) {
  34696. return _super.call(this, camera) || this;
  34697. }
  34698. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34699. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34700. return this;
  34701. };
  34702. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34703. if (touchEnabled === void 0) { touchEnabled = true; }
  34704. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34705. return this;
  34706. };
  34707. FreeCameraInputsManager.prototype.addGamepad = function () {
  34708. this.add(new BABYLON.FreeCameraGamepadInput());
  34709. return this;
  34710. };
  34711. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34712. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34713. return this;
  34714. };
  34715. FreeCameraInputsManager.prototype.addTouch = function () {
  34716. this.add(new BABYLON.FreeCameraTouchInput());
  34717. return this;
  34718. };
  34719. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34720. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34721. return this;
  34722. };
  34723. return FreeCameraInputsManager;
  34724. }(BABYLON.CameraInputsManager));
  34725. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34726. })(BABYLON || (BABYLON = {}));
  34727. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34728. /// <reference path="babylon.camera.ts" />
  34729. var BABYLON;
  34730. (function (BABYLON) {
  34731. var TargetCamera = (function (_super) {
  34732. __extends(TargetCamera, _super);
  34733. function TargetCamera(name, position, scene) {
  34734. var _this = _super.call(this, name, position, scene) || this;
  34735. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34736. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34737. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34738. _this.speed = 2.0;
  34739. _this.noRotationConstraint = false;
  34740. _this.lockedTarget = null;
  34741. _this._currentTarget = BABYLON.Vector3.Zero();
  34742. _this._viewMatrix = BABYLON.Matrix.Zero();
  34743. _this._camMatrix = BABYLON.Matrix.Zero();
  34744. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34745. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34746. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34747. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34748. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34749. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34750. _this._tempMatrix = BABYLON.Matrix.Zero();
  34751. return _this;
  34752. }
  34753. TargetCamera.prototype.getFrontPosition = function (distance) {
  34754. var direction = this.getTarget().subtract(this.position);
  34755. direction.normalize();
  34756. direction.scaleInPlace(distance);
  34757. return this.globalPosition.add(direction);
  34758. };
  34759. TargetCamera.prototype._getLockedTargetPosition = function () {
  34760. if (!this.lockedTarget) {
  34761. return null;
  34762. }
  34763. if (this.lockedTarget.absolutePosition) {
  34764. this.lockedTarget.computeWorldMatrix();
  34765. }
  34766. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34767. };
  34768. TargetCamera.prototype.storeState = function () {
  34769. this._storedPosition = this.position.clone();
  34770. this._storedRotation = this.rotation.clone();
  34771. if (this.rotationQuaternion) {
  34772. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  34773. }
  34774. return _super.prototype.storeState.call(this);
  34775. };
  34776. /**
  34777. * Restored camera state. You must call storeState() first
  34778. */
  34779. TargetCamera.prototype._restoreStateValues = function () {
  34780. if (!_super.prototype._restoreStateValues.call(this)) {
  34781. return false;
  34782. }
  34783. this.position = this._storedPosition.clone();
  34784. this.rotation = this._storedRotation.clone();
  34785. if (this.rotationQuaternion) {
  34786. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  34787. }
  34788. this.cameraDirection.copyFromFloats(0, 0, 0);
  34789. this.cameraRotation.copyFromFloats(0, 0);
  34790. return true;
  34791. };
  34792. // Cache
  34793. TargetCamera.prototype._initCache = function () {
  34794. _super.prototype._initCache.call(this);
  34795. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34796. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34797. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34798. };
  34799. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34800. if (!ignoreParentClass) {
  34801. _super.prototype._updateCache.call(this);
  34802. }
  34803. var lockedTargetPosition = this._getLockedTargetPosition();
  34804. if (!lockedTargetPosition) {
  34805. this._cache.lockedTarget = null;
  34806. }
  34807. else {
  34808. if (!this._cache.lockedTarget) {
  34809. this._cache.lockedTarget = lockedTargetPosition.clone();
  34810. }
  34811. else {
  34812. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34813. }
  34814. }
  34815. this._cache.rotation.copyFrom(this.rotation);
  34816. if (this.rotationQuaternion)
  34817. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34818. };
  34819. // Synchronized
  34820. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34821. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34822. return false;
  34823. }
  34824. var lockedTargetPosition = this._getLockedTargetPosition();
  34825. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34826. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34827. };
  34828. // Methods
  34829. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34830. var engine = this.getEngine();
  34831. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34832. };
  34833. // Target
  34834. TargetCamera.prototype.setTarget = function (target) {
  34835. this.upVector.normalize();
  34836. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34837. this._camMatrix.invert();
  34838. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34839. var vDir = target.subtract(this.position);
  34840. if (vDir.x >= 0.0) {
  34841. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34842. }
  34843. else {
  34844. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34845. }
  34846. this.rotation.z = 0;
  34847. if (isNaN(this.rotation.x)) {
  34848. this.rotation.x = 0;
  34849. }
  34850. if (isNaN(this.rotation.y)) {
  34851. this.rotation.y = 0;
  34852. }
  34853. if (isNaN(this.rotation.z)) {
  34854. this.rotation.z = 0;
  34855. }
  34856. if (this.rotationQuaternion) {
  34857. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34858. }
  34859. };
  34860. /**
  34861. * Return the current target position of the camera. This value is expressed in local space.
  34862. */
  34863. TargetCamera.prototype.getTarget = function () {
  34864. return this._currentTarget;
  34865. };
  34866. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34867. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34868. };
  34869. TargetCamera.prototype._updatePosition = function () {
  34870. if (this.parent) {
  34871. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34872. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34873. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34874. return;
  34875. }
  34876. this.position.addInPlace(this.cameraDirection);
  34877. };
  34878. TargetCamera.prototype._checkInputs = function () {
  34879. var needToMove = this._decideIfNeedsToMove();
  34880. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34881. // Move
  34882. if (needToMove) {
  34883. this._updatePosition();
  34884. }
  34885. // Rotate
  34886. if (needToRotate) {
  34887. this.rotation.x += this.cameraRotation.x;
  34888. this.rotation.y += this.cameraRotation.y;
  34889. //rotate, if quaternion is set and rotation was used
  34890. if (this.rotationQuaternion) {
  34891. var len = this.rotation.lengthSquared();
  34892. if (len) {
  34893. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34894. }
  34895. }
  34896. if (!this.noRotationConstraint) {
  34897. var limit = (Math.PI / 2) * 0.95;
  34898. if (this.rotation.x > limit)
  34899. this.rotation.x = limit;
  34900. if (this.rotation.x < -limit)
  34901. this.rotation.x = -limit;
  34902. }
  34903. }
  34904. // Inertia
  34905. if (needToMove) {
  34906. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34907. this.cameraDirection.x = 0;
  34908. }
  34909. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34910. this.cameraDirection.y = 0;
  34911. }
  34912. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34913. this.cameraDirection.z = 0;
  34914. }
  34915. this.cameraDirection.scaleInPlace(this.inertia);
  34916. }
  34917. if (needToRotate) {
  34918. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34919. this.cameraRotation.x = 0;
  34920. }
  34921. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34922. this.cameraRotation.y = 0;
  34923. }
  34924. this.cameraRotation.scaleInPlace(this.inertia);
  34925. }
  34926. _super.prototype._checkInputs.call(this);
  34927. };
  34928. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34929. if (this.rotationQuaternion) {
  34930. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34931. //update the up vector!
  34932. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34933. }
  34934. else {
  34935. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34936. }
  34937. };
  34938. TargetCamera.prototype._getViewMatrix = function () {
  34939. if (!this.lockedTarget) {
  34940. // Compute
  34941. this._updateCameraRotationMatrix();
  34942. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34943. // Computing target and final matrix
  34944. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34945. }
  34946. else {
  34947. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34948. }
  34949. if (this.getScene().useRightHandedSystem) {
  34950. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34951. }
  34952. else {
  34953. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34954. }
  34955. return this._viewMatrix;
  34956. };
  34957. /**
  34958. * @override
  34959. * Override Camera.createRigCamera
  34960. */
  34961. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34962. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34963. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34964. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34965. if (!this.rotationQuaternion) {
  34966. this.rotationQuaternion = new BABYLON.Quaternion();
  34967. }
  34968. rigCamera._cameraRigParams = {};
  34969. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34970. }
  34971. return rigCamera;
  34972. }
  34973. return null;
  34974. };
  34975. /**
  34976. * @override
  34977. * Override Camera._updateRigCameras
  34978. */
  34979. TargetCamera.prototype._updateRigCameras = function () {
  34980. var camLeft = this._rigCameras[0];
  34981. var camRight = this._rigCameras[1];
  34982. switch (this.cameraRigMode) {
  34983. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34984. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34985. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34986. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34987. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34988. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34989. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34990. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34991. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34992. camLeft.setTarget(this.getTarget());
  34993. camRight.setTarget(this.getTarget());
  34994. break;
  34995. case BABYLON.Camera.RIG_MODE_VR:
  34996. if (camLeft.rotationQuaternion) {
  34997. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34998. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34999. }
  35000. else {
  35001. camLeft.rotation.copyFrom(this.rotation);
  35002. camRight.rotation.copyFrom(this.rotation);
  35003. }
  35004. camLeft.position.copyFrom(this.position);
  35005. camRight.position.copyFrom(this.position);
  35006. break;
  35007. }
  35008. _super.prototype._updateRigCameras.call(this);
  35009. };
  35010. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  35011. if (!this._rigCamTransformMatrix) {
  35012. this._rigCamTransformMatrix = new BABYLON.Matrix();
  35013. }
  35014. var target = this.getTarget();
  35015. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  35016. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  35017. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  35018. };
  35019. TargetCamera.prototype.getClassName = function () {
  35020. return "TargetCamera";
  35021. };
  35022. __decorate([
  35023. BABYLON.serializeAsVector3()
  35024. ], TargetCamera.prototype, "rotation", void 0);
  35025. __decorate([
  35026. BABYLON.serialize()
  35027. ], TargetCamera.prototype, "speed", void 0);
  35028. __decorate([
  35029. BABYLON.serializeAsMeshReference("lockedTargetId")
  35030. ], TargetCamera.prototype, "lockedTarget", void 0);
  35031. return TargetCamera;
  35032. }(BABYLON.Camera));
  35033. BABYLON.TargetCamera = TargetCamera;
  35034. })(BABYLON || (BABYLON = {}));
  35035. //# sourceMappingURL=babylon.targetCamera.js.map
  35036. var BABYLON;
  35037. (function (BABYLON) {
  35038. var FreeCamera = (function (_super) {
  35039. __extends(FreeCamera, _super);
  35040. function FreeCamera(name, position, scene) {
  35041. var _this = _super.call(this, name, position, scene) || this;
  35042. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  35043. _this.checkCollisions = false;
  35044. _this.applyGravity = false;
  35045. _this._needMoveForGravity = false;
  35046. _this._oldPosition = BABYLON.Vector3.Zero();
  35047. _this._diffPosition = BABYLON.Vector3.Zero();
  35048. _this._newPosition = BABYLON.Vector3.Zero();
  35049. // Collisions
  35050. _this._collisionMask = -1;
  35051. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  35052. if (collidedMesh === void 0) { collidedMesh = null; }
  35053. //TODO move this to the collision coordinator!
  35054. if (_this.getScene().workerCollisions)
  35055. newPosition.multiplyInPlace(_this._collider.radius);
  35056. var updatePosition = function (newPos) {
  35057. _this._newPosition.copyFrom(newPos);
  35058. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  35059. var oldPosition = _this.position.clone();
  35060. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  35061. _this.position.addInPlace(_this._diffPosition);
  35062. if (_this.onCollide && collidedMesh) {
  35063. _this.onCollide(collidedMesh);
  35064. }
  35065. }
  35066. };
  35067. updatePosition(newPosition);
  35068. };
  35069. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  35070. _this.inputs.addKeyboard().addMouse();
  35071. return _this;
  35072. }
  35073. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  35074. //-- begin properties for backward compatibility for inputs
  35075. get: function () {
  35076. var mouse = this.inputs.attached["mouse"];
  35077. if (mouse)
  35078. return mouse.angularSensibility;
  35079. },
  35080. set: function (value) {
  35081. var mouse = this.inputs.attached["mouse"];
  35082. if (mouse)
  35083. mouse.angularSensibility = value;
  35084. },
  35085. enumerable: true,
  35086. configurable: true
  35087. });
  35088. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  35089. get: function () {
  35090. var keyboard = this.inputs.attached["keyboard"];
  35091. if (keyboard)
  35092. return keyboard.keysUp;
  35093. },
  35094. set: function (value) {
  35095. var keyboard = this.inputs.attached["keyboard"];
  35096. if (keyboard)
  35097. keyboard.keysUp = value;
  35098. },
  35099. enumerable: true,
  35100. configurable: true
  35101. });
  35102. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  35103. get: function () {
  35104. var keyboard = this.inputs.attached["keyboard"];
  35105. if (keyboard)
  35106. return keyboard.keysDown;
  35107. },
  35108. set: function (value) {
  35109. var keyboard = this.inputs.attached["keyboard"];
  35110. if (keyboard)
  35111. keyboard.keysDown = value;
  35112. },
  35113. enumerable: true,
  35114. configurable: true
  35115. });
  35116. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  35117. get: function () {
  35118. var keyboard = this.inputs.attached["keyboard"];
  35119. if (keyboard)
  35120. return keyboard.keysLeft;
  35121. },
  35122. set: function (value) {
  35123. var keyboard = this.inputs.attached["keyboard"];
  35124. if (keyboard)
  35125. keyboard.keysLeft = value;
  35126. },
  35127. enumerable: true,
  35128. configurable: true
  35129. });
  35130. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  35131. get: function () {
  35132. var keyboard = this.inputs.attached["keyboard"];
  35133. if (keyboard)
  35134. return keyboard.keysRight;
  35135. },
  35136. set: function (value) {
  35137. var keyboard = this.inputs.attached["keyboard"];
  35138. if (keyboard)
  35139. keyboard.keysRight = value;
  35140. },
  35141. enumerable: true,
  35142. configurable: true
  35143. });
  35144. // Controls
  35145. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  35146. this.inputs.attachElement(element, noPreventDefault);
  35147. };
  35148. FreeCamera.prototype.detachControl = function (element) {
  35149. this.inputs.detachElement(element);
  35150. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  35151. this.cameraRotation = new BABYLON.Vector2(0, 0);
  35152. };
  35153. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  35154. get: function () {
  35155. return this._collisionMask;
  35156. },
  35157. set: function (mask) {
  35158. this._collisionMask = !isNaN(mask) ? mask : -1;
  35159. },
  35160. enumerable: true,
  35161. configurable: true
  35162. });
  35163. FreeCamera.prototype._collideWithWorld = function (displacement) {
  35164. var globalPosition;
  35165. if (this.parent) {
  35166. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  35167. }
  35168. else {
  35169. globalPosition = this.position;
  35170. }
  35171. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  35172. if (!this._collider) {
  35173. this._collider = new BABYLON.Collider();
  35174. }
  35175. this._collider.radius = this.ellipsoid;
  35176. this._collider.collisionMask = this._collisionMask;
  35177. //no need for clone, as long as gravity is not on.
  35178. var actualDisplacement = displacement;
  35179. //add gravity to the direction to prevent the dual-collision checking
  35180. if (this.applyGravity) {
  35181. //this prevents mending with cameraDirection, a global variable of the free camera class.
  35182. actualDisplacement = displacement.add(this.getScene().gravity);
  35183. }
  35184. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  35185. };
  35186. FreeCamera.prototype._checkInputs = function () {
  35187. if (!this._localDirection) {
  35188. this._localDirection = BABYLON.Vector3.Zero();
  35189. this._transformedDirection = BABYLON.Vector3.Zero();
  35190. }
  35191. this.inputs.checkInputs();
  35192. _super.prototype._checkInputs.call(this);
  35193. };
  35194. FreeCamera.prototype._decideIfNeedsToMove = function () {
  35195. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  35196. };
  35197. FreeCamera.prototype._updatePosition = function () {
  35198. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  35199. this._collideWithWorld(this.cameraDirection);
  35200. }
  35201. else {
  35202. _super.prototype._updatePosition.call(this);
  35203. }
  35204. };
  35205. FreeCamera.prototype.dispose = function () {
  35206. this.inputs.clear();
  35207. _super.prototype.dispose.call(this);
  35208. };
  35209. FreeCamera.prototype.getClassName = function () {
  35210. return "FreeCamera";
  35211. };
  35212. __decorate([
  35213. BABYLON.serializeAsVector3()
  35214. ], FreeCamera.prototype, "ellipsoid", void 0);
  35215. __decorate([
  35216. BABYLON.serialize()
  35217. ], FreeCamera.prototype, "checkCollisions", void 0);
  35218. __decorate([
  35219. BABYLON.serialize()
  35220. ], FreeCamera.prototype, "applyGravity", void 0);
  35221. return FreeCamera;
  35222. }(BABYLON.TargetCamera));
  35223. BABYLON.FreeCamera = FreeCamera;
  35224. })(BABYLON || (BABYLON = {}));
  35225. //# sourceMappingURL=babylon.freeCamera.js.map
  35226. var BABYLON;
  35227. (function (BABYLON) {
  35228. var ArcRotateCameraKeyboardMoveInput = (function () {
  35229. function ArcRotateCameraKeyboardMoveInput() {
  35230. this._keys = [];
  35231. this.keysUp = [38];
  35232. this.keysDown = [40];
  35233. this.keysLeft = [37];
  35234. this.keysRight = [39];
  35235. this.keysReset = [220];
  35236. this.panningSensibility = 50.0;
  35237. this.zoomingSensibility = 25.0;
  35238. this.useAltToZoom = true;
  35239. }
  35240. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  35241. var _this = this;
  35242. if (this._onCanvasBlurObserver) {
  35243. return;
  35244. }
  35245. this._scene = this.camera.getScene();
  35246. this._engine = this._scene.getEngine();
  35247. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  35248. _this._keys = [];
  35249. });
  35250. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  35251. var evt = info.event;
  35252. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  35253. _this._ctrlPressed = evt.ctrlKey;
  35254. _this._altPressed = evt.altKey;
  35255. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35256. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35257. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35258. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35259. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35260. var index = _this._keys.indexOf(evt.keyCode);
  35261. if (index === -1) {
  35262. _this._keys.push(evt.keyCode);
  35263. }
  35264. if (evt.preventDefault) {
  35265. if (!noPreventDefault) {
  35266. evt.preventDefault();
  35267. }
  35268. }
  35269. }
  35270. }
  35271. else {
  35272. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35273. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35274. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35275. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  35276. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  35277. var index = _this._keys.indexOf(evt.keyCode);
  35278. if (index >= 0) {
  35279. _this._keys.splice(index, 1);
  35280. }
  35281. if (evt.preventDefault) {
  35282. if (!noPreventDefault) {
  35283. evt.preventDefault();
  35284. }
  35285. }
  35286. }
  35287. }
  35288. });
  35289. };
  35290. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  35291. if (this._scene) {
  35292. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  35293. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  35294. this._onKeyboardObserver = null;
  35295. this._onCanvasBlurObserver = null;
  35296. }
  35297. this._keys = [];
  35298. };
  35299. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  35300. if (this._onKeyboardObserver) {
  35301. var camera = this.camera;
  35302. for (var index = 0; index < this._keys.length; index++) {
  35303. var keyCode = this._keys[index];
  35304. if (this.keysLeft.indexOf(keyCode) !== -1) {
  35305. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35306. camera.inertialPanningX -= 1 / this.panningSensibility;
  35307. }
  35308. else {
  35309. camera.inertialAlphaOffset -= 0.01;
  35310. }
  35311. }
  35312. else if (this.keysUp.indexOf(keyCode) !== -1) {
  35313. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35314. camera.inertialPanningY += 1 / this.panningSensibility;
  35315. }
  35316. else if (this._altPressed && this.useAltToZoom) {
  35317. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  35318. }
  35319. else {
  35320. camera.inertialBetaOffset -= 0.01;
  35321. }
  35322. }
  35323. else if (this.keysRight.indexOf(keyCode) !== -1) {
  35324. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35325. camera.inertialPanningX += 1 / this.panningSensibility;
  35326. }
  35327. else {
  35328. camera.inertialAlphaOffset += 0.01;
  35329. }
  35330. }
  35331. else if (this.keysDown.indexOf(keyCode) !== -1) {
  35332. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  35333. camera.inertialPanningY -= 1 / this.panningSensibility;
  35334. }
  35335. else if (this._altPressed && this.useAltToZoom) {
  35336. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  35337. }
  35338. else {
  35339. camera.inertialBetaOffset += 0.01;
  35340. }
  35341. }
  35342. else if (this.keysReset.indexOf(keyCode) !== -1) {
  35343. camera.restoreState();
  35344. }
  35345. }
  35346. }
  35347. };
  35348. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  35349. return "ArcRotateCameraKeyboardMoveInput";
  35350. };
  35351. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  35352. return "keyboard";
  35353. };
  35354. __decorate([
  35355. BABYLON.serialize()
  35356. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  35357. __decorate([
  35358. BABYLON.serialize()
  35359. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  35360. __decorate([
  35361. BABYLON.serialize()
  35362. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  35363. __decorate([
  35364. BABYLON.serialize()
  35365. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  35366. __decorate([
  35367. BABYLON.serialize()
  35368. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  35369. __decorate([
  35370. BABYLON.serialize()
  35371. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  35372. __decorate([
  35373. BABYLON.serialize()
  35374. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  35375. __decorate([
  35376. BABYLON.serialize()
  35377. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  35378. return ArcRotateCameraKeyboardMoveInput;
  35379. }());
  35380. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  35381. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  35382. })(BABYLON || (BABYLON = {}));
  35383. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  35384. var BABYLON;
  35385. (function (BABYLON) {
  35386. var ArcRotateCameraMouseWheelInput = (function () {
  35387. function ArcRotateCameraMouseWheelInput() {
  35388. this.wheelPrecision = 3.0;
  35389. }
  35390. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  35391. var _this = this;
  35392. this._wheel = function (p, s) {
  35393. //sanity check - this should be a PointerWheel event.
  35394. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  35395. return;
  35396. var event = p.event;
  35397. var delta = 0;
  35398. if (event.wheelDelta) {
  35399. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  35400. }
  35401. else if (event.detail) {
  35402. delta = -event.detail / _this.wheelPrecision;
  35403. }
  35404. if (delta)
  35405. _this.camera.inertialRadiusOffset += delta;
  35406. if (event.preventDefault) {
  35407. if (!noPreventDefault) {
  35408. event.preventDefault();
  35409. }
  35410. }
  35411. };
  35412. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  35413. };
  35414. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  35415. if (this._observer && element) {
  35416. this.camera.getScene().onPointerObservable.remove(this._observer);
  35417. this._observer = null;
  35418. this._wheel = null;
  35419. }
  35420. };
  35421. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  35422. return "ArcRotateCameraMouseWheelInput";
  35423. };
  35424. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  35425. return "mousewheel";
  35426. };
  35427. __decorate([
  35428. BABYLON.serialize()
  35429. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  35430. return ArcRotateCameraMouseWheelInput;
  35431. }());
  35432. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  35433. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  35434. })(BABYLON || (BABYLON = {}));
  35435. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  35436. var BABYLON;
  35437. (function (BABYLON) {
  35438. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  35439. var ArcRotateCameraPointersInput = (function () {
  35440. function ArcRotateCameraPointersInput() {
  35441. this.buttons = [0, 1, 2];
  35442. this.angularSensibilityX = 1000.0;
  35443. this.angularSensibilityY = 1000.0;
  35444. this.pinchPrecision = 12.0;
  35445. this.panningSensibility = 1000.0;
  35446. this.multiTouchPanning = true;
  35447. this.multiTouchPanAndZoom = true;
  35448. this._isPanClick = false;
  35449. this.pinchInwards = true;
  35450. }
  35451. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  35452. var _this = this;
  35453. var engine = this.camera.getEngine();
  35454. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  35455. var pointA, pointB;
  35456. var previousPinchSquaredDistance = 0;
  35457. var initialDistance = 0;
  35458. var twoFingerActivityCount = 0;
  35459. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  35460. this._pointerInput = function (p, s) {
  35461. var evt = p.event;
  35462. if (engine.isInVRExclusivePointerMode) {
  35463. return;
  35464. }
  35465. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35466. return;
  35467. }
  35468. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35469. try {
  35470. evt.srcElement.setPointerCapture(evt.pointerId);
  35471. }
  35472. catch (e) {
  35473. //Nothing to do with the error. Execution will continue.
  35474. }
  35475. // Manage panning with pan button click
  35476. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  35477. // manage pointers
  35478. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  35479. if (pointA === undefined) {
  35480. pointA = cacheSoloPointer;
  35481. }
  35482. else if (pointB === undefined) {
  35483. pointB = cacheSoloPointer;
  35484. }
  35485. if (!noPreventDefault) {
  35486. evt.preventDefault();
  35487. element.focus();
  35488. }
  35489. }
  35490. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  35491. _this.camera.restoreState();
  35492. }
  35493. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35494. try {
  35495. evt.srcElement.releasePointerCapture(evt.pointerId);
  35496. }
  35497. catch (e) {
  35498. //Nothing to do with the error.
  35499. }
  35500. cacheSoloPointer = null;
  35501. previousPinchSquaredDistance = 0;
  35502. previousMultiTouchPanPosition.isPaning = false;
  35503. previousMultiTouchPanPosition.isPinching = false;
  35504. twoFingerActivityCount = 0;
  35505. initialDistance = 0;
  35506. if (p.event.pointerType !== "touch") {
  35507. pointB = undefined; // Mouse and pen are mono pointer
  35508. }
  35509. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  35510. //but emptying completly pointers collection is required to fix a bug on iPhone :
  35511. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  35512. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  35513. if (engine.badOS) {
  35514. pointA = pointB = undefined;
  35515. }
  35516. else {
  35517. //only remove the impacted pointer in case of multitouch allowing on most
  35518. //platforms switching from rotate to zoom and pan seamlessly.
  35519. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  35520. pointA = pointB;
  35521. pointB = undefined;
  35522. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  35523. }
  35524. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  35525. pointB = undefined;
  35526. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  35527. }
  35528. else {
  35529. pointA = pointB = undefined;
  35530. }
  35531. }
  35532. if (!noPreventDefault) {
  35533. evt.preventDefault();
  35534. }
  35535. }
  35536. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35537. if (!noPreventDefault) {
  35538. evt.preventDefault();
  35539. }
  35540. // One button down
  35541. if (pointA && pointB === undefined) {
  35542. if (_this.panningSensibility !== 0 &&
  35543. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  35544. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  35545. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  35546. }
  35547. else {
  35548. var offsetX = evt.clientX - cacheSoloPointer.x;
  35549. var offsetY = evt.clientY - cacheSoloPointer.y;
  35550. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35551. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35552. }
  35553. cacheSoloPointer.x = evt.clientX;
  35554. cacheSoloPointer.y = evt.clientY;
  35555. }
  35556. else if (pointA && pointB) {
  35557. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  35558. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  35559. ed.x = evt.clientX;
  35560. ed.y = evt.clientY;
  35561. var direction = _this.pinchInwards ? 1 : -1;
  35562. var distX = pointA.x - pointB.x;
  35563. var distY = pointA.y - pointB.y;
  35564. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  35565. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  35566. if (previousPinchSquaredDistance === 0) {
  35567. initialDistance = pinchDistance;
  35568. previousPinchSquaredDistance = pinchSquaredDistance;
  35569. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  35570. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  35571. return;
  35572. }
  35573. if (_this.multiTouchPanAndZoom) {
  35574. _this.camera
  35575. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  35576. (_this.pinchPrecision *
  35577. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  35578. direction);
  35579. if (_this.panningSensibility !== 0) {
  35580. var pointersCenterX = (pointA.x + pointB.x) / 2;
  35581. var pointersCenterY = (pointA.y + pointB.y) / 2;
  35582. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  35583. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  35584. previousMultiTouchPanPosition.x = pointersCenterX;
  35585. previousMultiTouchPanPosition.y = pointersCenterY;
  35586. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  35587. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  35588. }
  35589. }
  35590. else {
  35591. twoFingerActivityCount++;
  35592. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  35593. _this.camera
  35594. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  35595. (_this.pinchPrecision *
  35596. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  35597. direction);
  35598. previousMultiTouchPanPosition.isPaning = false;
  35599. previousMultiTouchPanPosition.isPinching = true;
  35600. }
  35601. else {
  35602. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  35603. if (!previousMultiTouchPanPosition.isPaning) {
  35604. previousMultiTouchPanPosition.isPaning = true;
  35605. previousMultiTouchPanPosition.isPinching = false;
  35606. previousMultiTouchPanPosition.x = ed.x;
  35607. previousMultiTouchPanPosition.y = ed.y;
  35608. return;
  35609. }
  35610. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  35611. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  35612. }
  35613. }
  35614. if (cacheSoloPointer.pointerId === evt.pointerId) {
  35615. previousMultiTouchPanPosition.x = ed.x;
  35616. previousMultiTouchPanPosition.y = ed.y;
  35617. }
  35618. }
  35619. previousPinchSquaredDistance = pinchSquaredDistance;
  35620. }
  35621. }
  35622. };
  35623. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  35624. this._onContextMenu = function (evt) {
  35625. evt.preventDefault();
  35626. };
  35627. if (!this.camera._useCtrlForPanning) {
  35628. element.addEventListener("contextmenu", this._onContextMenu, false);
  35629. }
  35630. this._onLostFocus = function () {
  35631. //this._keys = [];
  35632. pointA = pointB = undefined;
  35633. previousPinchSquaredDistance = 0;
  35634. previousMultiTouchPanPosition.isPaning = false;
  35635. previousMultiTouchPanPosition.isPinching = false;
  35636. twoFingerActivityCount = 0;
  35637. cacheSoloPointer = null;
  35638. initialDistance = 0;
  35639. };
  35640. this._onMouseMove = function (evt) {
  35641. if (!engine.isPointerLock) {
  35642. return;
  35643. }
  35644. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  35645. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  35646. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35647. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35648. if (!noPreventDefault) {
  35649. evt.preventDefault();
  35650. }
  35651. };
  35652. this._onGestureStart = function (e) {
  35653. if (window.MSGesture === undefined) {
  35654. return;
  35655. }
  35656. if (!_this._MSGestureHandler) {
  35657. _this._MSGestureHandler = new MSGesture();
  35658. _this._MSGestureHandler.target = element;
  35659. }
  35660. _this._MSGestureHandler.addPointer(e.pointerId);
  35661. };
  35662. this._onGesture = function (e) {
  35663. _this.camera.radius *= e.scale;
  35664. if (e.preventDefault) {
  35665. if (!noPreventDefault) {
  35666. e.stopPropagation();
  35667. e.preventDefault();
  35668. }
  35669. }
  35670. };
  35671. element.addEventListener("mousemove", this._onMouseMove, false);
  35672. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  35673. element.addEventListener("MSGestureChange", this._onGesture, false);
  35674. BABYLON.Tools.RegisterTopRootEvents([
  35675. { name: "blur", handler: this._onLostFocus }
  35676. ]);
  35677. };
  35678. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  35679. BABYLON.Tools.UnregisterTopRootEvents([
  35680. { name: "blur", handler: this._onLostFocus }
  35681. ]);
  35682. if (element && this._observer) {
  35683. this.camera.getScene().onPointerObservable.remove(this._observer);
  35684. this._observer = null;
  35685. element.removeEventListener("contextmenu", this._onContextMenu);
  35686. element.removeEventListener("mousemove", this._onMouseMove);
  35687. element.removeEventListener("MSPointerDown", this._onGestureStart);
  35688. element.removeEventListener("MSGestureChange", this._onGesture);
  35689. this._isPanClick = false;
  35690. this.pinchInwards = true;
  35691. this._onMouseMove = null;
  35692. this._onGestureStart = null;
  35693. this._onGesture = null;
  35694. this._MSGestureHandler = null;
  35695. this._onLostFocus = null;
  35696. this._onContextMenu = null;
  35697. }
  35698. };
  35699. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  35700. return "ArcRotateCameraPointersInput";
  35701. };
  35702. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  35703. return "pointers";
  35704. };
  35705. __decorate([
  35706. BABYLON.serialize()
  35707. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  35708. __decorate([
  35709. BABYLON.serialize()
  35710. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  35711. __decorate([
  35712. BABYLON.serialize()
  35713. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  35714. __decorate([
  35715. BABYLON.serialize()
  35716. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  35717. __decorate([
  35718. BABYLON.serialize()
  35719. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  35720. __decorate([
  35721. BABYLON.serialize()
  35722. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  35723. __decorate([
  35724. BABYLON.serialize()
  35725. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  35726. return ArcRotateCameraPointersInput;
  35727. }());
  35728. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  35729. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  35730. })(BABYLON || (BABYLON = {}));
  35731. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  35732. /// <reference path="babylon.targetCamera.ts" />
  35733. /// <reference path="..\Tools\babylon.tools.ts" />
  35734. var BABYLON;
  35735. (function (BABYLON) {
  35736. var ArcRotateCamera = (function (_super) {
  35737. __extends(ArcRotateCamera, _super);
  35738. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  35739. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  35740. _this.inertialAlphaOffset = 0;
  35741. _this.inertialBetaOffset = 0;
  35742. _this.inertialRadiusOffset = 0;
  35743. _this.lowerAlphaLimit = null;
  35744. _this.upperAlphaLimit = null;
  35745. _this.lowerBetaLimit = 0.01;
  35746. _this.upperBetaLimit = Math.PI;
  35747. _this.lowerRadiusLimit = null;
  35748. _this.upperRadiusLimit = null;
  35749. _this.inertialPanningX = 0;
  35750. _this.inertialPanningY = 0;
  35751. _this.pinchToPanMaxDistance = 20;
  35752. _this.panningDistanceLimit = null;
  35753. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  35754. _this.panningInertia = 0.9;
  35755. //-- end properties for backward compatibility for inputs
  35756. _this.zoomOnFactor = 1;
  35757. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  35758. _this.allowUpsideDown = true;
  35759. _this._viewMatrix = new BABYLON.Matrix();
  35760. // Panning
  35761. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  35762. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  35763. _this.checkCollisions = false;
  35764. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35765. _this._previousPosition = BABYLON.Vector3.Zero();
  35766. _this._collisionVelocity = BABYLON.Vector3.Zero();
  35767. _this._newPosition = BABYLON.Vector3.Zero();
  35768. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  35769. if (collidedMesh === void 0) { collidedMesh = null; }
  35770. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  35771. newPosition.multiplyInPlace(_this._collider.radius);
  35772. }
  35773. if (!collidedMesh) {
  35774. _this._previousPosition.copyFrom(_this.position);
  35775. }
  35776. else {
  35777. _this.setPosition(newPosition);
  35778. if (_this.onCollide) {
  35779. _this.onCollide(collidedMesh);
  35780. }
  35781. }
  35782. // Recompute because of constraints
  35783. var cosa = Math.cos(_this.alpha);
  35784. var sina = Math.sin(_this.alpha);
  35785. var cosb = Math.cos(_this.beta);
  35786. var sinb = Math.sin(_this.beta);
  35787. if (sinb === 0) {
  35788. sinb = 0.0001;
  35789. }
  35790. var target = _this._getTargetPosition();
  35791. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  35792. _this.position.copyFrom(_this._newPosition);
  35793. var up = _this.upVector;
  35794. if (_this.allowUpsideDown && _this.beta < 0) {
  35795. up = up.clone();
  35796. up = up.negate();
  35797. }
  35798. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  35799. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  35800. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  35801. _this._collisionTriggered = false;
  35802. };
  35803. _this._target = BABYLON.Vector3.Zero();
  35804. if (target) {
  35805. _this.setTarget(target);
  35806. }
  35807. _this.alpha = alpha;
  35808. _this.beta = beta;
  35809. _this.radius = radius;
  35810. _this.getViewMatrix();
  35811. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  35812. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  35813. return _this;
  35814. }
  35815. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  35816. get: function () {
  35817. return this._target;
  35818. },
  35819. set: function (value) {
  35820. this.setTarget(value);
  35821. },
  35822. enumerable: true,
  35823. configurable: true
  35824. });
  35825. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  35826. //-- begin properties for backward compatibility for inputs
  35827. get: function () {
  35828. var pointers = this.inputs.attached["pointers"];
  35829. if (pointers)
  35830. return pointers.angularSensibilityX;
  35831. },
  35832. set: function (value) {
  35833. var pointers = this.inputs.attached["pointers"];
  35834. if (pointers) {
  35835. pointers.angularSensibilityX = value;
  35836. }
  35837. },
  35838. enumerable: true,
  35839. configurable: true
  35840. });
  35841. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35842. get: function () {
  35843. var pointers = this.inputs.attached["pointers"];
  35844. if (pointers)
  35845. return pointers.angularSensibilityY;
  35846. },
  35847. set: function (value) {
  35848. var pointers = this.inputs.attached["pointers"];
  35849. if (pointers) {
  35850. pointers.angularSensibilityY = value;
  35851. }
  35852. },
  35853. enumerable: true,
  35854. configurable: true
  35855. });
  35856. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35857. get: function () {
  35858. var pointers = this.inputs.attached["pointers"];
  35859. if (pointers)
  35860. return pointers.pinchPrecision;
  35861. },
  35862. set: function (value) {
  35863. var pointers = this.inputs.attached["pointers"];
  35864. if (pointers) {
  35865. pointers.pinchPrecision = value;
  35866. }
  35867. },
  35868. enumerable: true,
  35869. configurable: true
  35870. });
  35871. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35872. get: function () {
  35873. var pointers = this.inputs.attached["pointers"];
  35874. if (pointers)
  35875. return pointers.panningSensibility;
  35876. },
  35877. set: function (value) {
  35878. var pointers = this.inputs.attached["pointers"];
  35879. if (pointers) {
  35880. pointers.panningSensibility = value;
  35881. }
  35882. },
  35883. enumerable: true,
  35884. configurable: true
  35885. });
  35886. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35887. get: function () {
  35888. var keyboard = this.inputs.attached["keyboard"];
  35889. if (keyboard)
  35890. return keyboard.keysUp;
  35891. },
  35892. set: function (value) {
  35893. var keyboard = this.inputs.attached["keyboard"];
  35894. if (keyboard)
  35895. keyboard.keysUp = value;
  35896. },
  35897. enumerable: true,
  35898. configurable: true
  35899. });
  35900. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35901. get: function () {
  35902. var keyboard = this.inputs.attached["keyboard"];
  35903. if (keyboard)
  35904. return keyboard.keysDown;
  35905. },
  35906. set: function (value) {
  35907. var keyboard = this.inputs.attached["keyboard"];
  35908. if (keyboard)
  35909. keyboard.keysDown = value;
  35910. },
  35911. enumerable: true,
  35912. configurable: true
  35913. });
  35914. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35915. get: function () {
  35916. var keyboard = this.inputs.attached["keyboard"];
  35917. if (keyboard)
  35918. return keyboard.keysLeft;
  35919. },
  35920. set: function (value) {
  35921. var keyboard = this.inputs.attached["keyboard"];
  35922. if (keyboard)
  35923. keyboard.keysLeft = value;
  35924. },
  35925. enumerable: true,
  35926. configurable: true
  35927. });
  35928. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35929. get: function () {
  35930. var keyboard = this.inputs.attached["keyboard"];
  35931. if (keyboard)
  35932. return keyboard.keysRight;
  35933. },
  35934. set: function (value) {
  35935. var keyboard = this.inputs.attached["keyboard"];
  35936. if (keyboard)
  35937. keyboard.keysRight = value;
  35938. },
  35939. enumerable: true,
  35940. configurable: true
  35941. });
  35942. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35943. get: function () {
  35944. var mousewheel = this.inputs.attached["mousewheel"];
  35945. if (mousewheel)
  35946. return mousewheel.wheelPrecision;
  35947. },
  35948. set: function (value) {
  35949. var mousewheel = this.inputs.attached["mousewheel"];
  35950. if (mousewheel)
  35951. mousewheel.wheelPrecision = value;
  35952. },
  35953. enumerable: true,
  35954. configurable: true
  35955. });
  35956. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35957. get: function () {
  35958. return this._bouncingBehavior;
  35959. },
  35960. enumerable: true,
  35961. configurable: true
  35962. });
  35963. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35964. get: function () {
  35965. return this._bouncingBehavior != null;
  35966. },
  35967. set: function (value) {
  35968. if (value === this.useBouncingBehavior) {
  35969. return;
  35970. }
  35971. if (value) {
  35972. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35973. this.addBehavior(this._bouncingBehavior);
  35974. }
  35975. else {
  35976. this.removeBehavior(this._bouncingBehavior);
  35977. this._bouncingBehavior = null;
  35978. }
  35979. },
  35980. enumerable: true,
  35981. configurable: true
  35982. });
  35983. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35984. get: function () {
  35985. return this._framingBehavior;
  35986. },
  35987. enumerable: true,
  35988. configurable: true
  35989. });
  35990. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35991. get: function () {
  35992. return this._framingBehavior != null;
  35993. },
  35994. set: function (value) {
  35995. if (value === this.useFramingBehavior) {
  35996. return;
  35997. }
  35998. if (value) {
  35999. this._framingBehavior = new BABYLON.FramingBehavior();
  36000. this.addBehavior(this._framingBehavior);
  36001. }
  36002. else {
  36003. this.removeBehavior(this._framingBehavior);
  36004. this._framingBehavior = null;
  36005. }
  36006. },
  36007. enumerable: true,
  36008. configurable: true
  36009. });
  36010. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  36011. get: function () {
  36012. return this._autoRotationBehavior;
  36013. },
  36014. enumerable: true,
  36015. configurable: true
  36016. });
  36017. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  36018. get: function () {
  36019. return this._autoRotationBehavior != null;
  36020. },
  36021. set: function (value) {
  36022. if (value === this.useAutoRotationBehavior) {
  36023. return;
  36024. }
  36025. if (value) {
  36026. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  36027. this.addBehavior(this._autoRotationBehavior);
  36028. }
  36029. else {
  36030. this.removeBehavior(this._autoRotationBehavior);
  36031. this._autoRotationBehavior = null;
  36032. }
  36033. },
  36034. enumerable: true,
  36035. configurable: true
  36036. });
  36037. // Cache
  36038. ArcRotateCamera.prototype._initCache = function () {
  36039. _super.prototype._initCache.call(this);
  36040. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36041. this._cache.alpha = undefined;
  36042. this._cache.beta = undefined;
  36043. this._cache.radius = undefined;
  36044. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  36045. };
  36046. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  36047. if (!ignoreParentClass) {
  36048. _super.prototype._updateCache.call(this);
  36049. }
  36050. this._cache._target.copyFrom(this._getTargetPosition());
  36051. this._cache.alpha = this.alpha;
  36052. this._cache.beta = this.beta;
  36053. this._cache.radius = this.radius;
  36054. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  36055. };
  36056. ArcRotateCamera.prototype._getTargetPosition = function () {
  36057. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  36058. var pos = this._targetHost.getAbsolutePosition();
  36059. if (this._targetBoundingCenter) {
  36060. pos.addToRef(this._targetBoundingCenter, this._target);
  36061. }
  36062. else {
  36063. this._target.copyFrom(pos);
  36064. }
  36065. }
  36066. var lockedTargetPosition = this._getLockedTargetPosition();
  36067. if (lockedTargetPosition) {
  36068. return lockedTargetPosition;
  36069. }
  36070. return this._target;
  36071. };
  36072. ArcRotateCamera.prototype.storeState = function () {
  36073. this._storedAlpha = this.alpha;
  36074. this._storedBeta = this.beta;
  36075. this._storedRadius = this.radius;
  36076. this._storedTarget = this._getTargetPosition().clone();
  36077. return _super.prototype.storeState.call(this);
  36078. };
  36079. /**
  36080. * Restored camera state. You must call storeState() first
  36081. */
  36082. ArcRotateCamera.prototype._restoreStateValues = function () {
  36083. if (!_super.prototype._restoreStateValues.call(this)) {
  36084. return false;
  36085. }
  36086. this.alpha = this._storedAlpha;
  36087. this.beta = this._storedBeta;
  36088. this.radius = this._storedRadius;
  36089. this.setTarget(this._storedTarget.clone());
  36090. this.inertialAlphaOffset = 0;
  36091. this.inertialBetaOffset = 0;
  36092. this.inertialRadiusOffset = 0;
  36093. this.inertialPanningX = 0;
  36094. this.inertialPanningY = 0;
  36095. return true;
  36096. };
  36097. // Synchronized
  36098. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  36099. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  36100. return false;
  36101. return this._cache._target.equals(this._getTargetPosition())
  36102. && this._cache.alpha === this.alpha
  36103. && this._cache.beta === this.beta
  36104. && this._cache.radius === this.radius
  36105. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  36106. };
  36107. // Methods
  36108. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  36109. var _this = this;
  36110. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  36111. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  36112. this._useCtrlForPanning = useCtrlForPanning;
  36113. this._panningMouseButton = panningMouseButton;
  36114. this.inputs.attachElement(element, noPreventDefault);
  36115. this._reset = function () {
  36116. _this.inertialAlphaOffset = 0;
  36117. _this.inertialBetaOffset = 0;
  36118. _this.inertialRadiusOffset = 0;
  36119. _this.inertialPanningX = 0;
  36120. _this.inertialPanningY = 0;
  36121. };
  36122. };
  36123. ArcRotateCamera.prototype.detachControl = function (element) {
  36124. this.inputs.detachElement(element);
  36125. if (this._reset) {
  36126. this._reset();
  36127. }
  36128. };
  36129. ArcRotateCamera.prototype._checkInputs = function () {
  36130. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  36131. if (this._collisionTriggered) {
  36132. return;
  36133. }
  36134. this.inputs.checkInputs();
  36135. // Inertia
  36136. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  36137. if (this.getScene().useRightHandedSystem) {
  36138. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  36139. }
  36140. else {
  36141. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  36142. }
  36143. this.beta += this.inertialBetaOffset;
  36144. this.radius -= this.inertialRadiusOffset;
  36145. this.inertialAlphaOffset *= this.inertia;
  36146. this.inertialBetaOffset *= this.inertia;
  36147. this.inertialRadiusOffset *= this.inertia;
  36148. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  36149. this.inertialAlphaOffset = 0;
  36150. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  36151. this.inertialBetaOffset = 0;
  36152. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  36153. this.inertialRadiusOffset = 0;
  36154. }
  36155. // Panning inertia
  36156. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  36157. if (!this._localDirection) {
  36158. this._localDirection = BABYLON.Vector3.Zero();
  36159. this._transformedDirection = BABYLON.Vector3.Zero();
  36160. }
  36161. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  36162. this._localDirection.multiplyInPlace(this.panningAxis);
  36163. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  36164. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  36165. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  36166. if (!this.panningAxis.y) {
  36167. this._transformedDirection.y = 0;
  36168. }
  36169. if (!this._targetHost) {
  36170. if (this.panningDistanceLimit) {
  36171. this._transformedDirection.addInPlace(this._target);
  36172. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  36173. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  36174. this._target.copyFrom(this._transformedDirection);
  36175. }
  36176. }
  36177. else {
  36178. this._target.addInPlace(this._transformedDirection);
  36179. }
  36180. }
  36181. this.inertialPanningX *= this.panningInertia;
  36182. this.inertialPanningY *= this.panningInertia;
  36183. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  36184. this.inertialPanningX = 0;
  36185. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  36186. this.inertialPanningY = 0;
  36187. }
  36188. // Limits
  36189. this._checkLimits();
  36190. _super.prototype._checkInputs.call(this);
  36191. };
  36192. ArcRotateCamera.prototype._checkLimits = function () {
  36193. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  36194. if (this.allowUpsideDown && this.beta > Math.PI) {
  36195. this.beta = this.beta - (2 * Math.PI);
  36196. }
  36197. }
  36198. else {
  36199. if (this.beta < this.lowerBetaLimit) {
  36200. this.beta = this.lowerBetaLimit;
  36201. }
  36202. }
  36203. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  36204. if (this.allowUpsideDown && this.beta < -Math.PI) {
  36205. this.beta = this.beta + (2 * Math.PI);
  36206. }
  36207. }
  36208. else {
  36209. if (this.beta > this.upperBetaLimit) {
  36210. this.beta = this.upperBetaLimit;
  36211. }
  36212. }
  36213. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  36214. this.alpha = this.lowerAlphaLimit;
  36215. }
  36216. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  36217. this.alpha = this.upperAlphaLimit;
  36218. }
  36219. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  36220. this.radius = this.lowerRadiusLimit;
  36221. }
  36222. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  36223. this.radius = this.upperRadiusLimit;
  36224. }
  36225. };
  36226. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  36227. var radiusv3 = this.position.subtract(this._getTargetPosition());
  36228. this.radius = radiusv3.length();
  36229. if (this.radius === 0) {
  36230. this.radius = 0.0001; // Just to avoid division by zero
  36231. }
  36232. // Alpha
  36233. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  36234. if (radiusv3.z < 0) {
  36235. this.alpha = 2 * Math.PI - this.alpha;
  36236. }
  36237. // Beta
  36238. this.beta = Math.acos(radiusv3.y / this.radius);
  36239. this._checkLimits();
  36240. };
  36241. ArcRotateCamera.prototype.setPosition = function (position) {
  36242. if (this.position.equals(position)) {
  36243. return;
  36244. }
  36245. this.position.copyFrom(position);
  36246. this.rebuildAnglesAndRadius();
  36247. };
  36248. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  36249. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  36250. if (allowSamePosition === void 0) { allowSamePosition = false; }
  36251. if (target.getBoundingInfo) {
  36252. if (toBoundingCenter) {
  36253. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  36254. }
  36255. else {
  36256. this._targetBoundingCenter = null;
  36257. }
  36258. this._targetHost = target;
  36259. this._target = this._getTargetPosition();
  36260. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  36261. }
  36262. else {
  36263. var newTarget = target;
  36264. var currentTarget = this._getTargetPosition();
  36265. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  36266. return;
  36267. }
  36268. this._targetHost = null;
  36269. this._target = newTarget;
  36270. this._targetBoundingCenter = null;
  36271. this.onMeshTargetChangedObservable.notifyObservers(null);
  36272. }
  36273. this.rebuildAnglesAndRadius();
  36274. };
  36275. ArcRotateCamera.prototype._getViewMatrix = function () {
  36276. // Compute
  36277. var cosa = Math.cos(this.alpha);
  36278. var sina = Math.sin(this.alpha);
  36279. var cosb = Math.cos(this.beta);
  36280. var sinb = Math.sin(this.beta);
  36281. if (sinb === 0) {
  36282. sinb = 0.0001;
  36283. }
  36284. var target = this._getTargetPosition();
  36285. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  36286. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  36287. if (!this._collider) {
  36288. this._collider = new BABYLON.Collider();
  36289. }
  36290. this._collider.radius = this.collisionRadius;
  36291. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  36292. this._collisionTriggered = true;
  36293. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  36294. }
  36295. else {
  36296. this.position.copyFrom(this._newPosition);
  36297. var up = this.upVector;
  36298. if (this.allowUpsideDown && sinb < 0) {
  36299. up = up.clone();
  36300. up = up.negate();
  36301. }
  36302. if (this.getScene().useRightHandedSystem) {
  36303. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  36304. }
  36305. else {
  36306. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  36307. }
  36308. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  36309. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  36310. }
  36311. this._currentTarget = target;
  36312. return this._viewMatrix;
  36313. };
  36314. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  36315. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36316. meshes = meshes || this.getScene().meshes;
  36317. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  36318. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  36319. this.radius = distance * this.zoomOnFactor;
  36320. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  36321. };
  36322. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  36323. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  36324. var meshesOrMinMaxVector;
  36325. var distance;
  36326. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  36327. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  36328. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  36329. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  36330. }
  36331. else {
  36332. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  36333. distance = meshesOrMinMaxVectorAndDistance.distance;
  36334. }
  36335. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  36336. if (!doNotUpdateMaxZ) {
  36337. this.maxZ = distance * 2;
  36338. }
  36339. };
  36340. /**
  36341. * @override
  36342. * Override Camera.createRigCamera
  36343. */
  36344. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  36345. var alphaShift;
  36346. switch (this.cameraRigMode) {
  36347. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36348. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36349. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36350. case BABYLON.Camera.RIG_MODE_VR:
  36351. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  36352. break;
  36353. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36354. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  36355. break;
  36356. }
  36357. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  36358. rigCam._cameraRigParams = {};
  36359. return rigCam;
  36360. };
  36361. /**
  36362. * @override
  36363. * Override Camera._updateRigCameras
  36364. */
  36365. ArcRotateCamera.prototype._updateRigCameras = function () {
  36366. var camLeft = this._rigCameras[0];
  36367. var camRight = this._rigCameras[1];
  36368. camLeft.beta = camRight.beta = this.beta;
  36369. camLeft.radius = camRight.radius = this.radius;
  36370. switch (this.cameraRigMode) {
  36371. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36372. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36373. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36374. case BABYLON.Camera.RIG_MODE_VR:
  36375. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36376. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36377. break;
  36378. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36379. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  36380. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  36381. break;
  36382. }
  36383. _super.prototype._updateRigCameras.call(this);
  36384. };
  36385. ArcRotateCamera.prototype.dispose = function () {
  36386. this.inputs.clear();
  36387. _super.prototype.dispose.call(this);
  36388. };
  36389. ArcRotateCamera.prototype.getClassName = function () {
  36390. return "ArcRotateCamera";
  36391. };
  36392. __decorate([
  36393. BABYLON.serialize()
  36394. ], ArcRotateCamera.prototype, "alpha", void 0);
  36395. __decorate([
  36396. BABYLON.serialize()
  36397. ], ArcRotateCamera.prototype, "beta", void 0);
  36398. __decorate([
  36399. BABYLON.serialize()
  36400. ], ArcRotateCamera.prototype, "radius", void 0);
  36401. __decorate([
  36402. BABYLON.serializeAsVector3("target")
  36403. ], ArcRotateCamera.prototype, "_target", void 0);
  36404. __decorate([
  36405. BABYLON.serialize()
  36406. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  36407. __decorate([
  36408. BABYLON.serialize()
  36409. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  36410. __decorate([
  36411. BABYLON.serialize()
  36412. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  36413. __decorate([
  36414. BABYLON.serialize()
  36415. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  36416. __decorate([
  36417. BABYLON.serialize()
  36418. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  36419. __decorate([
  36420. BABYLON.serialize()
  36421. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  36422. __decorate([
  36423. BABYLON.serialize()
  36424. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  36425. __decorate([
  36426. BABYLON.serialize()
  36427. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  36428. __decorate([
  36429. BABYLON.serialize()
  36430. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  36431. __decorate([
  36432. BABYLON.serialize()
  36433. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  36434. __decorate([
  36435. BABYLON.serialize()
  36436. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  36437. __decorate([
  36438. BABYLON.serialize()
  36439. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  36440. __decorate([
  36441. BABYLON.serialize()
  36442. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  36443. __decorate([
  36444. BABYLON.serializeAsVector3()
  36445. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  36446. __decorate([
  36447. BABYLON.serialize()
  36448. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  36449. __decorate([
  36450. BABYLON.serialize()
  36451. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  36452. __decorate([
  36453. BABYLON.serialize()
  36454. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  36455. return ArcRotateCamera;
  36456. }(BABYLON.TargetCamera));
  36457. BABYLON.ArcRotateCamera = ArcRotateCamera;
  36458. })(BABYLON || (BABYLON = {}));
  36459. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  36460. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  36461. var BABYLON;
  36462. (function (BABYLON) {
  36463. var ArcRotateCameraInputsManager = (function (_super) {
  36464. __extends(ArcRotateCameraInputsManager, _super);
  36465. function ArcRotateCameraInputsManager(camera) {
  36466. return _super.call(this, camera) || this;
  36467. }
  36468. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  36469. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  36470. return this;
  36471. };
  36472. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  36473. this.add(new BABYLON.ArcRotateCameraPointersInput());
  36474. return this;
  36475. };
  36476. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  36477. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  36478. return this;
  36479. };
  36480. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  36481. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  36482. return this;
  36483. };
  36484. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  36485. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  36486. return this;
  36487. };
  36488. return ArcRotateCameraInputsManager;
  36489. }(BABYLON.CameraInputsManager));
  36490. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  36491. })(BABYLON || (BABYLON = {}));
  36492. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  36493. var BABYLON;
  36494. (function (BABYLON) {
  36495. var HemisphericLight = (function (_super) {
  36496. __extends(HemisphericLight, _super);
  36497. /**
  36498. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  36499. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  36500. * The HemisphericLight can't cast shadows.
  36501. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36502. */
  36503. function HemisphericLight(name, direction, scene) {
  36504. var _this = _super.call(this, name, scene) || this;
  36505. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  36506. _this.direction = direction || BABYLON.Vector3.Up();
  36507. return _this;
  36508. }
  36509. HemisphericLight.prototype._buildUniformLayout = function () {
  36510. this._uniformBuffer.addUniform("vLightData", 4);
  36511. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36512. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36513. this._uniformBuffer.addUniform("vLightGround", 3);
  36514. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36515. this._uniformBuffer.addUniform("depthValues", 2);
  36516. this._uniformBuffer.create();
  36517. };
  36518. /**
  36519. * Returns the string "HemisphericLight".
  36520. */
  36521. HemisphericLight.prototype.getClassName = function () {
  36522. return "HemisphericLight";
  36523. };
  36524. /**
  36525. * Sets the HemisphericLight direction towards the passed target (Vector3).
  36526. * Returns the updated direction.
  36527. */
  36528. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  36529. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  36530. return this.direction;
  36531. };
  36532. HemisphericLight.prototype.getShadowGenerator = function () {
  36533. return null;
  36534. };
  36535. /**
  36536. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  36537. * Returns the HemisphericLight.
  36538. */
  36539. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  36540. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36541. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  36542. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  36543. return this;
  36544. };
  36545. HemisphericLight.prototype._getWorldMatrix = function () {
  36546. if (!this._worldMatrix) {
  36547. this._worldMatrix = BABYLON.Matrix.Identity();
  36548. }
  36549. return this._worldMatrix;
  36550. };
  36551. /**
  36552. * Returns the integer 3.
  36553. */
  36554. HemisphericLight.prototype.getTypeID = function () {
  36555. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  36556. };
  36557. __decorate([
  36558. BABYLON.serializeAsColor3()
  36559. ], HemisphericLight.prototype, "groundColor", void 0);
  36560. __decorate([
  36561. BABYLON.serializeAsVector3()
  36562. ], HemisphericLight.prototype, "direction", void 0);
  36563. return HemisphericLight;
  36564. }(BABYLON.Light));
  36565. BABYLON.HemisphericLight = HemisphericLight;
  36566. })(BABYLON || (BABYLON = {}));
  36567. //# sourceMappingURL=babylon.hemisphericLight.js.map
  36568. var BABYLON;
  36569. (function (BABYLON) {
  36570. var ShadowLight = (function (_super) {
  36571. __extends(ShadowLight, _super);
  36572. function ShadowLight() {
  36573. var _this = _super !== null && _super.apply(this, arguments) || this;
  36574. _this._needProjectionMatrixCompute = true;
  36575. return _this;
  36576. }
  36577. Object.defineProperty(ShadowLight.prototype, "direction", {
  36578. get: function () {
  36579. return this._direction;
  36580. },
  36581. set: function (value) {
  36582. this._direction = value;
  36583. },
  36584. enumerable: true,
  36585. configurable: true
  36586. });
  36587. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36588. get: function () {
  36589. return this._shadowMinZ;
  36590. },
  36591. set: function (value) {
  36592. this._shadowMinZ = value;
  36593. this.forceProjectionMatrixCompute();
  36594. },
  36595. enumerable: true,
  36596. configurable: true
  36597. });
  36598. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36599. get: function () {
  36600. return this._shadowMaxZ;
  36601. },
  36602. set: function (value) {
  36603. this._shadowMaxZ = value;
  36604. this.forceProjectionMatrixCompute();
  36605. },
  36606. enumerable: true,
  36607. configurable: true
  36608. });
  36609. /**
  36610. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36611. */
  36612. ShadowLight.prototype.computeTransformedInformation = function () {
  36613. if (this.parent && this.parent.getWorldMatrix) {
  36614. if (!this.transformedPosition) {
  36615. this.transformedPosition = BABYLON.Vector3.Zero();
  36616. }
  36617. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36618. // In case the direction is present.
  36619. if (this.direction) {
  36620. if (!this.transformedDirection) {
  36621. this.transformedDirection = BABYLON.Vector3.Zero();
  36622. }
  36623. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36624. }
  36625. return true;
  36626. }
  36627. return false;
  36628. };
  36629. /**
  36630. * Return the depth scale used for the shadow map.
  36631. */
  36632. ShadowLight.prototype.getDepthScale = function () {
  36633. return 50.0;
  36634. };
  36635. /**
  36636. * Returns the light direction (Vector3) for any passed face index.
  36637. */
  36638. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36639. return this.transformedDirection ? this.transformedDirection : this.direction;
  36640. };
  36641. /**
  36642. * Returns the DirectionalLight absolute position in the World.
  36643. */
  36644. ShadowLight.prototype.getAbsolutePosition = function () {
  36645. return this.transformedPosition ? this.transformedPosition : this.position;
  36646. };
  36647. /**
  36648. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36649. * Returns the updated DirectionalLight direction (Vector3).
  36650. */
  36651. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36652. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36653. return this.direction;
  36654. };
  36655. /**
  36656. * Returns the light rotation (Vector3).
  36657. */
  36658. ShadowLight.prototype.getRotation = function () {
  36659. this.direction.normalize();
  36660. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36661. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36662. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36663. };
  36664. /**
  36665. * Boolean : false by default.
  36666. */
  36667. ShadowLight.prototype.needCube = function () {
  36668. return false;
  36669. };
  36670. /**
  36671. * Specifies wether or not the projection matrix should be recomputed this frame.
  36672. */
  36673. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36674. return this._needProjectionMatrixCompute;
  36675. };
  36676. /**
  36677. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36678. */
  36679. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36680. this._needProjectionMatrixCompute = true;
  36681. };
  36682. /**
  36683. * Get the world matrix of the sahdow lights.
  36684. */
  36685. ShadowLight.prototype._getWorldMatrix = function () {
  36686. if (!this._worldMatrix) {
  36687. this._worldMatrix = BABYLON.Matrix.Identity();
  36688. }
  36689. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36690. return this._worldMatrix;
  36691. };
  36692. /**
  36693. * Gets the minZ used for shadow according to both the scene and the light.
  36694. * @param activeCamera
  36695. */
  36696. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36697. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36698. };
  36699. /**
  36700. * Gets the maxZ used for shadow according to both the scene and the light.
  36701. * @param activeCamera
  36702. */
  36703. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36704. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36705. };
  36706. /**
  36707. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36708. * Returns the light.
  36709. */
  36710. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36711. if (this.customProjectionMatrixBuilder) {
  36712. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36713. }
  36714. else {
  36715. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36716. }
  36717. return this;
  36718. };
  36719. __decorate([
  36720. BABYLON.serializeAsVector3()
  36721. ], ShadowLight.prototype, "position", void 0);
  36722. __decorate([
  36723. BABYLON.serializeAsVector3()
  36724. ], ShadowLight.prototype, "direction", null);
  36725. __decorate([
  36726. BABYLON.serialize()
  36727. ], ShadowLight.prototype, "shadowMinZ", null);
  36728. __decorate([
  36729. BABYLON.serialize()
  36730. ], ShadowLight.prototype, "shadowMaxZ", null);
  36731. return ShadowLight;
  36732. }(BABYLON.Light));
  36733. BABYLON.ShadowLight = ShadowLight;
  36734. })(BABYLON || (BABYLON = {}));
  36735. //# sourceMappingURL=babylon.shadowLight.js.map
  36736. var BABYLON;
  36737. (function (BABYLON) {
  36738. var PointLight = (function (_super) {
  36739. __extends(PointLight, _super);
  36740. /**
  36741. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36742. * A PointLight emits the light in every direction.
  36743. * It can cast shadows.
  36744. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36745. * ```javascript
  36746. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36747. * ```
  36748. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36749. */
  36750. function PointLight(name, position, scene) {
  36751. var _this = _super.call(this, name, scene) || this;
  36752. _this._shadowAngle = Math.PI / 2;
  36753. _this.position = position;
  36754. return _this;
  36755. }
  36756. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36757. /**
  36758. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36759. * This specifies what angle the shadow will use to be created.
  36760. *
  36761. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36762. */
  36763. get: function () {
  36764. return this._shadowAngle;
  36765. },
  36766. /**
  36767. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36768. * This specifies what angle the shadow will use to be created.
  36769. *
  36770. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36771. */
  36772. set: function (value) {
  36773. this._shadowAngle = value;
  36774. this.forceProjectionMatrixCompute();
  36775. },
  36776. enumerable: true,
  36777. configurable: true
  36778. });
  36779. Object.defineProperty(PointLight.prototype, "direction", {
  36780. get: function () {
  36781. return this._direction;
  36782. },
  36783. /**
  36784. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36785. */
  36786. set: function (value) {
  36787. var previousNeedCube = this.needCube();
  36788. this._direction = value;
  36789. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36790. this._shadowGenerator.recreateShadowMap();
  36791. }
  36792. },
  36793. enumerable: true,
  36794. configurable: true
  36795. });
  36796. /**
  36797. * Returns the string "PointLight"
  36798. */
  36799. PointLight.prototype.getClassName = function () {
  36800. return "PointLight";
  36801. };
  36802. /**
  36803. * Returns the integer 0.
  36804. */
  36805. PointLight.prototype.getTypeID = function () {
  36806. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36807. };
  36808. /**
  36809. * Specifies wether or not the shadowmap should be a cube texture.
  36810. */
  36811. PointLight.prototype.needCube = function () {
  36812. return !this.direction;
  36813. };
  36814. /**
  36815. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36816. */
  36817. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36818. if (this.direction) {
  36819. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36820. }
  36821. else {
  36822. switch (faceIndex) {
  36823. case 0:
  36824. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36825. case 1:
  36826. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36827. case 2:
  36828. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36829. case 3:
  36830. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36831. case 4:
  36832. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36833. case 5:
  36834. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36835. }
  36836. }
  36837. return BABYLON.Vector3.Zero();
  36838. };
  36839. /**
  36840. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36841. * - fov = PI / 2
  36842. * - aspect ratio : 1.0
  36843. * - z-near and far equal to the active camera minZ and maxZ.
  36844. * Returns the PointLight.
  36845. */
  36846. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36847. var activeCamera = this.getScene().activeCamera;
  36848. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36849. };
  36850. PointLight.prototype._buildUniformLayout = function () {
  36851. this._uniformBuffer.addUniform("vLightData", 4);
  36852. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36853. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36854. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36855. this._uniformBuffer.addUniform("depthValues", 2);
  36856. this._uniformBuffer.create();
  36857. };
  36858. /**
  36859. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36860. * Returns the PointLight.
  36861. */
  36862. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36863. if (this.computeTransformedInformation()) {
  36864. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36865. return this;
  36866. }
  36867. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36868. return this;
  36869. };
  36870. __decorate([
  36871. BABYLON.serialize()
  36872. ], PointLight.prototype, "shadowAngle", null);
  36873. return PointLight;
  36874. }(BABYLON.ShadowLight));
  36875. BABYLON.PointLight = PointLight;
  36876. })(BABYLON || (BABYLON = {}));
  36877. //# sourceMappingURL=babylon.pointLight.js.map
  36878. /// <reference path="babylon.light.ts" />
  36879. var BABYLON;
  36880. (function (BABYLON) {
  36881. var DirectionalLight = (function (_super) {
  36882. __extends(DirectionalLight, _super);
  36883. /**
  36884. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36885. * The directional light is emitted from everywhere in the given direction.
  36886. * It can cast shawdows.
  36887. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36888. */
  36889. function DirectionalLight(name, direction, scene) {
  36890. var _this = _super.call(this, name, scene) || this;
  36891. _this._shadowFrustumSize = 0;
  36892. _this._shadowOrthoScale = 0.5;
  36893. _this.autoUpdateExtends = true;
  36894. // Cache
  36895. _this._orthoLeft = Number.MAX_VALUE;
  36896. _this._orthoRight = Number.MIN_VALUE;
  36897. _this._orthoTop = Number.MIN_VALUE;
  36898. _this._orthoBottom = Number.MAX_VALUE;
  36899. _this.position = direction.scale(-1.0);
  36900. _this.direction = direction;
  36901. return _this;
  36902. }
  36903. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36904. /**
  36905. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36906. */
  36907. get: function () {
  36908. return this._shadowFrustumSize;
  36909. },
  36910. /**
  36911. * Specifies a fix frustum size for the shadow generation.
  36912. */
  36913. set: function (value) {
  36914. this._shadowFrustumSize = value;
  36915. this.forceProjectionMatrixCompute();
  36916. },
  36917. enumerable: true,
  36918. configurable: true
  36919. });
  36920. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36921. get: function () {
  36922. return this._shadowOrthoScale;
  36923. },
  36924. set: function (value) {
  36925. this._shadowOrthoScale = value;
  36926. this.forceProjectionMatrixCompute();
  36927. },
  36928. enumerable: true,
  36929. configurable: true
  36930. });
  36931. /**
  36932. * Returns the string "DirectionalLight".
  36933. */
  36934. DirectionalLight.prototype.getClassName = function () {
  36935. return "DirectionalLight";
  36936. };
  36937. /**
  36938. * Returns the integer 1.
  36939. */
  36940. DirectionalLight.prototype.getTypeID = function () {
  36941. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36942. };
  36943. /**
  36944. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36945. * Returns the DirectionalLight Shadow projection matrix.
  36946. */
  36947. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36948. if (this.shadowFrustumSize > 0) {
  36949. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36950. }
  36951. else {
  36952. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36953. }
  36954. };
  36955. /**
  36956. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36957. * Returns the DirectionalLight Shadow projection matrix.
  36958. */
  36959. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36960. var activeCamera = this.getScene().activeCamera;
  36961. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36962. };
  36963. /**
  36964. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36965. * Returns the DirectionalLight Shadow projection matrix.
  36966. */
  36967. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36968. var activeCamera = this.getScene().activeCamera;
  36969. // Check extends
  36970. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36971. var tempVector3 = BABYLON.Vector3.Zero();
  36972. this._orthoLeft = Number.MAX_VALUE;
  36973. this._orthoRight = Number.MIN_VALUE;
  36974. this._orthoTop = Number.MIN_VALUE;
  36975. this._orthoBottom = Number.MAX_VALUE;
  36976. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36977. var mesh = renderList[meshIndex];
  36978. if (!mesh) {
  36979. continue;
  36980. }
  36981. var boundingInfo = mesh.getBoundingInfo();
  36982. if (!boundingInfo) {
  36983. continue;
  36984. }
  36985. var boundingBox = boundingInfo.boundingBox;
  36986. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36987. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36988. if (tempVector3.x < this._orthoLeft)
  36989. this._orthoLeft = tempVector3.x;
  36990. if (tempVector3.y < this._orthoBottom)
  36991. this._orthoBottom = tempVector3.y;
  36992. if (tempVector3.x > this._orthoRight)
  36993. this._orthoRight = tempVector3.x;
  36994. if (tempVector3.y > this._orthoTop)
  36995. this._orthoTop = tempVector3.y;
  36996. }
  36997. }
  36998. }
  36999. var xOffset = this._orthoRight - this._orthoLeft;
  37000. var yOffset = this._orthoTop - this._orthoBottom;
  37001. 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);
  37002. };
  37003. DirectionalLight.prototype._buildUniformLayout = function () {
  37004. this._uniformBuffer.addUniform("vLightData", 4);
  37005. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  37006. this._uniformBuffer.addUniform("vLightSpecular", 3);
  37007. this._uniformBuffer.addUniform("shadowsInfo", 3);
  37008. this._uniformBuffer.addUniform("depthValues", 2);
  37009. this._uniformBuffer.create();
  37010. };
  37011. /**
  37012. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  37013. * Returns the DirectionalLight.
  37014. */
  37015. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  37016. if (this.computeTransformedInformation()) {
  37017. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  37018. return this;
  37019. }
  37020. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  37021. return this;
  37022. };
  37023. /**
  37024. * Gets the minZ used for shadow according to both the scene and the light.
  37025. *
  37026. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  37027. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  37028. * @param activeCamera
  37029. */
  37030. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  37031. return 1;
  37032. };
  37033. /**
  37034. * Gets the maxZ used for shadow according to both the scene and the light.
  37035. *
  37036. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  37037. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  37038. * @param activeCamera
  37039. */
  37040. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  37041. return 1;
  37042. };
  37043. __decorate([
  37044. BABYLON.serialize()
  37045. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  37046. __decorate([
  37047. BABYLON.serialize()
  37048. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  37049. __decorate([
  37050. BABYLON.serialize()
  37051. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  37052. return DirectionalLight;
  37053. }(BABYLON.ShadowLight));
  37054. BABYLON.DirectionalLight = DirectionalLight;
  37055. })(BABYLON || (BABYLON = {}));
  37056. //# sourceMappingURL=babylon.directionalLight.js.map
  37057. var BABYLON;
  37058. (function (BABYLON) {
  37059. var SpotLight = (function (_super) {
  37060. __extends(SpotLight, _super);
  37061. /**
  37062. * Creates a SpotLight object in the scene with the passed parameters :
  37063. * - `position` (Vector3) is the initial SpotLight position,
  37064. * - `direction` (Vector3) is the initial SpotLight direction,
  37065. * - `angle` (float, in radians) is the spot light cone angle,
  37066. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  37067. * A spot light is a simply light oriented cone.
  37068. * It can cast shadows.
  37069. * Documentation : http://doc.babylonjs.com/tutorials/lights
  37070. */
  37071. function SpotLight(name, position, direction, angle, exponent, scene) {
  37072. var _this = _super.call(this, name, scene) || this;
  37073. _this.position = position;
  37074. _this.direction = direction;
  37075. _this.angle = angle;
  37076. _this.exponent = exponent;
  37077. return _this;
  37078. }
  37079. Object.defineProperty(SpotLight.prototype, "angle", {
  37080. get: function () {
  37081. return this._angle;
  37082. },
  37083. set: function (value) {
  37084. this._angle = value;
  37085. this.forceProjectionMatrixCompute();
  37086. },
  37087. enumerable: true,
  37088. configurable: true
  37089. });
  37090. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  37091. get: function () {
  37092. return this._shadowAngleScale;
  37093. },
  37094. /**
  37095. * Allows scaling the angle of the light for shadow generation only.
  37096. */
  37097. set: function (value) {
  37098. this._shadowAngleScale = value;
  37099. this.forceProjectionMatrixCompute();
  37100. },
  37101. enumerable: true,
  37102. configurable: true
  37103. });
  37104. /**
  37105. * Returns the string "SpotLight".
  37106. */
  37107. SpotLight.prototype.getClassName = function () {
  37108. return "SpotLight";
  37109. };
  37110. /**
  37111. * Returns the integer 2.
  37112. */
  37113. SpotLight.prototype.getTypeID = function () {
  37114. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  37115. };
  37116. /**
  37117. * 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.
  37118. * Returns the SpotLight.
  37119. */
  37120. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  37121. var activeCamera = this.getScene().activeCamera;
  37122. this._shadowAngleScale = this._shadowAngleScale || 1;
  37123. var angle = this._shadowAngleScale * this._angle;
  37124. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  37125. };
  37126. SpotLight.prototype._buildUniformLayout = function () {
  37127. this._uniformBuffer.addUniform("vLightData", 4);
  37128. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  37129. this._uniformBuffer.addUniform("vLightSpecular", 3);
  37130. this._uniformBuffer.addUniform("vLightDirection", 3);
  37131. this._uniformBuffer.addUniform("shadowsInfo", 3);
  37132. this._uniformBuffer.addUniform("depthValues", 2);
  37133. this._uniformBuffer.create();
  37134. };
  37135. /**
  37136. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  37137. * Return the SpotLight.
  37138. */
  37139. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  37140. var normalizeDirection;
  37141. if (this.computeTransformedInformation()) {
  37142. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  37143. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  37144. }
  37145. else {
  37146. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  37147. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  37148. }
  37149. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  37150. return this;
  37151. };
  37152. __decorate([
  37153. BABYLON.serialize()
  37154. ], SpotLight.prototype, "angle", null);
  37155. __decorate([
  37156. BABYLON.serialize()
  37157. /**
  37158. * Allows scaling the angle of the light for shadow generation only.
  37159. */
  37160. ], SpotLight.prototype, "shadowAngleScale", null);
  37161. __decorate([
  37162. BABYLON.serialize()
  37163. ], SpotLight.prototype, "exponent", void 0);
  37164. return SpotLight;
  37165. }(BABYLON.ShadowLight));
  37166. BABYLON.SpotLight = SpotLight;
  37167. })(BABYLON || (BABYLON = {}));
  37168. //# sourceMappingURL=babylon.spotLight.js.map
  37169. var BABYLON;
  37170. (function (BABYLON) {
  37171. var AnimationRange = (function () {
  37172. function AnimationRange(name, from, to) {
  37173. this.name = name;
  37174. this.from = from;
  37175. this.to = to;
  37176. }
  37177. AnimationRange.prototype.clone = function () {
  37178. return new AnimationRange(this.name, this.from, this.to);
  37179. };
  37180. return AnimationRange;
  37181. }());
  37182. BABYLON.AnimationRange = AnimationRange;
  37183. /**
  37184. * Composed of a frame, and an action function
  37185. */
  37186. var AnimationEvent = (function () {
  37187. function AnimationEvent(frame, action, onlyOnce) {
  37188. this.frame = frame;
  37189. this.action = action;
  37190. this.onlyOnce = onlyOnce;
  37191. this.isDone = false;
  37192. }
  37193. return AnimationEvent;
  37194. }());
  37195. BABYLON.AnimationEvent = AnimationEvent;
  37196. var PathCursor = (function () {
  37197. function PathCursor(path) {
  37198. this.path = path;
  37199. this._onchange = new Array();
  37200. this.value = 0;
  37201. this.animations = new Array();
  37202. }
  37203. PathCursor.prototype.getPoint = function () {
  37204. var point = this.path.getPointAtLengthPosition(this.value);
  37205. return new BABYLON.Vector3(point.x, 0, point.y);
  37206. };
  37207. PathCursor.prototype.moveAhead = function (step) {
  37208. if (step === void 0) { step = 0.002; }
  37209. this.move(step);
  37210. return this;
  37211. };
  37212. PathCursor.prototype.moveBack = function (step) {
  37213. if (step === void 0) { step = 0.002; }
  37214. this.move(-step);
  37215. return this;
  37216. };
  37217. PathCursor.prototype.move = function (step) {
  37218. if (Math.abs(step) > 1) {
  37219. throw "step size should be less than 1.";
  37220. }
  37221. this.value += step;
  37222. this.ensureLimits();
  37223. this.raiseOnChange();
  37224. return this;
  37225. };
  37226. PathCursor.prototype.ensureLimits = function () {
  37227. while (this.value > 1) {
  37228. this.value -= 1;
  37229. }
  37230. while (this.value < 0) {
  37231. this.value += 1;
  37232. }
  37233. return this;
  37234. };
  37235. // used by animation engine
  37236. PathCursor.prototype.markAsDirty = function (propertyName) {
  37237. this.ensureLimits();
  37238. this.raiseOnChange();
  37239. return this;
  37240. };
  37241. PathCursor.prototype.raiseOnChange = function () {
  37242. var _this = this;
  37243. this._onchange.forEach(function (f) { return f(_this); });
  37244. return this;
  37245. };
  37246. PathCursor.prototype.onchange = function (f) {
  37247. this._onchange.push(f);
  37248. return this;
  37249. };
  37250. return PathCursor;
  37251. }());
  37252. BABYLON.PathCursor = PathCursor;
  37253. var Animation = (function () {
  37254. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  37255. this.name = name;
  37256. this.targetProperty = targetProperty;
  37257. this.framePerSecond = framePerSecond;
  37258. this.dataType = dataType;
  37259. this.loopMode = loopMode;
  37260. this.enableBlending = enableBlending;
  37261. this._runtimeAnimations = new Array();
  37262. // The set of event that will be linked to this animation
  37263. this._events = new Array();
  37264. this.blendingSpeed = 0.01;
  37265. this._ranges = {};
  37266. this.targetPropertyPath = targetProperty.split(".");
  37267. this.dataType = dataType;
  37268. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  37269. }
  37270. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  37271. var dataType = undefined;
  37272. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  37273. dataType = Animation.ANIMATIONTYPE_FLOAT;
  37274. }
  37275. else if (from instanceof BABYLON.Quaternion) {
  37276. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  37277. }
  37278. else if (from instanceof BABYLON.Vector3) {
  37279. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  37280. }
  37281. else if (from instanceof BABYLON.Vector2) {
  37282. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  37283. }
  37284. else if (from instanceof BABYLON.Color3) {
  37285. dataType = Animation.ANIMATIONTYPE_COLOR3;
  37286. }
  37287. else if (from instanceof BABYLON.Size) {
  37288. dataType = Animation.ANIMATIONTYPE_SIZE;
  37289. }
  37290. if (dataType == undefined) {
  37291. return null;
  37292. }
  37293. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  37294. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  37295. animation.setKeys(keys);
  37296. if (easingFunction !== undefined) {
  37297. animation.setEasingFunction(easingFunction);
  37298. }
  37299. return animation;
  37300. };
  37301. /**
  37302. * Sets up an animation.
  37303. * @param property the property to animate
  37304. * @param animationType the animation type to apply
  37305. * @param easingFunction the easing function used in the animation
  37306. * @returns The created animation
  37307. */
  37308. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  37309. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37310. animation.setEasingFunction(easingFunction);
  37311. return animation;
  37312. };
  37313. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37314. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37315. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37316. };
  37317. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  37318. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  37319. node.animations.push(animation);
  37320. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  37321. };
  37322. /**
  37323. * Transition property of the Camera to the target Value.
  37324. * @param property The property to transition
  37325. * @param targetValue The target Value of the property
  37326. * @param host The object where the property to animate belongs
  37327. * @param scene Scene used to run the animation
  37328. * @param frameRate Framerate (in frame/s) to use
  37329. * @param transition The transition type we want to use
  37330. * @param duration The duration of the animation, in milliseconds
  37331. * @param onAnimationEnd Call back trigger at the end of the animation.
  37332. */
  37333. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  37334. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  37335. if (duration <= 0) {
  37336. host[property] = targetValue;
  37337. if (onAnimationEnd) {
  37338. onAnimationEnd();
  37339. }
  37340. return;
  37341. }
  37342. var endFrame = frameRate * (duration / 1000);
  37343. transition.setKeys([{
  37344. frame: 0,
  37345. value: host[property].clone ? host[property].clone() : host[property]
  37346. },
  37347. {
  37348. frame: endFrame,
  37349. value: targetValue
  37350. }]);
  37351. if (!host.animations) {
  37352. host.animations = [];
  37353. }
  37354. host.animations.push(transition);
  37355. var animation = scene.beginAnimation(host, 0, endFrame, false);
  37356. animation.onAnimationEnd = onAnimationEnd;
  37357. return animation;
  37358. };
  37359. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  37360. /**
  37361. * Return the array of runtime animations currently using this animation
  37362. */
  37363. get: function () {
  37364. return this._runtimeAnimations;
  37365. },
  37366. enumerable: true,
  37367. configurable: true
  37368. });
  37369. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  37370. get: function () {
  37371. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  37372. var runtimeAnimation = _a[_i];
  37373. if (!runtimeAnimation.isStopped) {
  37374. return true;
  37375. }
  37376. }
  37377. return false;
  37378. },
  37379. enumerable: true,
  37380. configurable: true
  37381. });
  37382. // Methods
  37383. /**
  37384. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  37385. */
  37386. Animation.prototype.toString = function (fullDetails) {
  37387. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  37388. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  37389. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  37390. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  37391. if (fullDetails) {
  37392. ret += ", Ranges: {";
  37393. var first = true;
  37394. for (var name in this._ranges) {
  37395. if (first) {
  37396. ret += ", ";
  37397. first = false;
  37398. }
  37399. ret += name;
  37400. }
  37401. ret += "}";
  37402. }
  37403. return ret;
  37404. };
  37405. /**
  37406. * Add an event to this animation.
  37407. */
  37408. Animation.prototype.addEvent = function (event) {
  37409. this._events.push(event);
  37410. };
  37411. /**
  37412. * Remove all events found at the given frame
  37413. * @param frame
  37414. */
  37415. Animation.prototype.removeEvents = function (frame) {
  37416. for (var index = 0; index < this._events.length; index++) {
  37417. if (this._events[index].frame === frame) {
  37418. this._events.splice(index, 1);
  37419. index--;
  37420. }
  37421. }
  37422. };
  37423. Animation.prototype.getEvents = function () {
  37424. return this._events;
  37425. };
  37426. Animation.prototype.createRange = function (name, from, to) {
  37427. // check name not already in use; could happen for bones after serialized
  37428. if (!this._ranges[name]) {
  37429. this._ranges[name] = new AnimationRange(name, from, to);
  37430. }
  37431. };
  37432. Animation.prototype.deleteRange = function (name, deleteFrames) {
  37433. if (deleteFrames === void 0) { deleteFrames = true; }
  37434. if (this._ranges[name]) {
  37435. if (deleteFrames) {
  37436. var from = this._ranges[name].from;
  37437. var to = this._ranges[name].to;
  37438. // this loop MUST go high to low for multiple splices to work
  37439. for (var key = this._keys.length - 1; key >= 0; key--) {
  37440. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  37441. this._keys.splice(key, 1);
  37442. }
  37443. }
  37444. }
  37445. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  37446. }
  37447. };
  37448. Animation.prototype.getRange = function (name) {
  37449. return this._ranges[name];
  37450. };
  37451. Animation.prototype.getKeys = function () {
  37452. return this._keys;
  37453. };
  37454. Animation.prototype.getHighestFrame = function () {
  37455. var ret = 0;
  37456. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  37457. if (ret < this._keys[key].frame) {
  37458. ret = this._keys[key].frame;
  37459. }
  37460. }
  37461. return ret;
  37462. };
  37463. Animation.prototype.getEasingFunction = function () {
  37464. return this._easingFunction;
  37465. };
  37466. Animation.prototype.setEasingFunction = function (easingFunction) {
  37467. this._easingFunction = easingFunction;
  37468. };
  37469. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  37470. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  37471. };
  37472. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37473. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37474. };
  37475. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  37476. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  37477. };
  37478. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37479. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  37480. };
  37481. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  37482. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  37483. };
  37484. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37485. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37486. };
  37487. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  37488. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  37489. };
  37490. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37491. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37492. };
  37493. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  37494. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  37495. };
  37496. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  37497. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  37498. };
  37499. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  37500. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  37501. };
  37502. Animation.prototype.clone = function () {
  37503. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  37504. clone.enableBlending = this.enableBlending;
  37505. clone.blendingSpeed = this.blendingSpeed;
  37506. if (this._keys) {
  37507. clone.setKeys(this._keys);
  37508. }
  37509. if (this._ranges) {
  37510. clone._ranges = {};
  37511. for (var name in this._ranges) {
  37512. clone._ranges[name] = this._ranges[name].clone();
  37513. }
  37514. }
  37515. return clone;
  37516. };
  37517. Animation.prototype.setKeys = function (values) {
  37518. this._keys = values.slice(0);
  37519. };
  37520. Animation.prototype.serialize = function () {
  37521. var serializationObject = {};
  37522. serializationObject.name = this.name;
  37523. serializationObject.property = this.targetProperty;
  37524. serializationObject.framePerSecond = this.framePerSecond;
  37525. serializationObject.dataType = this.dataType;
  37526. serializationObject.loopBehavior = this.loopMode;
  37527. serializationObject.enableBlending = this.enableBlending;
  37528. serializationObject.blendingSpeed = this.blendingSpeed;
  37529. var dataType = this.dataType;
  37530. serializationObject.keys = [];
  37531. var keys = this.getKeys();
  37532. for (var index = 0; index < keys.length; index++) {
  37533. var animationKey = keys[index];
  37534. var key = {};
  37535. key.frame = animationKey.frame;
  37536. switch (dataType) {
  37537. case Animation.ANIMATIONTYPE_FLOAT:
  37538. key.values = [animationKey.value];
  37539. break;
  37540. case Animation.ANIMATIONTYPE_QUATERNION:
  37541. case Animation.ANIMATIONTYPE_MATRIX:
  37542. case Animation.ANIMATIONTYPE_VECTOR3:
  37543. case Animation.ANIMATIONTYPE_COLOR3:
  37544. key.values = animationKey.value.asArray();
  37545. break;
  37546. }
  37547. serializationObject.keys.push(key);
  37548. }
  37549. serializationObject.ranges = [];
  37550. for (var name in this._ranges) {
  37551. var range = {};
  37552. range.name = name;
  37553. range.from = this._ranges[name].from;
  37554. range.to = this._ranges[name].to;
  37555. serializationObject.ranges.push(range);
  37556. }
  37557. return serializationObject;
  37558. };
  37559. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  37560. get: function () {
  37561. return Animation._ANIMATIONTYPE_FLOAT;
  37562. },
  37563. enumerable: true,
  37564. configurable: true
  37565. });
  37566. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  37567. get: function () {
  37568. return Animation._ANIMATIONTYPE_VECTOR3;
  37569. },
  37570. enumerable: true,
  37571. configurable: true
  37572. });
  37573. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  37574. get: function () {
  37575. return Animation._ANIMATIONTYPE_VECTOR2;
  37576. },
  37577. enumerable: true,
  37578. configurable: true
  37579. });
  37580. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  37581. get: function () {
  37582. return Animation._ANIMATIONTYPE_SIZE;
  37583. },
  37584. enumerable: true,
  37585. configurable: true
  37586. });
  37587. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  37588. get: function () {
  37589. return Animation._ANIMATIONTYPE_QUATERNION;
  37590. },
  37591. enumerable: true,
  37592. configurable: true
  37593. });
  37594. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37595. get: function () {
  37596. return Animation._ANIMATIONTYPE_MATRIX;
  37597. },
  37598. enumerable: true,
  37599. configurable: true
  37600. });
  37601. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37602. get: function () {
  37603. return Animation._ANIMATIONTYPE_COLOR3;
  37604. },
  37605. enumerable: true,
  37606. configurable: true
  37607. });
  37608. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37609. get: function () {
  37610. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37611. },
  37612. enumerable: true,
  37613. configurable: true
  37614. });
  37615. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37616. get: function () {
  37617. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37618. },
  37619. enumerable: true,
  37620. configurable: true
  37621. });
  37622. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37623. get: function () {
  37624. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37625. },
  37626. enumerable: true,
  37627. configurable: true
  37628. });
  37629. Animation.Parse = function (parsedAnimation) {
  37630. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37631. var dataType = parsedAnimation.dataType;
  37632. var keys = [];
  37633. var data;
  37634. var index;
  37635. if (parsedAnimation.enableBlending) {
  37636. animation.enableBlending = parsedAnimation.enableBlending;
  37637. }
  37638. if (parsedAnimation.blendingSpeed) {
  37639. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37640. }
  37641. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37642. var key = parsedAnimation.keys[index];
  37643. switch (dataType) {
  37644. case Animation.ANIMATIONTYPE_FLOAT:
  37645. data = key.values[0];
  37646. break;
  37647. case Animation.ANIMATIONTYPE_QUATERNION:
  37648. data = BABYLON.Quaternion.FromArray(key.values);
  37649. break;
  37650. case Animation.ANIMATIONTYPE_MATRIX:
  37651. data = BABYLON.Matrix.FromArray(key.values);
  37652. break;
  37653. case Animation.ANIMATIONTYPE_COLOR3:
  37654. data = BABYLON.Color3.FromArray(key.values);
  37655. break;
  37656. case Animation.ANIMATIONTYPE_VECTOR3:
  37657. default:
  37658. data = BABYLON.Vector3.FromArray(key.values);
  37659. break;
  37660. }
  37661. keys.push({
  37662. frame: key.frame,
  37663. value: data
  37664. });
  37665. }
  37666. animation.setKeys(keys);
  37667. if (parsedAnimation.ranges) {
  37668. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37669. data = parsedAnimation.ranges[index];
  37670. animation.createRange(data.name, data.from, data.to);
  37671. }
  37672. }
  37673. return animation;
  37674. };
  37675. Animation.AppendSerializedAnimations = function (source, destination) {
  37676. if (source.animations) {
  37677. destination.animations = [];
  37678. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37679. var animation = source.animations[animationIndex];
  37680. destination.animations.push(animation.serialize());
  37681. }
  37682. }
  37683. };
  37684. Animation.AllowMatricesInterpolation = false;
  37685. // Statics
  37686. Animation._ANIMATIONTYPE_FLOAT = 0;
  37687. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37688. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37689. Animation._ANIMATIONTYPE_MATRIX = 3;
  37690. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37691. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37692. Animation._ANIMATIONTYPE_SIZE = 6;
  37693. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37694. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37695. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37696. return Animation;
  37697. }());
  37698. BABYLON.Animation = Animation;
  37699. })(BABYLON || (BABYLON = {}));
  37700. //# sourceMappingURL=babylon.animation.js.map
  37701. var BABYLON;
  37702. (function (BABYLON) {
  37703. var RuntimeAnimation = (function () {
  37704. function RuntimeAnimation(target, animation) {
  37705. this._offsetsCache = {};
  37706. this._highLimitsCache = {};
  37707. this._stopped = false;
  37708. this._blendingFactor = 0;
  37709. this._ratioOffset = 0;
  37710. this._animation = animation;
  37711. this._target = target;
  37712. animation._runtimeAnimations.push(this);
  37713. }
  37714. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  37715. get: function () {
  37716. return this._animation;
  37717. },
  37718. enumerable: true,
  37719. configurable: true
  37720. });
  37721. RuntimeAnimation.prototype.reset = function () {
  37722. this._offsetsCache = {};
  37723. this._highLimitsCache = {};
  37724. this.currentFrame = 0;
  37725. this._blendingFactor = 0;
  37726. this._originalBlendValue = null;
  37727. };
  37728. RuntimeAnimation.prototype.isStopped = function () {
  37729. return this._stopped;
  37730. };
  37731. RuntimeAnimation.prototype.dispose = function () {
  37732. var index = this._animation.runtimeAnimations.indexOf(this);
  37733. if (index > -1) {
  37734. this._animation.runtimeAnimations.splice(index, 1);
  37735. }
  37736. };
  37737. RuntimeAnimation.prototype._getKeyValue = function (value) {
  37738. if (typeof value === "function") {
  37739. return value();
  37740. }
  37741. return value;
  37742. };
  37743. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  37744. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  37745. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  37746. }
  37747. this.currentFrame = currentFrame;
  37748. var keys = this._animation.getKeys();
  37749. // Try to get a hash to find the right key
  37750. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  37751. if (keys[startKeyIndex].frame >= currentFrame) {
  37752. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  37753. startKeyIndex--;
  37754. }
  37755. }
  37756. for (var key = startKeyIndex; key < keys.length; key++) {
  37757. var endKey = keys[key + 1];
  37758. if (endKey.frame >= currentFrame) {
  37759. var startKey = keys[key];
  37760. var startValue = this._getKeyValue(startKey.value);
  37761. var endValue = this._getKeyValue(endKey.value);
  37762. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  37763. var frameDelta = endKey.frame - startKey.frame;
  37764. // gradient : percent of currentFrame between the frame inf and the frame sup
  37765. var gradient = (currentFrame - startKey.frame) / frameDelta;
  37766. // check for easingFunction and correction of gradient
  37767. var easingFunction = this._animation.getEasingFunction();
  37768. if (easingFunction != null) {
  37769. gradient = easingFunction.ease(gradient);
  37770. }
  37771. switch (this._animation.dataType) {
  37772. // Float
  37773. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37774. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  37775. switch (loopMode) {
  37776. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37777. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37778. return floatValue;
  37779. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37780. return offsetValue * repeatCount + floatValue;
  37781. }
  37782. break;
  37783. // Quaternion
  37784. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37785. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  37786. switch (loopMode) {
  37787. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37788. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37789. return quatValue;
  37790. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37791. return quatValue.add(offsetValue.scale(repeatCount));
  37792. }
  37793. return quatValue;
  37794. // Vector3
  37795. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37796. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  37797. switch (loopMode) {
  37798. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37799. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37800. return vec3Value;
  37801. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37802. return vec3Value.add(offsetValue.scale(repeatCount));
  37803. }
  37804. // Vector2
  37805. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37806. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  37807. switch (loopMode) {
  37808. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37809. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37810. return vec2Value;
  37811. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37812. return vec2Value.add(offsetValue.scale(repeatCount));
  37813. }
  37814. // Size
  37815. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37816. switch (loopMode) {
  37817. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37818. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37819. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  37820. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37821. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37822. }
  37823. // Color3
  37824. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37825. switch (loopMode) {
  37826. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37827. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37828. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  37829. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37830. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37831. }
  37832. // Matrix
  37833. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  37834. switch (loopMode) {
  37835. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  37836. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  37837. if (BABYLON.Animation.AllowMatricesInterpolation) {
  37838. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  37839. }
  37840. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  37841. return startValue;
  37842. }
  37843. default:
  37844. break;
  37845. }
  37846. break;
  37847. }
  37848. }
  37849. return this._getKeyValue(keys[keys.length - 1].value);
  37850. };
  37851. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  37852. if (blend === void 0) { blend = false; }
  37853. // Set value
  37854. var path;
  37855. var destination;
  37856. var targetPropertyPath = this._animation.targetPropertyPath;
  37857. if (targetPropertyPath.length > 1) {
  37858. var property = this._target[targetPropertyPath[0]];
  37859. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  37860. property = property[targetPropertyPath[index]];
  37861. }
  37862. path = targetPropertyPath[targetPropertyPath.length - 1];
  37863. destination = property;
  37864. }
  37865. else {
  37866. path = targetPropertyPath[0];
  37867. destination = this._target;
  37868. }
  37869. // Blending
  37870. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  37871. if (!this._originalBlendValue) {
  37872. if (destination[path].clone) {
  37873. this._originalBlendValue = destination[path].clone();
  37874. }
  37875. else {
  37876. this._originalBlendValue = destination[path];
  37877. }
  37878. }
  37879. if (this._originalBlendValue.prototype) {
  37880. if (this._originalBlendValue.prototype.Lerp) {
  37881. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  37882. }
  37883. else {
  37884. destination[path] = currentValue;
  37885. }
  37886. }
  37887. else if (this._originalBlendValue.m) {
  37888. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  37889. }
  37890. else {
  37891. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  37892. }
  37893. this._blendingFactor += this._animation.blendingSpeed;
  37894. }
  37895. else {
  37896. destination[path] = currentValue;
  37897. }
  37898. if (this._target.markAsDirty) {
  37899. this._target.markAsDirty(this._animation.targetProperty);
  37900. }
  37901. };
  37902. RuntimeAnimation.prototype.goToFrame = function (frame) {
  37903. var keys = this._animation.getKeys();
  37904. if (frame < keys[0].frame) {
  37905. frame = keys[0].frame;
  37906. }
  37907. else if (frame > keys[keys.length - 1].frame) {
  37908. frame = keys[keys.length - 1].frame;
  37909. }
  37910. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  37911. this.setValue(currentValue);
  37912. };
  37913. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  37914. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  37915. this._ratioOffset = this._previousRatio - newRatio;
  37916. };
  37917. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  37918. if (blend === void 0) { blend = false; }
  37919. var targetPropertyPath = this._animation.targetPropertyPath;
  37920. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  37921. this._stopped = true;
  37922. return false;
  37923. }
  37924. var returnValue = true;
  37925. var keys = this._animation.getKeys();
  37926. // Adding a start key at frame 0 if missing
  37927. if (keys[0].frame !== 0) {
  37928. var newKey = { frame: 0, value: keys[0].value };
  37929. keys.splice(0, 0, newKey);
  37930. }
  37931. // Check limits
  37932. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  37933. from = keys[0].frame;
  37934. }
  37935. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  37936. to = keys[keys.length - 1].frame;
  37937. }
  37938. //to and from cannot be the same key
  37939. if (from === to) {
  37940. if (from > keys[0].frame) {
  37941. from--;
  37942. }
  37943. else if (to < keys[keys.length - 1].frame) {
  37944. to++;
  37945. }
  37946. }
  37947. // Compute ratio
  37948. var range = to - from;
  37949. var offsetValue;
  37950. // ratio represents the frame delta between from and to
  37951. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  37952. var highLimitValue = 0;
  37953. this._previousDelay = delay;
  37954. this._previousRatio = ratio;
  37955. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  37956. returnValue = false;
  37957. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  37958. }
  37959. else {
  37960. // Get max value if required
  37961. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  37962. var keyOffset = to.toString() + from.toString();
  37963. if (!this._offsetsCache[keyOffset]) {
  37964. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  37965. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  37966. switch (this._animation.dataType) {
  37967. // Float
  37968. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  37969. this._offsetsCache[keyOffset] = toValue - fromValue;
  37970. break;
  37971. // Quaternion
  37972. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  37973. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37974. break;
  37975. // Vector3
  37976. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  37977. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37978. // Vector2
  37979. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  37980. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37981. // Size
  37982. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  37983. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37984. // Color3
  37985. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  37986. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37987. default:
  37988. break;
  37989. }
  37990. this._highLimitsCache[keyOffset] = toValue;
  37991. }
  37992. highLimitValue = this._highLimitsCache[keyOffset];
  37993. offsetValue = this._offsetsCache[keyOffset];
  37994. }
  37995. }
  37996. if (offsetValue === undefined) {
  37997. switch (this._animation.dataType) {
  37998. // Float
  37999. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  38000. offsetValue = 0;
  38001. break;
  38002. // Quaternion
  38003. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  38004. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  38005. break;
  38006. // Vector3
  38007. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  38008. offsetValue = BABYLON.Vector3.Zero();
  38009. break;
  38010. // Vector2
  38011. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  38012. offsetValue = BABYLON.Vector2.Zero();
  38013. break;
  38014. // Size
  38015. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  38016. offsetValue = BABYLON.Size.Zero();
  38017. break;
  38018. // Color3
  38019. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  38020. offsetValue = BABYLON.Color3.Black();
  38021. }
  38022. }
  38023. // Compute value
  38024. var repeatCount = (ratio / range) >> 0;
  38025. var currentFrame = returnValue ? from + ratio % range : to;
  38026. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  38027. // Set value
  38028. this.setValue(currentValue);
  38029. // Check events
  38030. var events = this._animation.getEvents();
  38031. for (var index = 0; index < events.length; index++) {
  38032. // Make sure current frame has passed event frame and that event frame is within the current range
  38033. // Also, handle both forward and reverse animations
  38034. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  38035. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  38036. var event = events[index];
  38037. if (!event.isDone) {
  38038. // If event should be done only once, remove it.
  38039. if (event.onlyOnce) {
  38040. events.splice(index, 1);
  38041. index--;
  38042. }
  38043. event.isDone = true;
  38044. event.action();
  38045. } // Don't do anything if the event has already be done.
  38046. }
  38047. else if (events[index].isDone && !events[index].onlyOnce) {
  38048. // reset event, the animation is looping
  38049. events[index].isDone = false;
  38050. }
  38051. }
  38052. if (!returnValue) {
  38053. this._stopped = true;
  38054. }
  38055. return returnValue;
  38056. };
  38057. return RuntimeAnimation;
  38058. }());
  38059. BABYLON.RuntimeAnimation = RuntimeAnimation;
  38060. })(BABYLON || (BABYLON = {}));
  38061. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  38062. var BABYLON;
  38063. (function (BABYLON) {
  38064. var Animatable = (function () {
  38065. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  38066. if (fromFrame === void 0) { fromFrame = 0; }
  38067. if (toFrame === void 0) { toFrame = 100; }
  38068. if (loopAnimation === void 0) { loopAnimation = false; }
  38069. if (speedRatio === void 0) { speedRatio = 1.0; }
  38070. this.target = target;
  38071. this.fromFrame = fromFrame;
  38072. this.toFrame = toFrame;
  38073. this.loopAnimation = loopAnimation;
  38074. this.onAnimationEnd = onAnimationEnd;
  38075. this._localDelayOffset = null;
  38076. this._pausedDelay = null;
  38077. this._runtimeAnimations = new Array();
  38078. this._paused = false;
  38079. this._speedRatio = 1;
  38080. this.animationStarted = false;
  38081. if (animations) {
  38082. this.appendAnimations(target, animations);
  38083. }
  38084. this._speedRatio = speedRatio;
  38085. this._scene = scene;
  38086. scene._activeAnimatables.push(this);
  38087. }
  38088. Object.defineProperty(Animatable.prototype, "speedRatio", {
  38089. get: function () {
  38090. return this._speedRatio;
  38091. },
  38092. set: function (value) {
  38093. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  38094. var animation = this._runtimeAnimations[index];
  38095. animation._prepareForSpeedRatioChange(value);
  38096. }
  38097. this._speedRatio = value;
  38098. },
  38099. enumerable: true,
  38100. configurable: true
  38101. });
  38102. // Methods
  38103. Animatable.prototype.getAnimations = function () {
  38104. return this._runtimeAnimations;
  38105. };
  38106. Animatable.prototype.appendAnimations = function (target, animations) {
  38107. for (var index = 0; index < animations.length; index++) {
  38108. var animation = animations[index];
  38109. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  38110. }
  38111. };
  38112. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  38113. var runtimeAnimations = this._runtimeAnimations;
  38114. for (var index = 0; index < runtimeAnimations.length; index++) {
  38115. if (runtimeAnimations[index].animation.targetProperty === property) {
  38116. return runtimeAnimations[index].animation;
  38117. }
  38118. }
  38119. return null;
  38120. };
  38121. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  38122. var runtimeAnimations = this._runtimeAnimations;
  38123. for (var index = 0; index < runtimeAnimations.length; index++) {
  38124. if (runtimeAnimations[index].animation.targetProperty === property) {
  38125. return runtimeAnimations[index];
  38126. }
  38127. }
  38128. return null;
  38129. };
  38130. Animatable.prototype.reset = function () {
  38131. var runtimeAnimations = this._runtimeAnimations;
  38132. for (var index = 0; index < runtimeAnimations.length; index++) {
  38133. runtimeAnimations[index].reset();
  38134. }
  38135. this._localDelayOffset = null;
  38136. this._pausedDelay = null;
  38137. };
  38138. Animatable.prototype.enableBlending = function (blendingSpeed) {
  38139. var runtimeAnimations = this._runtimeAnimations;
  38140. for (var index = 0; index < runtimeAnimations.length; index++) {
  38141. runtimeAnimations[index].animation.enableBlending = true;
  38142. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  38143. }
  38144. };
  38145. Animatable.prototype.disableBlending = function () {
  38146. var runtimeAnimations = this._runtimeAnimations;
  38147. for (var index = 0; index < runtimeAnimations.length; index++) {
  38148. runtimeAnimations[index].animation.enableBlending = false;
  38149. }
  38150. };
  38151. Animatable.prototype.goToFrame = function (frame) {
  38152. var runtimeAnimations = this._runtimeAnimations;
  38153. if (runtimeAnimations[0]) {
  38154. var fps = runtimeAnimations[0].animation.framePerSecond;
  38155. var currentFrame = runtimeAnimations[0].currentFrame;
  38156. var adjustTime = frame - currentFrame;
  38157. var delay = adjustTime * 1000 / fps;
  38158. this._localDelayOffset -= delay;
  38159. }
  38160. for (var index = 0; index < runtimeAnimations.length; index++) {
  38161. runtimeAnimations[index].goToFrame(frame);
  38162. }
  38163. };
  38164. Animatable.prototype.pause = function () {
  38165. if (this._paused) {
  38166. return;
  38167. }
  38168. this._paused = true;
  38169. };
  38170. Animatable.prototype.restart = function () {
  38171. this._paused = false;
  38172. };
  38173. Animatable.prototype.stop = function (animationName) {
  38174. if (animationName) {
  38175. var idx = this._scene._activeAnimatables.indexOf(this);
  38176. if (idx > -1) {
  38177. var runtimeAnimations = this._runtimeAnimations;
  38178. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  38179. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  38180. continue;
  38181. }
  38182. runtimeAnimations[index].dispose();
  38183. runtimeAnimations.splice(index, 1);
  38184. }
  38185. if (runtimeAnimations.length == 0) {
  38186. this._scene._activeAnimatables.splice(idx, 1);
  38187. if (this.onAnimationEnd) {
  38188. this.onAnimationEnd();
  38189. }
  38190. }
  38191. }
  38192. }
  38193. else {
  38194. var index = this._scene._activeAnimatables.indexOf(this);
  38195. if (index > -1) {
  38196. this._scene._activeAnimatables.splice(index, 1);
  38197. var runtimeAnimations = this._runtimeAnimations;
  38198. for (var index = 0; index < runtimeAnimations.length; index++) {
  38199. runtimeAnimations[index].dispose();
  38200. }
  38201. if (this.onAnimationEnd) {
  38202. this.onAnimationEnd();
  38203. }
  38204. }
  38205. }
  38206. };
  38207. Animatable.prototype._animate = function (delay) {
  38208. if (this._paused) {
  38209. this.animationStarted = false;
  38210. if (this._pausedDelay === null) {
  38211. this._pausedDelay = delay;
  38212. }
  38213. return true;
  38214. }
  38215. if (this._localDelayOffset === null) {
  38216. this._localDelayOffset = delay;
  38217. }
  38218. else if (this._pausedDelay !== null) {
  38219. this._localDelayOffset += delay - this._pausedDelay;
  38220. this._pausedDelay = null;
  38221. }
  38222. // Animating
  38223. var running = false;
  38224. var runtimeAnimations = this._runtimeAnimations;
  38225. var index;
  38226. for (index = 0; index < runtimeAnimations.length; index++) {
  38227. var animation = runtimeAnimations[index];
  38228. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  38229. running = running || isRunning;
  38230. }
  38231. this.animationStarted = running;
  38232. if (!running) {
  38233. // Remove from active animatables
  38234. index = this._scene._activeAnimatables.indexOf(this);
  38235. this._scene._activeAnimatables.splice(index, 1);
  38236. // Dispose all runtime animations
  38237. for (index = 0; index < runtimeAnimations.length; index++) {
  38238. runtimeAnimations[index].dispose();
  38239. }
  38240. }
  38241. if (!running && this.onAnimationEnd) {
  38242. this.onAnimationEnd();
  38243. this.onAnimationEnd = null;
  38244. }
  38245. return running;
  38246. };
  38247. return Animatable;
  38248. }());
  38249. BABYLON.Animatable = Animatable;
  38250. })(BABYLON || (BABYLON = {}));
  38251. //# sourceMappingURL=babylon.animatable.js.map
  38252. var BABYLON;
  38253. (function (BABYLON) {
  38254. var EasingFunction = (function () {
  38255. function EasingFunction() {
  38256. // Properties
  38257. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  38258. }
  38259. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  38260. get: function () {
  38261. return EasingFunction._EASINGMODE_EASEIN;
  38262. },
  38263. enumerable: true,
  38264. configurable: true
  38265. });
  38266. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  38267. get: function () {
  38268. return EasingFunction._EASINGMODE_EASEOUT;
  38269. },
  38270. enumerable: true,
  38271. configurable: true
  38272. });
  38273. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  38274. get: function () {
  38275. return EasingFunction._EASINGMODE_EASEINOUT;
  38276. },
  38277. enumerable: true,
  38278. configurable: true
  38279. });
  38280. EasingFunction.prototype.setEasingMode = function (easingMode) {
  38281. var n = Math.min(Math.max(easingMode, 0), 2);
  38282. this._easingMode = n;
  38283. };
  38284. EasingFunction.prototype.getEasingMode = function () {
  38285. return this._easingMode;
  38286. };
  38287. EasingFunction.prototype.easeInCore = function (gradient) {
  38288. throw new Error('You must implement this method');
  38289. };
  38290. EasingFunction.prototype.ease = function (gradient) {
  38291. switch (this._easingMode) {
  38292. case EasingFunction.EASINGMODE_EASEIN:
  38293. return this.easeInCore(gradient);
  38294. case EasingFunction.EASINGMODE_EASEOUT:
  38295. return (1 - this.easeInCore(1 - gradient));
  38296. }
  38297. if (gradient >= 0.5) {
  38298. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  38299. }
  38300. return (this.easeInCore(gradient * 2) * 0.5);
  38301. };
  38302. //Statics
  38303. EasingFunction._EASINGMODE_EASEIN = 0;
  38304. EasingFunction._EASINGMODE_EASEOUT = 1;
  38305. EasingFunction._EASINGMODE_EASEINOUT = 2;
  38306. return EasingFunction;
  38307. }());
  38308. BABYLON.EasingFunction = EasingFunction;
  38309. var CircleEase = (function (_super) {
  38310. __extends(CircleEase, _super);
  38311. function CircleEase() {
  38312. return _super !== null && _super.apply(this, arguments) || this;
  38313. }
  38314. CircleEase.prototype.easeInCore = function (gradient) {
  38315. gradient = Math.max(0, Math.min(1, gradient));
  38316. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  38317. };
  38318. return CircleEase;
  38319. }(EasingFunction));
  38320. BABYLON.CircleEase = CircleEase;
  38321. var BackEase = (function (_super) {
  38322. __extends(BackEase, _super);
  38323. function BackEase(amplitude) {
  38324. if (amplitude === void 0) { amplitude = 1; }
  38325. var _this = _super.call(this) || this;
  38326. _this.amplitude = amplitude;
  38327. return _this;
  38328. }
  38329. BackEase.prototype.easeInCore = function (gradient) {
  38330. var num = Math.max(0, this.amplitude);
  38331. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  38332. };
  38333. return BackEase;
  38334. }(EasingFunction));
  38335. BABYLON.BackEase = BackEase;
  38336. var BounceEase = (function (_super) {
  38337. __extends(BounceEase, _super);
  38338. function BounceEase(bounces, bounciness) {
  38339. if (bounces === void 0) { bounces = 3; }
  38340. if (bounciness === void 0) { bounciness = 2; }
  38341. var _this = _super.call(this) || this;
  38342. _this.bounces = bounces;
  38343. _this.bounciness = bounciness;
  38344. return _this;
  38345. }
  38346. BounceEase.prototype.easeInCore = function (gradient) {
  38347. var y = Math.max(0.0, this.bounces);
  38348. var bounciness = this.bounciness;
  38349. if (bounciness <= 1.0) {
  38350. bounciness = 1.001;
  38351. }
  38352. var num9 = Math.pow(bounciness, y);
  38353. var num5 = 1.0 - bounciness;
  38354. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  38355. var num15 = gradient * num4;
  38356. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  38357. var num3 = Math.floor(num65);
  38358. var num13 = num3 + 1.0;
  38359. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  38360. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  38361. var num7 = (num8 + num12) * 0.5;
  38362. var num6 = gradient - num7;
  38363. var num2 = num7 - num8;
  38364. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  38365. };
  38366. return BounceEase;
  38367. }(EasingFunction));
  38368. BABYLON.BounceEase = BounceEase;
  38369. var CubicEase = (function (_super) {
  38370. __extends(CubicEase, _super);
  38371. function CubicEase() {
  38372. return _super !== null && _super.apply(this, arguments) || this;
  38373. }
  38374. CubicEase.prototype.easeInCore = function (gradient) {
  38375. return (gradient * gradient * gradient);
  38376. };
  38377. return CubicEase;
  38378. }(EasingFunction));
  38379. BABYLON.CubicEase = CubicEase;
  38380. var ElasticEase = (function (_super) {
  38381. __extends(ElasticEase, _super);
  38382. function ElasticEase(oscillations, springiness) {
  38383. if (oscillations === void 0) { oscillations = 3; }
  38384. if (springiness === void 0) { springiness = 3; }
  38385. var _this = _super.call(this) || this;
  38386. _this.oscillations = oscillations;
  38387. _this.springiness = springiness;
  38388. return _this;
  38389. }
  38390. ElasticEase.prototype.easeInCore = function (gradient) {
  38391. var num2;
  38392. var num3 = Math.max(0.0, this.oscillations);
  38393. var num = Math.max(0.0, this.springiness);
  38394. if (num == 0) {
  38395. num2 = gradient;
  38396. }
  38397. else {
  38398. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  38399. }
  38400. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  38401. };
  38402. return ElasticEase;
  38403. }(EasingFunction));
  38404. BABYLON.ElasticEase = ElasticEase;
  38405. var ExponentialEase = (function (_super) {
  38406. __extends(ExponentialEase, _super);
  38407. function ExponentialEase(exponent) {
  38408. if (exponent === void 0) { exponent = 2; }
  38409. var _this = _super.call(this) || this;
  38410. _this.exponent = exponent;
  38411. return _this;
  38412. }
  38413. ExponentialEase.prototype.easeInCore = function (gradient) {
  38414. if (this.exponent <= 0) {
  38415. return gradient;
  38416. }
  38417. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  38418. };
  38419. return ExponentialEase;
  38420. }(EasingFunction));
  38421. BABYLON.ExponentialEase = ExponentialEase;
  38422. var PowerEase = (function (_super) {
  38423. __extends(PowerEase, _super);
  38424. function PowerEase(power) {
  38425. if (power === void 0) { power = 2; }
  38426. var _this = _super.call(this) || this;
  38427. _this.power = power;
  38428. return _this;
  38429. }
  38430. PowerEase.prototype.easeInCore = function (gradient) {
  38431. var y = Math.max(0.0, this.power);
  38432. return Math.pow(gradient, y);
  38433. };
  38434. return PowerEase;
  38435. }(EasingFunction));
  38436. BABYLON.PowerEase = PowerEase;
  38437. var QuadraticEase = (function (_super) {
  38438. __extends(QuadraticEase, _super);
  38439. function QuadraticEase() {
  38440. return _super !== null && _super.apply(this, arguments) || this;
  38441. }
  38442. QuadraticEase.prototype.easeInCore = function (gradient) {
  38443. return (gradient * gradient);
  38444. };
  38445. return QuadraticEase;
  38446. }(EasingFunction));
  38447. BABYLON.QuadraticEase = QuadraticEase;
  38448. var QuarticEase = (function (_super) {
  38449. __extends(QuarticEase, _super);
  38450. function QuarticEase() {
  38451. return _super !== null && _super.apply(this, arguments) || this;
  38452. }
  38453. QuarticEase.prototype.easeInCore = function (gradient) {
  38454. return (gradient * gradient * gradient * gradient);
  38455. };
  38456. return QuarticEase;
  38457. }(EasingFunction));
  38458. BABYLON.QuarticEase = QuarticEase;
  38459. var QuinticEase = (function (_super) {
  38460. __extends(QuinticEase, _super);
  38461. function QuinticEase() {
  38462. return _super !== null && _super.apply(this, arguments) || this;
  38463. }
  38464. QuinticEase.prototype.easeInCore = function (gradient) {
  38465. return (gradient * gradient * gradient * gradient * gradient);
  38466. };
  38467. return QuinticEase;
  38468. }(EasingFunction));
  38469. BABYLON.QuinticEase = QuinticEase;
  38470. var SineEase = (function (_super) {
  38471. __extends(SineEase, _super);
  38472. function SineEase() {
  38473. return _super !== null && _super.apply(this, arguments) || this;
  38474. }
  38475. SineEase.prototype.easeInCore = function (gradient) {
  38476. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  38477. };
  38478. return SineEase;
  38479. }(EasingFunction));
  38480. BABYLON.SineEase = SineEase;
  38481. var BezierCurveEase = (function (_super) {
  38482. __extends(BezierCurveEase, _super);
  38483. function BezierCurveEase(x1, y1, x2, y2) {
  38484. if (x1 === void 0) { x1 = 0; }
  38485. if (y1 === void 0) { y1 = 0; }
  38486. if (x2 === void 0) { x2 = 1; }
  38487. if (y2 === void 0) { y2 = 1; }
  38488. var _this = _super.call(this) || this;
  38489. _this.x1 = x1;
  38490. _this.y1 = y1;
  38491. _this.x2 = x2;
  38492. _this.y2 = y2;
  38493. return _this;
  38494. }
  38495. BezierCurveEase.prototype.easeInCore = function (gradient) {
  38496. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  38497. };
  38498. return BezierCurveEase;
  38499. }(EasingFunction));
  38500. BABYLON.BezierCurveEase = BezierCurveEase;
  38501. })(BABYLON || (BABYLON = {}));
  38502. //# sourceMappingURL=babylon.easing.js.map
  38503. var BABYLON;
  38504. (function (BABYLON) {
  38505. var Condition = (function () {
  38506. function Condition(actionManager) {
  38507. this._actionManager = actionManager;
  38508. }
  38509. Condition.prototype.isValid = function () {
  38510. return true;
  38511. };
  38512. Condition.prototype._getProperty = function (propertyPath) {
  38513. return this._actionManager._getProperty(propertyPath);
  38514. };
  38515. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38516. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38517. };
  38518. Condition.prototype.serialize = function () {
  38519. };
  38520. Condition.prototype._serialize = function (serializedCondition) {
  38521. return {
  38522. type: 2,
  38523. children: [],
  38524. name: serializedCondition.name,
  38525. properties: serializedCondition.properties
  38526. };
  38527. };
  38528. return Condition;
  38529. }());
  38530. BABYLON.Condition = Condition;
  38531. var ValueCondition = (function (_super) {
  38532. __extends(ValueCondition, _super);
  38533. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38534. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38535. var _this = _super.call(this, actionManager) || this;
  38536. _this.propertyPath = propertyPath;
  38537. _this.value = value;
  38538. _this.operator = operator;
  38539. _this._target = target;
  38540. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38541. _this._property = _this._getProperty(_this.propertyPath);
  38542. return _this;
  38543. }
  38544. Object.defineProperty(ValueCondition, "IsEqual", {
  38545. get: function () {
  38546. return ValueCondition._IsEqual;
  38547. },
  38548. enumerable: true,
  38549. configurable: true
  38550. });
  38551. Object.defineProperty(ValueCondition, "IsDifferent", {
  38552. get: function () {
  38553. return ValueCondition._IsDifferent;
  38554. },
  38555. enumerable: true,
  38556. configurable: true
  38557. });
  38558. Object.defineProperty(ValueCondition, "IsGreater", {
  38559. get: function () {
  38560. return ValueCondition._IsGreater;
  38561. },
  38562. enumerable: true,
  38563. configurable: true
  38564. });
  38565. Object.defineProperty(ValueCondition, "IsLesser", {
  38566. get: function () {
  38567. return ValueCondition._IsLesser;
  38568. },
  38569. enumerable: true,
  38570. configurable: true
  38571. });
  38572. // Methods
  38573. ValueCondition.prototype.isValid = function () {
  38574. switch (this.operator) {
  38575. case ValueCondition.IsGreater:
  38576. return this._effectiveTarget[this._property] > this.value;
  38577. case ValueCondition.IsLesser:
  38578. return this._effectiveTarget[this._property] < this.value;
  38579. case ValueCondition.IsEqual:
  38580. case ValueCondition.IsDifferent:
  38581. var check;
  38582. if (this.value.equals) {
  38583. check = this.value.equals(this._effectiveTarget[this._property]);
  38584. }
  38585. else {
  38586. check = this.value === this._effectiveTarget[this._property];
  38587. }
  38588. return this.operator === ValueCondition.IsEqual ? check : !check;
  38589. }
  38590. return false;
  38591. };
  38592. ValueCondition.prototype.serialize = function () {
  38593. return this._serialize({
  38594. name: "ValueCondition",
  38595. properties: [
  38596. BABYLON.Action._GetTargetProperty(this._target),
  38597. { name: "propertyPath", value: this.propertyPath },
  38598. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38599. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38600. ]
  38601. });
  38602. };
  38603. ValueCondition.GetOperatorName = function (operator) {
  38604. switch (operator) {
  38605. case ValueCondition._IsEqual: return "IsEqual";
  38606. case ValueCondition._IsDifferent: return "IsDifferent";
  38607. case ValueCondition._IsGreater: return "IsGreater";
  38608. case ValueCondition._IsLesser: return "IsLesser";
  38609. default: return "";
  38610. }
  38611. };
  38612. // Statics
  38613. ValueCondition._IsEqual = 0;
  38614. ValueCondition._IsDifferent = 1;
  38615. ValueCondition._IsGreater = 2;
  38616. ValueCondition._IsLesser = 3;
  38617. return ValueCondition;
  38618. }(Condition));
  38619. BABYLON.ValueCondition = ValueCondition;
  38620. var PredicateCondition = (function (_super) {
  38621. __extends(PredicateCondition, _super);
  38622. function PredicateCondition(actionManager, predicate) {
  38623. var _this = _super.call(this, actionManager) || this;
  38624. _this.predicate = predicate;
  38625. return _this;
  38626. }
  38627. PredicateCondition.prototype.isValid = function () {
  38628. return this.predicate();
  38629. };
  38630. return PredicateCondition;
  38631. }(Condition));
  38632. BABYLON.PredicateCondition = PredicateCondition;
  38633. var StateCondition = (function (_super) {
  38634. __extends(StateCondition, _super);
  38635. function StateCondition(actionManager, target, value) {
  38636. var _this = _super.call(this, actionManager) || this;
  38637. _this.value = value;
  38638. _this._target = target;
  38639. return _this;
  38640. }
  38641. // Methods
  38642. StateCondition.prototype.isValid = function () {
  38643. return this._target.state === this.value;
  38644. };
  38645. StateCondition.prototype.serialize = function () {
  38646. return this._serialize({
  38647. name: "StateCondition",
  38648. properties: [
  38649. BABYLON.Action._GetTargetProperty(this._target),
  38650. { name: "value", value: this.value }
  38651. ]
  38652. });
  38653. };
  38654. return StateCondition;
  38655. }(Condition));
  38656. BABYLON.StateCondition = StateCondition;
  38657. })(BABYLON || (BABYLON = {}));
  38658. //# sourceMappingURL=babylon.condition.js.map
  38659. var BABYLON;
  38660. (function (BABYLON) {
  38661. var Action = (function () {
  38662. function Action(triggerOptions, condition) {
  38663. this.triggerOptions = triggerOptions;
  38664. this.onBeforeExecuteObservable = new BABYLON.Observable();
  38665. if (triggerOptions.parameter) {
  38666. this.trigger = triggerOptions.trigger;
  38667. this._triggerParameter = triggerOptions.parameter;
  38668. }
  38669. else {
  38670. this.trigger = triggerOptions;
  38671. }
  38672. this._nextActiveAction = this;
  38673. this._condition = condition;
  38674. }
  38675. // Methods
  38676. Action.prototype._prepare = function () {
  38677. };
  38678. Action.prototype.getTriggerParameter = function () {
  38679. return this._triggerParameter;
  38680. };
  38681. Action.prototype._executeCurrent = function (evt) {
  38682. if (this._nextActiveAction._condition) {
  38683. var condition = this._nextActiveAction._condition;
  38684. var currentRenderId = this._actionManager.getScene().getRenderId();
  38685. // We cache the current evaluation for the current frame
  38686. if (condition._evaluationId === currentRenderId) {
  38687. if (!condition._currentResult) {
  38688. return;
  38689. }
  38690. }
  38691. else {
  38692. condition._evaluationId = currentRenderId;
  38693. if (!condition.isValid()) {
  38694. condition._currentResult = false;
  38695. return;
  38696. }
  38697. condition._currentResult = true;
  38698. }
  38699. }
  38700. this.onBeforeExecuteObservable.notifyObservers(this);
  38701. this._nextActiveAction.execute(evt);
  38702. this.skipToNextActiveAction();
  38703. };
  38704. Action.prototype.execute = function (evt) {
  38705. };
  38706. Action.prototype.skipToNextActiveAction = function () {
  38707. if (this._nextActiveAction._child) {
  38708. if (!this._nextActiveAction._child._actionManager) {
  38709. this._nextActiveAction._child._actionManager = this._actionManager;
  38710. }
  38711. this._nextActiveAction = this._nextActiveAction._child;
  38712. }
  38713. else {
  38714. this._nextActiveAction = this;
  38715. }
  38716. };
  38717. Action.prototype.then = function (action) {
  38718. this._child = action;
  38719. action._actionManager = this._actionManager;
  38720. action._prepare();
  38721. return action;
  38722. };
  38723. Action.prototype._getProperty = function (propertyPath) {
  38724. return this._actionManager._getProperty(propertyPath);
  38725. };
  38726. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38727. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38728. };
  38729. Action.prototype.serialize = function (parent) {
  38730. };
  38731. // Called by BABYLON.Action objects in serialize(...). Internal use
  38732. Action.prototype._serialize = function (serializedAction, parent) {
  38733. var serializationObject = {
  38734. type: 1,
  38735. children: [],
  38736. name: serializedAction.name,
  38737. properties: serializedAction.properties || []
  38738. };
  38739. // Serialize child
  38740. if (this._child) {
  38741. this._child.serialize(serializationObject);
  38742. }
  38743. // Check if "this" has a condition
  38744. if (this._condition) {
  38745. var serializedCondition = this._condition.serialize();
  38746. serializedCondition.children.push(serializationObject);
  38747. if (parent) {
  38748. parent.children.push(serializedCondition);
  38749. }
  38750. return serializedCondition;
  38751. }
  38752. if (parent) {
  38753. parent.children.push(serializationObject);
  38754. }
  38755. return serializationObject;
  38756. };
  38757. Action._SerializeValueAsString = function (value) {
  38758. if (typeof value === "number") {
  38759. return value.toString();
  38760. }
  38761. if (typeof value === "boolean") {
  38762. return value ? "true" : "false";
  38763. }
  38764. if (value instanceof BABYLON.Vector2) {
  38765. return value.x + ", " + value.y;
  38766. }
  38767. if (value instanceof BABYLON.Vector3) {
  38768. return value.x + ", " + value.y + ", " + value.z;
  38769. }
  38770. if (value instanceof BABYLON.Color3) {
  38771. return value.r + ", " + value.g + ", " + value.b;
  38772. }
  38773. if (value instanceof BABYLON.Color4) {
  38774. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38775. }
  38776. return value; // string
  38777. };
  38778. Action._GetTargetProperty = function (target) {
  38779. return {
  38780. name: "target",
  38781. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38782. : target instanceof BABYLON.Light ? "LightProperties"
  38783. : target instanceof BABYLON.Camera ? "CameraProperties"
  38784. : "SceneProperties",
  38785. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38786. };
  38787. };
  38788. return Action;
  38789. }());
  38790. BABYLON.Action = Action;
  38791. })(BABYLON || (BABYLON = {}));
  38792. //# sourceMappingURL=babylon.action.js.map
  38793. var BABYLON;
  38794. (function (BABYLON) {
  38795. /**
  38796. * ActionEvent is the event beint sent when an action is triggered.
  38797. */
  38798. var ActionEvent = (function () {
  38799. /**
  38800. * @param source The mesh or sprite that triggered the action.
  38801. * @param pointerX The X mouse cursor position at the time of the event
  38802. * @param pointerY The Y mouse cursor position at the time of the event
  38803. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38804. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38805. */
  38806. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38807. this.source = source;
  38808. this.pointerX = pointerX;
  38809. this.pointerY = pointerY;
  38810. this.meshUnderPointer = meshUnderPointer;
  38811. this.sourceEvent = sourceEvent;
  38812. this.additionalData = additionalData;
  38813. }
  38814. /**
  38815. * Helper function to auto-create an ActionEvent from a source mesh.
  38816. * @param source The source mesh that triggered the event
  38817. * @param evt {Event} The original (browser) event
  38818. */
  38819. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38820. var scene = source.getScene();
  38821. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38822. };
  38823. /**
  38824. * Helper function to auto-create an ActionEvent from a source mesh.
  38825. * @param source The source sprite that triggered the event
  38826. * @param scene Scene associated with the sprite
  38827. * @param evt {Event} The original (browser) event
  38828. */
  38829. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38830. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38831. };
  38832. /**
  38833. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38834. * @param scene the scene where the event occurred
  38835. * @param evt {Event} The original (browser) event
  38836. */
  38837. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38838. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38839. };
  38840. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38841. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38842. };
  38843. return ActionEvent;
  38844. }());
  38845. BABYLON.ActionEvent = ActionEvent;
  38846. /**
  38847. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38848. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38849. */
  38850. var ActionManager = (function () {
  38851. function ActionManager(scene) {
  38852. // Members
  38853. this.actions = new Array();
  38854. this.hoverCursor = '';
  38855. this._scene = scene;
  38856. scene._actionManagers.push(this);
  38857. }
  38858. Object.defineProperty(ActionManager, "NothingTrigger", {
  38859. get: function () {
  38860. return ActionManager._NothingTrigger;
  38861. },
  38862. enumerable: true,
  38863. configurable: true
  38864. });
  38865. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38866. get: function () {
  38867. return ActionManager._OnPickTrigger;
  38868. },
  38869. enumerable: true,
  38870. configurable: true
  38871. });
  38872. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38873. get: function () {
  38874. return ActionManager._OnLeftPickTrigger;
  38875. },
  38876. enumerable: true,
  38877. configurable: true
  38878. });
  38879. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38880. get: function () {
  38881. return ActionManager._OnRightPickTrigger;
  38882. },
  38883. enumerable: true,
  38884. configurable: true
  38885. });
  38886. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38887. get: function () {
  38888. return ActionManager._OnCenterPickTrigger;
  38889. },
  38890. enumerable: true,
  38891. configurable: true
  38892. });
  38893. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38894. get: function () {
  38895. return ActionManager._OnPickDownTrigger;
  38896. },
  38897. enumerable: true,
  38898. configurable: true
  38899. });
  38900. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  38901. get: function () {
  38902. return ActionManager._OnDoublePickTrigger;
  38903. },
  38904. enumerable: true,
  38905. configurable: true
  38906. });
  38907. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38908. get: function () {
  38909. return ActionManager._OnPickUpTrigger;
  38910. },
  38911. enumerable: true,
  38912. configurable: true
  38913. });
  38914. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38915. /// This trigger will only be raised if you also declared a OnPickDown
  38916. get: function () {
  38917. return ActionManager._OnPickOutTrigger;
  38918. },
  38919. enumerable: true,
  38920. configurable: true
  38921. });
  38922. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38923. get: function () {
  38924. return ActionManager._OnLongPressTrigger;
  38925. },
  38926. enumerable: true,
  38927. configurable: true
  38928. });
  38929. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38930. get: function () {
  38931. return ActionManager._OnPointerOverTrigger;
  38932. },
  38933. enumerable: true,
  38934. configurable: true
  38935. });
  38936. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38937. get: function () {
  38938. return ActionManager._OnPointerOutTrigger;
  38939. },
  38940. enumerable: true,
  38941. configurable: true
  38942. });
  38943. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38944. get: function () {
  38945. return ActionManager._OnEveryFrameTrigger;
  38946. },
  38947. enumerable: true,
  38948. configurable: true
  38949. });
  38950. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38951. get: function () {
  38952. return ActionManager._OnIntersectionEnterTrigger;
  38953. },
  38954. enumerable: true,
  38955. configurable: true
  38956. });
  38957. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38958. get: function () {
  38959. return ActionManager._OnIntersectionExitTrigger;
  38960. },
  38961. enumerable: true,
  38962. configurable: true
  38963. });
  38964. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38965. get: function () {
  38966. return ActionManager._OnKeyDownTrigger;
  38967. },
  38968. enumerable: true,
  38969. configurable: true
  38970. });
  38971. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38972. get: function () {
  38973. return ActionManager._OnKeyUpTrigger;
  38974. },
  38975. enumerable: true,
  38976. configurable: true
  38977. });
  38978. // Methods
  38979. ActionManager.prototype.dispose = function () {
  38980. var index = this._scene._actionManagers.indexOf(this);
  38981. for (var i = 0; i < this.actions.length; i++) {
  38982. var action = this.actions[i];
  38983. ActionManager.Triggers[action.trigger]--;
  38984. if (ActionManager.Triggers[action.trigger] === 0) {
  38985. delete ActionManager.Triggers[action.trigger];
  38986. }
  38987. }
  38988. if (index > -1) {
  38989. this._scene._actionManagers.splice(index, 1);
  38990. }
  38991. };
  38992. ActionManager.prototype.getScene = function () {
  38993. return this._scene;
  38994. };
  38995. /**
  38996. * Does this action manager handles actions of any of the given triggers
  38997. * @param {number[]} triggers - the triggers to be tested
  38998. * @return {boolean} whether one (or more) of the triggers is handeled
  38999. */
  39000. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  39001. for (var index = 0; index < this.actions.length; index++) {
  39002. var action = this.actions[index];
  39003. if (triggers.indexOf(action.trigger) > -1) {
  39004. return true;
  39005. }
  39006. }
  39007. return false;
  39008. };
  39009. /**
  39010. * Does this action manager handles actions of a given trigger
  39011. * @param {number} trigger - the trigger to be tested
  39012. * @return {boolean} whether the trigger is handeled
  39013. */
  39014. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  39015. for (var index = 0; index < this.actions.length; index++) {
  39016. var action = this.actions[index];
  39017. if (action.trigger === trigger) {
  39018. return true;
  39019. }
  39020. }
  39021. return false;
  39022. };
  39023. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  39024. /**
  39025. * Does this action manager has pointer triggers
  39026. * @return {boolean} whether or not it has pointer triggers
  39027. */
  39028. get: function () {
  39029. for (var index = 0; index < this.actions.length; index++) {
  39030. var action = this.actions[index];
  39031. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  39032. return true;
  39033. }
  39034. }
  39035. return false;
  39036. },
  39037. enumerable: true,
  39038. configurable: true
  39039. });
  39040. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  39041. /**
  39042. * Does this action manager has pick triggers
  39043. * @return {boolean} whether or not it has pick triggers
  39044. */
  39045. get: function () {
  39046. for (var index = 0; index < this.actions.length; index++) {
  39047. var action = this.actions[index];
  39048. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  39049. return true;
  39050. }
  39051. }
  39052. return false;
  39053. },
  39054. enumerable: true,
  39055. configurable: true
  39056. });
  39057. Object.defineProperty(ActionManager, "HasTriggers", {
  39058. /**
  39059. * Does exist one action manager with at least one trigger
  39060. * @return {boolean} whether or not it exists one action manager with one trigger
  39061. **/
  39062. get: function () {
  39063. for (var t in ActionManager.Triggers) {
  39064. if (ActionManager.Triggers.hasOwnProperty(t)) {
  39065. return true;
  39066. }
  39067. }
  39068. return false;
  39069. },
  39070. enumerable: true,
  39071. configurable: true
  39072. });
  39073. Object.defineProperty(ActionManager, "HasPickTriggers", {
  39074. /**
  39075. * Does exist one action manager with at least one pick trigger
  39076. * @return {boolean} whether or not it exists one action manager with one pick trigger
  39077. **/
  39078. get: function () {
  39079. for (var t in ActionManager.Triggers) {
  39080. if (ActionManager.Triggers.hasOwnProperty(t)) {
  39081. var t_int = parseInt(t);
  39082. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  39083. return true;
  39084. }
  39085. }
  39086. }
  39087. return false;
  39088. },
  39089. enumerable: true,
  39090. configurable: true
  39091. });
  39092. /**
  39093. * Does exist one action manager that handles actions of a given trigger
  39094. * @param {number} trigger - the trigger to be tested
  39095. * @return {boolean} whether the trigger is handeled by at least one action manager
  39096. **/
  39097. ActionManager.HasSpecificTrigger = function (trigger) {
  39098. for (var t in ActionManager.Triggers) {
  39099. if (ActionManager.Triggers.hasOwnProperty(t)) {
  39100. var t_int = parseInt(t);
  39101. if (t_int === trigger) {
  39102. return true;
  39103. }
  39104. }
  39105. }
  39106. return false;
  39107. };
  39108. /**
  39109. * Registers an action to this action manager
  39110. * @param {BABYLON.Action} action - the action to be registered
  39111. * @return {BABYLON.Action} the action amended (prepared) after registration
  39112. */
  39113. ActionManager.prototype.registerAction = function (action) {
  39114. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  39115. if (this.getScene().actionManager !== this) {
  39116. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  39117. return null;
  39118. }
  39119. }
  39120. this.actions.push(action);
  39121. if (ActionManager.Triggers[action.trigger]) {
  39122. ActionManager.Triggers[action.trigger]++;
  39123. }
  39124. else {
  39125. ActionManager.Triggers[action.trigger] = 1;
  39126. }
  39127. action._actionManager = this;
  39128. action._prepare();
  39129. return action;
  39130. };
  39131. /**
  39132. * Process a specific trigger
  39133. * @param {number} trigger - the trigger to process
  39134. * @param evt {BABYLON.ActionEvent} the event details to be processed
  39135. */
  39136. ActionManager.prototype.processTrigger = function (trigger, evt) {
  39137. for (var index = 0; index < this.actions.length; index++) {
  39138. var action = this.actions[index];
  39139. if (action.trigger === trigger) {
  39140. if (trigger === ActionManager.OnKeyUpTrigger
  39141. || trigger === ActionManager.OnKeyDownTrigger) {
  39142. var parameter = action.getTriggerParameter();
  39143. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  39144. if (!parameter.toLowerCase) {
  39145. continue;
  39146. }
  39147. var lowerCase = parameter.toLowerCase();
  39148. if (lowerCase !== evt.sourceEvent.key) {
  39149. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  39150. var actualkey = String.fromCharCode(unicode).toLowerCase();
  39151. if (actualkey !== lowerCase) {
  39152. continue;
  39153. }
  39154. }
  39155. }
  39156. }
  39157. action._executeCurrent(evt);
  39158. }
  39159. }
  39160. };
  39161. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  39162. var properties = propertyPath.split(".");
  39163. for (var index = 0; index < properties.length - 1; index++) {
  39164. target = target[properties[index]];
  39165. }
  39166. return target;
  39167. };
  39168. ActionManager.prototype._getProperty = function (propertyPath) {
  39169. var properties = propertyPath.split(".");
  39170. return properties[properties.length - 1];
  39171. };
  39172. ActionManager.prototype.serialize = function (name) {
  39173. var root = {
  39174. children: [],
  39175. name: name,
  39176. type: 3,
  39177. properties: [] // Empty for root but required
  39178. };
  39179. for (var i = 0; i < this.actions.length; i++) {
  39180. var triggerObject = {
  39181. type: 0,
  39182. children: [],
  39183. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  39184. properties: []
  39185. };
  39186. var triggerOptions = this.actions[i].triggerOptions;
  39187. if (triggerOptions && typeof triggerOptions !== "number") {
  39188. if (triggerOptions.parameter instanceof BABYLON.Node) {
  39189. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  39190. }
  39191. else {
  39192. var parameter = {};
  39193. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  39194. if (triggerOptions.parameter.mesh) {
  39195. parameter._meshId = triggerOptions.parameter.mesh.id;
  39196. }
  39197. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  39198. }
  39199. }
  39200. // Serialize child action, recursively
  39201. this.actions[i].serialize(triggerObject);
  39202. // Add serialized trigger
  39203. root.children.push(triggerObject);
  39204. }
  39205. return root;
  39206. };
  39207. ActionManager.Parse = function (parsedActions, object, scene) {
  39208. var actionManager = new BABYLON.ActionManager(scene);
  39209. if (object === null)
  39210. scene.actionManager = actionManager;
  39211. else
  39212. object.actionManager = actionManager;
  39213. // instanciate a new object
  39214. var instanciate = function (name, params) {
  39215. var newInstance = Object.create(BABYLON[name].prototype);
  39216. newInstance.constructor.apply(newInstance, params);
  39217. return newInstance;
  39218. };
  39219. var parseParameter = function (name, value, target, propertyPath) {
  39220. if (propertyPath === null) {
  39221. // String, boolean or float
  39222. var floatValue = parseFloat(value);
  39223. if (value === "true" || value === "false")
  39224. return value === "true";
  39225. else
  39226. return isNaN(floatValue) ? value : floatValue;
  39227. }
  39228. var effectiveTarget = propertyPath.split(".");
  39229. var values = value.split(",");
  39230. // Get effective Target
  39231. for (var i = 0; i < effectiveTarget.length; i++) {
  39232. target = target[effectiveTarget[i]];
  39233. }
  39234. // Return appropriate value with its type
  39235. if (typeof (target) === "boolean")
  39236. return values[0] === "true";
  39237. if (typeof (target) === "string")
  39238. return values[0];
  39239. // Parameters with multiple values such as Vector3 etc.
  39240. var split = new Array();
  39241. for (var i = 0; i < values.length; i++)
  39242. split.push(parseFloat(values[i]));
  39243. if (target instanceof BABYLON.Vector3)
  39244. return BABYLON.Vector3.FromArray(split);
  39245. if (target instanceof BABYLON.Vector4)
  39246. return BABYLON.Vector4.FromArray(split);
  39247. if (target instanceof BABYLON.Color3)
  39248. return BABYLON.Color3.FromArray(split);
  39249. if (target instanceof BABYLON.Color4)
  39250. return BABYLON.Color4.FromArray(split);
  39251. return parseFloat(values[0]);
  39252. };
  39253. // traverse graph per trigger
  39254. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  39255. if (combineArray === void 0) { combineArray = null; }
  39256. if (parsedAction.detached)
  39257. return;
  39258. var parameters = new Array();
  39259. var target = null;
  39260. var propertyPath = null;
  39261. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  39262. // Parameters
  39263. if (parsedAction.type === 2)
  39264. parameters.push(actionManager);
  39265. else
  39266. parameters.push(trigger);
  39267. if (combine) {
  39268. var actions = new Array();
  39269. for (var j = 0; j < parsedAction.combine.length; j++) {
  39270. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  39271. }
  39272. parameters.push(actions);
  39273. }
  39274. else {
  39275. for (var i = 0; i < parsedAction.properties.length; i++) {
  39276. var value = parsedAction.properties[i].value;
  39277. var name = parsedAction.properties[i].name;
  39278. var targetType = parsedAction.properties[i].targetType;
  39279. if (name === "target")
  39280. if (targetType !== null && targetType === "SceneProperties")
  39281. value = target = scene;
  39282. else
  39283. value = target = scene.getNodeByName(value);
  39284. else if (name === "parent")
  39285. value = scene.getNodeByName(value);
  39286. else if (name === "sound")
  39287. value = scene.getSoundByName(value);
  39288. else if (name !== "propertyPath") {
  39289. if (parsedAction.type === 2 && name === "operator")
  39290. value = BABYLON.ValueCondition[value];
  39291. else
  39292. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  39293. }
  39294. else {
  39295. propertyPath = value;
  39296. }
  39297. parameters.push(value);
  39298. }
  39299. }
  39300. if (combineArray === null) {
  39301. parameters.push(condition);
  39302. }
  39303. else {
  39304. parameters.push(null);
  39305. }
  39306. // If interpolate value action
  39307. if (parsedAction.name === "InterpolateValueAction") {
  39308. var param = parameters[parameters.length - 2];
  39309. parameters[parameters.length - 1] = param;
  39310. parameters[parameters.length - 2] = condition;
  39311. }
  39312. // Action or condition(s) and not CombineAction
  39313. var newAction = instanciate(parsedAction.name, parameters);
  39314. if (newAction instanceof BABYLON.Condition && condition !== null) {
  39315. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  39316. if (action)
  39317. action.then(nothing);
  39318. else
  39319. actionManager.registerAction(nothing);
  39320. action = nothing;
  39321. }
  39322. if (combineArray === null) {
  39323. if (newAction instanceof BABYLON.Condition) {
  39324. condition = newAction;
  39325. newAction = action;
  39326. }
  39327. else {
  39328. condition = null;
  39329. if (action)
  39330. action.then(newAction);
  39331. else
  39332. actionManager.registerAction(newAction);
  39333. }
  39334. }
  39335. else {
  39336. combineArray.push(newAction);
  39337. }
  39338. for (var i = 0; i < parsedAction.children.length; i++)
  39339. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  39340. };
  39341. // triggers
  39342. for (var i = 0; i < parsedActions.children.length; i++) {
  39343. var triggerParams;
  39344. var trigger = parsedActions.children[i];
  39345. if (trigger.properties.length > 0) {
  39346. var param = trigger.properties[0].value;
  39347. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  39348. if (value._meshId) {
  39349. value.mesh = scene.getMeshByID(value._meshId);
  39350. }
  39351. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  39352. }
  39353. else
  39354. triggerParams = BABYLON.ActionManager[trigger.name];
  39355. for (var j = 0; j < trigger.children.length; j++) {
  39356. if (!trigger.detached)
  39357. traverse(trigger.children[j], triggerParams, null, null);
  39358. }
  39359. }
  39360. };
  39361. ActionManager.GetTriggerName = function (trigger) {
  39362. switch (trigger) {
  39363. case 0: return "NothingTrigger";
  39364. case 1: return "OnPickTrigger";
  39365. case 2: return "OnLeftPickTrigger";
  39366. case 3: return "OnRightPickTrigger";
  39367. case 4: return "OnCenterPickTrigger";
  39368. case 5: return "OnPickDownTrigger";
  39369. case 6: return "OnPickUpTrigger";
  39370. case 7: return "OnLongPressTrigger";
  39371. case 8: return "OnPointerOverTrigger";
  39372. case 9: return "OnPointerOutTrigger";
  39373. case 10: return "OnEveryFrameTrigger";
  39374. case 11: return "OnIntersectionEnterTrigger";
  39375. case 12: return "OnIntersectionExitTrigger";
  39376. case 13: return "OnKeyDownTrigger";
  39377. case 14: return "OnKeyUpTrigger";
  39378. case 15: return "OnPickOutTrigger";
  39379. default: return "";
  39380. }
  39381. };
  39382. // Statics
  39383. ActionManager._NothingTrigger = 0;
  39384. ActionManager._OnPickTrigger = 1;
  39385. ActionManager._OnLeftPickTrigger = 2;
  39386. ActionManager._OnRightPickTrigger = 3;
  39387. ActionManager._OnCenterPickTrigger = 4;
  39388. ActionManager._OnPickDownTrigger = 5;
  39389. ActionManager._OnDoublePickTrigger = 6;
  39390. ActionManager._OnPickUpTrigger = 7;
  39391. ActionManager._OnLongPressTrigger = 8;
  39392. ActionManager._OnPointerOverTrigger = 9;
  39393. ActionManager._OnPointerOutTrigger = 10;
  39394. ActionManager._OnEveryFrameTrigger = 11;
  39395. ActionManager._OnIntersectionEnterTrigger = 12;
  39396. ActionManager._OnIntersectionExitTrigger = 13;
  39397. ActionManager._OnKeyDownTrigger = 14;
  39398. ActionManager._OnKeyUpTrigger = 15;
  39399. ActionManager._OnPickOutTrigger = 16;
  39400. ActionManager.Triggers = {};
  39401. return ActionManager;
  39402. }());
  39403. BABYLON.ActionManager = ActionManager;
  39404. })(BABYLON || (BABYLON = {}));
  39405. //# sourceMappingURL=babylon.actionManager.js.map
  39406. var BABYLON;
  39407. (function (BABYLON) {
  39408. var InterpolateValueAction = (function (_super) {
  39409. __extends(InterpolateValueAction, _super);
  39410. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  39411. if (duration === void 0) { duration = 1000; }
  39412. var _this = _super.call(this, triggerOptions, condition) || this;
  39413. _this.propertyPath = propertyPath;
  39414. _this.value = value;
  39415. _this.duration = duration;
  39416. _this.stopOtherAnimations = stopOtherAnimations;
  39417. _this.onInterpolationDone = onInterpolationDone;
  39418. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  39419. _this._target = _this._effectiveTarget = target;
  39420. return _this;
  39421. }
  39422. InterpolateValueAction.prototype._prepare = function () {
  39423. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39424. this._property = this._getProperty(this.propertyPath);
  39425. };
  39426. InterpolateValueAction.prototype.execute = function () {
  39427. var _this = this;
  39428. var scene = this._actionManager.getScene();
  39429. var keys = [
  39430. {
  39431. frame: 0,
  39432. value: this._effectiveTarget[this._property]
  39433. }, {
  39434. frame: 100,
  39435. value: this.value
  39436. }
  39437. ];
  39438. var dataType;
  39439. if (typeof this.value === "number") {
  39440. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  39441. }
  39442. else if (this.value instanceof BABYLON.Color3) {
  39443. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  39444. }
  39445. else if (this.value instanceof BABYLON.Vector3) {
  39446. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  39447. }
  39448. else if (this.value instanceof BABYLON.Matrix) {
  39449. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  39450. }
  39451. else if (this.value instanceof BABYLON.Quaternion) {
  39452. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  39453. }
  39454. else {
  39455. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  39456. return;
  39457. }
  39458. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39459. animation.setKeys(keys);
  39460. if (this.stopOtherAnimations) {
  39461. scene.stopAnimation(this._effectiveTarget);
  39462. }
  39463. var wrapper = function () {
  39464. _this.onInterpolationDoneObservable.notifyObservers(_this);
  39465. if (_this.onInterpolationDone) {
  39466. _this.onInterpolationDone();
  39467. }
  39468. };
  39469. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  39470. };
  39471. InterpolateValueAction.prototype.serialize = function (parent) {
  39472. return _super.prototype._serialize.call(this, {
  39473. name: "InterpolateValueAction",
  39474. properties: [
  39475. BABYLON.Action._GetTargetProperty(this._target),
  39476. { name: "propertyPath", value: this.propertyPath },
  39477. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39478. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  39479. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  39480. ]
  39481. }, parent);
  39482. };
  39483. return InterpolateValueAction;
  39484. }(BABYLON.Action));
  39485. BABYLON.InterpolateValueAction = InterpolateValueAction;
  39486. })(BABYLON || (BABYLON = {}));
  39487. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  39488. var BABYLON;
  39489. (function (BABYLON) {
  39490. var SwitchBooleanAction = (function (_super) {
  39491. __extends(SwitchBooleanAction, _super);
  39492. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  39493. var _this = _super.call(this, triggerOptions, condition) || this;
  39494. _this.propertyPath = propertyPath;
  39495. _this._target = _this._effectiveTarget = target;
  39496. return _this;
  39497. }
  39498. SwitchBooleanAction.prototype._prepare = function () {
  39499. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39500. this._property = this._getProperty(this.propertyPath);
  39501. };
  39502. SwitchBooleanAction.prototype.execute = function () {
  39503. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  39504. };
  39505. SwitchBooleanAction.prototype.serialize = function (parent) {
  39506. return _super.prototype._serialize.call(this, {
  39507. name: "SwitchBooleanAction",
  39508. properties: [
  39509. BABYLON.Action._GetTargetProperty(this._target),
  39510. { name: "propertyPath", value: this.propertyPath }
  39511. ]
  39512. }, parent);
  39513. };
  39514. return SwitchBooleanAction;
  39515. }(BABYLON.Action));
  39516. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39517. var SetStateAction = (function (_super) {
  39518. __extends(SetStateAction, _super);
  39519. function SetStateAction(triggerOptions, target, value, condition) {
  39520. var _this = _super.call(this, triggerOptions, condition) || this;
  39521. _this.value = value;
  39522. _this._target = target;
  39523. return _this;
  39524. }
  39525. SetStateAction.prototype.execute = function () {
  39526. this._target.state = this.value;
  39527. };
  39528. SetStateAction.prototype.serialize = function (parent) {
  39529. return _super.prototype._serialize.call(this, {
  39530. name: "SetStateAction",
  39531. properties: [
  39532. BABYLON.Action._GetTargetProperty(this._target),
  39533. { name: "value", value: this.value }
  39534. ]
  39535. }, parent);
  39536. };
  39537. return SetStateAction;
  39538. }(BABYLON.Action));
  39539. BABYLON.SetStateAction = SetStateAction;
  39540. var SetValueAction = (function (_super) {
  39541. __extends(SetValueAction, _super);
  39542. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39543. var _this = _super.call(this, triggerOptions, condition) || this;
  39544. _this.propertyPath = propertyPath;
  39545. _this.value = value;
  39546. _this._target = _this._effectiveTarget = target;
  39547. return _this;
  39548. }
  39549. SetValueAction.prototype._prepare = function () {
  39550. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39551. this._property = this._getProperty(this.propertyPath);
  39552. };
  39553. SetValueAction.prototype.execute = function () {
  39554. this._effectiveTarget[this._property] = this.value;
  39555. if (this._target.markAsDirty) {
  39556. this._target.markAsDirty(this._property);
  39557. }
  39558. };
  39559. SetValueAction.prototype.serialize = function (parent) {
  39560. return _super.prototype._serialize.call(this, {
  39561. name: "SetValueAction",
  39562. properties: [
  39563. BABYLON.Action._GetTargetProperty(this._target),
  39564. { name: "propertyPath", value: this.propertyPath },
  39565. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39566. ]
  39567. }, parent);
  39568. };
  39569. return SetValueAction;
  39570. }(BABYLON.Action));
  39571. BABYLON.SetValueAction = SetValueAction;
  39572. var IncrementValueAction = (function (_super) {
  39573. __extends(IncrementValueAction, _super);
  39574. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39575. var _this = _super.call(this, triggerOptions, condition) || this;
  39576. _this.propertyPath = propertyPath;
  39577. _this.value = value;
  39578. _this._target = _this._effectiveTarget = target;
  39579. return _this;
  39580. }
  39581. IncrementValueAction.prototype._prepare = function () {
  39582. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39583. this._property = this._getProperty(this.propertyPath);
  39584. if (typeof this._effectiveTarget[this._property] !== "number") {
  39585. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39586. }
  39587. };
  39588. IncrementValueAction.prototype.execute = function () {
  39589. this._effectiveTarget[this._property] += this.value;
  39590. if (this._target.markAsDirty) {
  39591. this._target.markAsDirty(this._property);
  39592. }
  39593. };
  39594. IncrementValueAction.prototype.serialize = function (parent) {
  39595. return _super.prototype._serialize.call(this, {
  39596. name: "IncrementValueAction",
  39597. properties: [
  39598. BABYLON.Action._GetTargetProperty(this._target),
  39599. { name: "propertyPath", value: this.propertyPath },
  39600. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39601. ]
  39602. }, parent);
  39603. };
  39604. return IncrementValueAction;
  39605. }(BABYLON.Action));
  39606. BABYLON.IncrementValueAction = IncrementValueAction;
  39607. var PlayAnimationAction = (function (_super) {
  39608. __extends(PlayAnimationAction, _super);
  39609. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39610. var _this = _super.call(this, triggerOptions, condition) || this;
  39611. _this.from = from;
  39612. _this.to = to;
  39613. _this.loop = loop;
  39614. _this._target = target;
  39615. return _this;
  39616. }
  39617. PlayAnimationAction.prototype._prepare = function () {
  39618. };
  39619. PlayAnimationAction.prototype.execute = function () {
  39620. var scene = this._actionManager.getScene();
  39621. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39622. };
  39623. PlayAnimationAction.prototype.serialize = function (parent) {
  39624. return _super.prototype._serialize.call(this, {
  39625. name: "PlayAnimationAction",
  39626. properties: [
  39627. BABYLON.Action._GetTargetProperty(this._target),
  39628. { name: "from", value: String(this.from) },
  39629. { name: "to", value: String(this.to) },
  39630. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39631. ]
  39632. }, parent);
  39633. };
  39634. return PlayAnimationAction;
  39635. }(BABYLON.Action));
  39636. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39637. var StopAnimationAction = (function (_super) {
  39638. __extends(StopAnimationAction, _super);
  39639. function StopAnimationAction(triggerOptions, target, condition) {
  39640. var _this = _super.call(this, triggerOptions, condition) || this;
  39641. _this._target = target;
  39642. return _this;
  39643. }
  39644. StopAnimationAction.prototype._prepare = function () {
  39645. };
  39646. StopAnimationAction.prototype.execute = function () {
  39647. var scene = this._actionManager.getScene();
  39648. scene.stopAnimation(this._target);
  39649. };
  39650. StopAnimationAction.prototype.serialize = function (parent) {
  39651. return _super.prototype._serialize.call(this, {
  39652. name: "StopAnimationAction",
  39653. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39654. }, parent);
  39655. };
  39656. return StopAnimationAction;
  39657. }(BABYLON.Action));
  39658. BABYLON.StopAnimationAction = StopAnimationAction;
  39659. var DoNothingAction = (function (_super) {
  39660. __extends(DoNothingAction, _super);
  39661. function DoNothingAction(triggerOptions, condition) {
  39662. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39663. return _super.call(this, triggerOptions, condition) || this;
  39664. }
  39665. DoNothingAction.prototype.execute = function () {
  39666. };
  39667. DoNothingAction.prototype.serialize = function (parent) {
  39668. return _super.prototype._serialize.call(this, {
  39669. name: "DoNothingAction",
  39670. properties: []
  39671. }, parent);
  39672. };
  39673. return DoNothingAction;
  39674. }(BABYLON.Action));
  39675. BABYLON.DoNothingAction = DoNothingAction;
  39676. var CombineAction = (function (_super) {
  39677. __extends(CombineAction, _super);
  39678. function CombineAction(triggerOptions, children, condition) {
  39679. var _this = _super.call(this, triggerOptions, condition) || this;
  39680. _this.children = children;
  39681. return _this;
  39682. }
  39683. CombineAction.prototype._prepare = function () {
  39684. for (var index = 0; index < this.children.length; index++) {
  39685. this.children[index]._actionManager = this._actionManager;
  39686. this.children[index]._prepare();
  39687. }
  39688. };
  39689. CombineAction.prototype.execute = function (evt) {
  39690. for (var index = 0; index < this.children.length; index++) {
  39691. this.children[index].execute(evt);
  39692. }
  39693. };
  39694. CombineAction.prototype.serialize = function (parent) {
  39695. var serializationObject = _super.prototype._serialize.call(this, {
  39696. name: "CombineAction",
  39697. properties: [],
  39698. combine: []
  39699. }, parent);
  39700. for (var i = 0; i < this.children.length; i++) {
  39701. serializationObject.combine.push(this.children[i].serialize(null));
  39702. }
  39703. return serializationObject;
  39704. };
  39705. return CombineAction;
  39706. }(BABYLON.Action));
  39707. BABYLON.CombineAction = CombineAction;
  39708. var ExecuteCodeAction = (function (_super) {
  39709. __extends(ExecuteCodeAction, _super);
  39710. function ExecuteCodeAction(triggerOptions, func, condition) {
  39711. var _this = _super.call(this, triggerOptions, condition) || this;
  39712. _this.func = func;
  39713. return _this;
  39714. }
  39715. ExecuteCodeAction.prototype.execute = function (evt) {
  39716. this.func(evt);
  39717. };
  39718. return ExecuteCodeAction;
  39719. }(BABYLON.Action));
  39720. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39721. var SetParentAction = (function (_super) {
  39722. __extends(SetParentAction, _super);
  39723. function SetParentAction(triggerOptions, target, parent, condition) {
  39724. var _this = _super.call(this, triggerOptions, condition) || this;
  39725. _this._target = target;
  39726. _this._parent = parent;
  39727. return _this;
  39728. }
  39729. SetParentAction.prototype._prepare = function () {
  39730. };
  39731. SetParentAction.prototype.execute = function () {
  39732. if (this._target.parent === this._parent) {
  39733. return;
  39734. }
  39735. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39736. invertParentWorldMatrix.invert();
  39737. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39738. this._target.parent = this._parent;
  39739. };
  39740. SetParentAction.prototype.serialize = function (parent) {
  39741. return _super.prototype._serialize.call(this, {
  39742. name: "SetParentAction",
  39743. properties: [
  39744. BABYLON.Action._GetTargetProperty(this._target),
  39745. BABYLON.Action._GetTargetProperty(this._parent),
  39746. ]
  39747. }, parent);
  39748. };
  39749. return SetParentAction;
  39750. }(BABYLON.Action));
  39751. BABYLON.SetParentAction = SetParentAction;
  39752. var PlaySoundAction = (function (_super) {
  39753. __extends(PlaySoundAction, _super);
  39754. function PlaySoundAction(triggerOptions, sound, condition) {
  39755. var _this = _super.call(this, triggerOptions, condition) || this;
  39756. _this._sound = sound;
  39757. return _this;
  39758. }
  39759. PlaySoundAction.prototype._prepare = function () {
  39760. };
  39761. PlaySoundAction.prototype.execute = function () {
  39762. if (this._sound !== undefined)
  39763. this._sound.play();
  39764. };
  39765. PlaySoundAction.prototype.serialize = function (parent) {
  39766. return _super.prototype._serialize.call(this, {
  39767. name: "PlaySoundAction",
  39768. properties: [{ name: "sound", value: this._sound.name }]
  39769. }, parent);
  39770. };
  39771. return PlaySoundAction;
  39772. }(BABYLON.Action));
  39773. BABYLON.PlaySoundAction = PlaySoundAction;
  39774. var StopSoundAction = (function (_super) {
  39775. __extends(StopSoundAction, _super);
  39776. function StopSoundAction(triggerOptions, sound, condition) {
  39777. var _this = _super.call(this, triggerOptions, condition) || this;
  39778. _this._sound = sound;
  39779. return _this;
  39780. }
  39781. StopSoundAction.prototype._prepare = function () {
  39782. };
  39783. StopSoundAction.prototype.execute = function () {
  39784. if (this._sound !== undefined)
  39785. this._sound.stop();
  39786. };
  39787. StopSoundAction.prototype.serialize = function (parent) {
  39788. return _super.prototype._serialize.call(this, {
  39789. name: "StopSoundAction",
  39790. properties: [{ name: "sound", value: this._sound.name }]
  39791. }, parent);
  39792. };
  39793. return StopSoundAction;
  39794. }(BABYLON.Action));
  39795. BABYLON.StopSoundAction = StopSoundAction;
  39796. })(BABYLON || (BABYLON = {}));
  39797. //# sourceMappingURL=babylon.directActions.js.map
  39798. var BABYLON;
  39799. (function (BABYLON) {
  39800. var SpriteManager = (function () {
  39801. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  39802. if (epsilon === void 0) { epsilon = 0.01; }
  39803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39804. this.name = name;
  39805. this.sprites = new Array();
  39806. this.renderingGroupId = 0;
  39807. this.layerMask = 0x0FFFFFFF;
  39808. this.fogEnabled = true;
  39809. this.isPickable = false;
  39810. /**
  39811. * An event triggered when the manager is disposed.
  39812. * @type {BABYLON.Observable}
  39813. */
  39814. this.onDisposeObservable = new BABYLON.Observable();
  39815. this._vertexBuffers = {};
  39816. this._capacity = capacity;
  39817. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  39818. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39819. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39820. if (cellSize.width && cellSize.height) {
  39821. this.cellWidth = cellSize.width;
  39822. this.cellHeight = cellSize.height;
  39823. }
  39824. else if (cellSize !== undefined) {
  39825. this.cellWidth = cellSize;
  39826. this.cellHeight = cellSize;
  39827. }
  39828. else {
  39829. return;
  39830. }
  39831. this._epsilon = epsilon;
  39832. this._scene = scene;
  39833. this._scene.spriteManagers.push(this);
  39834. var indices = [];
  39835. var index = 0;
  39836. for (var count = 0; count < capacity; count++) {
  39837. indices.push(index);
  39838. indices.push(index + 1);
  39839. indices.push(index + 2);
  39840. indices.push(index);
  39841. indices.push(index + 2);
  39842. indices.push(index + 3);
  39843. index += 4;
  39844. }
  39845. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39846. // VBO
  39847. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  39848. this._vertexData = new Float32Array(capacity * 16 * 4);
  39849. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  39850. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  39851. var options = this._buffer.createVertexBuffer("options", 4, 4);
  39852. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  39853. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  39854. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39855. this._vertexBuffers["options"] = options;
  39856. this._vertexBuffers["cellInfo"] = cellInfo;
  39857. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39858. // Effects
  39859. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  39860. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  39861. }
  39862. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  39863. set: function (callback) {
  39864. if (this._onDisposeObserver) {
  39865. this.onDisposeObservable.remove(this._onDisposeObserver);
  39866. }
  39867. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39868. },
  39869. enumerable: true,
  39870. configurable: true
  39871. });
  39872. Object.defineProperty(SpriteManager.prototype, "texture", {
  39873. get: function () {
  39874. return this._spriteTexture;
  39875. },
  39876. set: function (value) {
  39877. this._spriteTexture = value;
  39878. },
  39879. enumerable: true,
  39880. configurable: true
  39881. });
  39882. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  39883. var arrayOffset = index * 16;
  39884. if (offsetX === 0)
  39885. offsetX = this._epsilon;
  39886. else if (offsetX === 1)
  39887. offsetX = 1 - this._epsilon;
  39888. if (offsetY === 0)
  39889. offsetY = this._epsilon;
  39890. else if (offsetY === 1)
  39891. offsetY = 1 - this._epsilon;
  39892. this._vertexData[arrayOffset] = sprite.position.x;
  39893. this._vertexData[arrayOffset + 1] = sprite.position.y;
  39894. this._vertexData[arrayOffset + 2] = sprite.position.z;
  39895. this._vertexData[arrayOffset + 3] = sprite.angle;
  39896. this._vertexData[arrayOffset + 4] = sprite.width;
  39897. this._vertexData[arrayOffset + 5] = sprite.height;
  39898. this._vertexData[arrayOffset + 6] = offsetX;
  39899. this._vertexData[arrayOffset + 7] = offsetY;
  39900. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  39901. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  39902. var offset = (sprite.cellIndex / rowSize) >> 0;
  39903. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  39904. this._vertexData[arrayOffset + 11] = offset;
  39905. // Color
  39906. this._vertexData[arrayOffset + 12] = sprite.color.r;
  39907. this._vertexData[arrayOffset + 13] = sprite.color.g;
  39908. this._vertexData[arrayOffset + 14] = sprite.color.b;
  39909. this._vertexData[arrayOffset + 15] = sprite.color.a;
  39910. };
  39911. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  39912. var count = Math.min(this._capacity, this.sprites.length);
  39913. var min = BABYLON.Vector3.Zero();
  39914. var max = BABYLON.Vector3.Zero();
  39915. var distance = Number.MAX_VALUE;
  39916. var currentSprite;
  39917. var cameraSpacePosition = BABYLON.Vector3.Zero();
  39918. var cameraView = camera.getViewMatrix();
  39919. for (var index = 0; index < count; index++) {
  39920. var sprite = this.sprites[index];
  39921. if (!sprite) {
  39922. continue;
  39923. }
  39924. if (predicate) {
  39925. if (!predicate(sprite)) {
  39926. continue;
  39927. }
  39928. }
  39929. else if (!sprite.isPickable) {
  39930. continue;
  39931. }
  39932. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  39933. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  39934. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  39935. if (ray.intersectsBoxMinMax(min, max)) {
  39936. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  39937. if (distance > currentDistance) {
  39938. distance = currentDistance;
  39939. currentSprite = sprite;
  39940. if (fastCheck) {
  39941. break;
  39942. }
  39943. }
  39944. }
  39945. }
  39946. if (currentSprite) {
  39947. var result = new BABYLON.PickingInfo();
  39948. result.hit = true;
  39949. result.pickedSprite = currentSprite;
  39950. result.distance = distance;
  39951. return result;
  39952. }
  39953. return null;
  39954. };
  39955. SpriteManager.prototype.render = function () {
  39956. // Check
  39957. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  39958. return;
  39959. var engine = this._scene.getEngine();
  39960. var baseSize = this._spriteTexture.getBaseSize();
  39961. // Sprites
  39962. var deltaTime = engine.getDeltaTime();
  39963. var max = Math.min(this._capacity, this.sprites.length);
  39964. var rowSize = baseSize.width / this.cellWidth;
  39965. var offset = 0;
  39966. for (var index = 0; index < max; index++) {
  39967. var sprite = this.sprites[index];
  39968. if (!sprite) {
  39969. continue;
  39970. }
  39971. sprite._animate(deltaTime);
  39972. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  39973. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  39974. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  39975. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  39976. }
  39977. this._buffer.update(this._vertexData);
  39978. // Render
  39979. var effect = this._effectBase;
  39980. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39981. effect = this._effectFog;
  39982. }
  39983. engine.enableEffect(effect);
  39984. var viewMatrix = this._scene.getViewMatrix();
  39985. effect.setTexture("diffuseSampler", this._spriteTexture);
  39986. effect.setMatrix("view", viewMatrix);
  39987. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39988. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  39989. // Fog
  39990. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39991. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39992. effect.setColor3("vFogColor", this._scene.fogColor);
  39993. }
  39994. // VBOs
  39995. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39996. // Draw order
  39997. engine.setDepthFunctionToLessOrEqual();
  39998. effect.setBool("alphaTest", true);
  39999. engine.setColorWrite(false);
  40000. engine.draw(true, 0, max * 6);
  40001. engine.setColorWrite(true);
  40002. effect.setBool("alphaTest", false);
  40003. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40004. engine.draw(true, 0, max * 6);
  40005. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40006. };
  40007. SpriteManager.prototype.dispose = function () {
  40008. if (this._buffer) {
  40009. this._buffer.dispose();
  40010. this._buffer = null;
  40011. }
  40012. if (this._indexBuffer) {
  40013. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40014. this._indexBuffer = null;
  40015. }
  40016. if (this._spriteTexture) {
  40017. this._spriteTexture.dispose();
  40018. this._spriteTexture = null;
  40019. }
  40020. // Remove from scene
  40021. var index = this._scene.spriteManagers.indexOf(this);
  40022. this._scene.spriteManagers.splice(index, 1);
  40023. // Callback
  40024. this.onDisposeObservable.notifyObservers(this);
  40025. this.onDisposeObservable.clear();
  40026. };
  40027. return SpriteManager;
  40028. }());
  40029. BABYLON.SpriteManager = SpriteManager;
  40030. })(BABYLON || (BABYLON = {}));
  40031. //# sourceMappingURL=babylon.spriteManager.js.map
  40032. var BABYLON;
  40033. (function (BABYLON) {
  40034. var Sprite = (function () {
  40035. function Sprite(name, manager) {
  40036. this.name = name;
  40037. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40038. this.width = 1.0;
  40039. this.height = 1.0;
  40040. this.angle = 0;
  40041. this.cellIndex = 0;
  40042. this.invertU = 0;
  40043. this.invertV = 0;
  40044. this.animations = new Array();
  40045. this.isPickable = false;
  40046. this._animationStarted = false;
  40047. this._loopAnimation = false;
  40048. this._fromIndex = 0;
  40049. this._toIndex = 0;
  40050. this._delay = 0;
  40051. this._direction = 1;
  40052. this._frameCount = 0;
  40053. this._time = 0;
  40054. this._manager = manager;
  40055. this._manager.sprites.push(this);
  40056. this.position = BABYLON.Vector3.Zero();
  40057. }
  40058. Object.defineProperty(Sprite.prototype, "size", {
  40059. get: function () {
  40060. return this.width;
  40061. },
  40062. set: function (value) {
  40063. this.width = value;
  40064. this.height = value;
  40065. },
  40066. enumerable: true,
  40067. configurable: true
  40068. });
  40069. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  40070. this._fromIndex = from;
  40071. this._toIndex = to;
  40072. this._loopAnimation = loop;
  40073. this._delay = delay;
  40074. this._animationStarted = true;
  40075. this._direction = from < to ? 1 : -1;
  40076. this.cellIndex = from;
  40077. this._time = 0;
  40078. this._onAnimationEnd = onAnimationEnd;
  40079. };
  40080. Sprite.prototype.stopAnimation = function () {
  40081. this._animationStarted = false;
  40082. };
  40083. Sprite.prototype._animate = function (deltaTime) {
  40084. if (!this._animationStarted)
  40085. return;
  40086. this._time += deltaTime;
  40087. if (this._time > this._delay) {
  40088. this._time = this._time % this._delay;
  40089. this.cellIndex += this._direction;
  40090. if (this.cellIndex > this._toIndex) {
  40091. if (this._loopAnimation) {
  40092. this.cellIndex = this._fromIndex;
  40093. }
  40094. else {
  40095. this.cellIndex = this._toIndex;
  40096. this._animationStarted = false;
  40097. if (this._onAnimationEnd) {
  40098. this._onAnimationEnd();
  40099. }
  40100. if (this.disposeWhenFinishedAnimating) {
  40101. this.dispose();
  40102. }
  40103. }
  40104. }
  40105. }
  40106. };
  40107. Sprite.prototype.dispose = function () {
  40108. for (var i = 0; i < this._manager.sprites.length; i++) {
  40109. if (this._manager.sprites[i] == this) {
  40110. this._manager.sprites.splice(i, 1);
  40111. }
  40112. }
  40113. };
  40114. return Sprite;
  40115. }());
  40116. BABYLON.Sprite = Sprite;
  40117. })(BABYLON || (BABYLON = {}));
  40118. //# sourceMappingURL=babylon.sprite.js.map
  40119. var BABYLON;
  40120. (function (BABYLON) {
  40121. var IntersectionInfo = (function () {
  40122. function IntersectionInfo(bu, bv, distance) {
  40123. this.bu = bu;
  40124. this.bv = bv;
  40125. this.distance = distance;
  40126. this.faceId = 0;
  40127. this.subMeshId = 0;
  40128. }
  40129. return IntersectionInfo;
  40130. }());
  40131. BABYLON.IntersectionInfo = IntersectionInfo;
  40132. var PickingInfo = (function () {
  40133. function PickingInfo() {
  40134. this.hit = false;
  40135. this.distance = 0;
  40136. this.pickedPoint = null;
  40137. this.pickedMesh = null;
  40138. this.bu = 0;
  40139. this.bv = 0;
  40140. this.faceId = -1;
  40141. this.subMeshId = 0;
  40142. this.pickedSprite = null;
  40143. }
  40144. // Methods
  40145. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  40146. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  40147. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  40148. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40149. return null;
  40150. }
  40151. var indices = this.pickedMesh.getIndices();
  40152. var result;
  40153. if (useVerticesNormals) {
  40154. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40155. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  40156. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  40157. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  40158. normal0 = normal0.scale(this.bu);
  40159. normal1 = normal1.scale(this.bv);
  40160. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  40161. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  40162. }
  40163. else {
  40164. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40165. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  40166. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  40167. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  40168. var p1p2 = vertex1.subtract(vertex2);
  40169. var p3p2 = vertex3.subtract(vertex2);
  40170. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  40171. }
  40172. if (useWorldCoordinates) {
  40173. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  40174. }
  40175. return BABYLON.Vector3.Normalize(result);
  40176. };
  40177. PickingInfo.prototype.getTextureCoordinates = function () {
  40178. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40179. return null;
  40180. }
  40181. var indices = this.pickedMesh.getIndices();
  40182. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40183. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  40184. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  40185. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  40186. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  40187. uv1 = uv1.scale(this.bu);
  40188. uv2 = uv2.scale(this.bv);
  40189. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  40190. };
  40191. return PickingInfo;
  40192. }());
  40193. BABYLON.PickingInfo = PickingInfo;
  40194. })(BABYLON || (BABYLON = {}));
  40195. //# sourceMappingURL=babylon.pickingInfo.js.map
  40196. var BABYLON;
  40197. (function (BABYLON) {
  40198. var Ray = (function () {
  40199. function Ray(origin, direction, length) {
  40200. if (length === void 0) { length = Number.MAX_VALUE; }
  40201. this.origin = origin;
  40202. this.direction = direction;
  40203. this.length = length;
  40204. }
  40205. // Methods
  40206. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  40207. var d = 0.0;
  40208. var maxValue = Number.MAX_VALUE;
  40209. var inv;
  40210. var min;
  40211. var max;
  40212. var temp;
  40213. if (Math.abs(this.direction.x) < 0.0000001) {
  40214. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  40215. return false;
  40216. }
  40217. }
  40218. else {
  40219. inv = 1.0 / this.direction.x;
  40220. min = (minimum.x - this.origin.x) * inv;
  40221. max = (maximum.x - this.origin.x) * inv;
  40222. if (max === -Infinity) {
  40223. max = Infinity;
  40224. }
  40225. if (min > max) {
  40226. temp = min;
  40227. min = max;
  40228. max = temp;
  40229. }
  40230. d = Math.max(min, d);
  40231. maxValue = Math.min(max, maxValue);
  40232. if (d > maxValue) {
  40233. return false;
  40234. }
  40235. }
  40236. if (Math.abs(this.direction.y) < 0.0000001) {
  40237. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  40238. return false;
  40239. }
  40240. }
  40241. else {
  40242. inv = 1.0 / this.direction.y;
  40243. min = (minimum.y - this.origin.y) * inv;
  40244. max = (maximum.y - this.origin.y) * inv;
  40245. if (max === -Infinity) {
  40246. max = Infinity;
  40247. }
  40248. if (min > max) {
  40249. temp = min;
  40250. min = max;
  40251. max = temp;
  40252. }
  40253. d = Math.max(min, d);
  40254. maxValue = Math.min(max, maxValue);
  40255. if (d > maxValue) {
  40256. return false;
  40257. }
  40258. }
  40259. if (Math.abs(this.direction.z) < 0.0000001) {
  40260. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  40261. return false;
  40262. }
  40263. }
  40264. else {
  40265. inv = 1.0 / this.direction.z;
  40266. min = (minimum.z - this.origin.z) * inv;
  40267. max = (maximum.z - this.origin.z) * inv;
  40268. if (max === -Infinity) {
  40269. max = Infinity;
  40270. }
  40271. if (min > max) {
  40272. temp = min;
  40273. min = max;
  40274. max = temp;
  40275. }
  40276. d = Math.max(min, d);
  40277. maxValue = Math.min(max, maxValue);
  40278. if (d > maxValue) {
  40279. return false;
  40280. }
  40281. }
  40282. return true;
  40283. };
  40284. Ray.prototype.intersectsBox = function (box) {
  40285. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  40286. };
  40287. Ray.prototype.intersectsSphere = function (sphere) {
  40288. var x = sphere.center.x - this.origin.x;
  40289. var y = sphere.center.y - this.origin.y;
  40290. var z = sphere.center.z - this.origin.z;
  40291. var pyth = (x * x) + (y * y) + (z * z);
  40292. var rr = sphere.radius * sphere.radius;
  40293. if (pyth <= rr) {
  40294. return true;
  40295. }
  40296. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  40297. if (dot < 0.0) {
  40298. return false;
  40299. }
  40300. var temp = pyth - (dot * dot);
  40301. return temp <= rr;
  40302. };
  40303. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  40304. if (!this._edge1) {
  40305. this._edge1 = BABYLON.Vector3.Zero();
  40306. this._edge2 = BABYLON.Vector3.Zero();
  40307. this._pvec = BABYLON.Vector3.Zero();
  40308. this._tvec = BABYLON.Vector3.Zero();
  40309. this._qvec = BABYLON.Vector3.Zero();
  40310. }
  40311. vertex1.subtractToRef(vertex0, this._edge1);
  40312. vertex2.subtractToRef(vertex0, this._edge2);
  40313. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  40314. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  40315. if (det === 0) {
  40316. return null;
  40317. }
  40318. var invdet = 1 / det;
  40319. this.origin.subtractToRef(vertex0, this._tvec);
  40320. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  40321. if (bu < 0 || bu > 1.0) {
  40322. return null;
  40323. }
  40324. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  40325. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  40326. if (bv < 0 || bu + bv > 1.0) {
  40327. return null;
  40328. }
  40329. //check if the distance is longer than the predefined length.
  40330. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  40331. if (distance > this.length) {
  40332. return null;
  40333. }
  40334. return new BABYLON.IntersectionInfo(bu, bv, distance);
  40335. };
  40336. Ray.prototype.intersectsPlane = function (plane) {
  40337. var distance;
  40338. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  40339. if (Math.abs(result1) < 9.99999997475243E-07) {
  40340. return null;
  40341. }
  40342. else {
  40343. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  40344. distance = (-plane.d - result2) / result1;
  40345. if (distance < 0.0) {
  40346. if (distance < -9.99999997475243E-07) {
  40347. return null;
  40348. }
  40349. else {
  40350. return 0;
  40351. }
  40352. }
  40353. return distance;
  40354. }
  40355. };
  40356. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  40357. var tm = BABYLON.Tmp.Matrix[0];
  40358. mesh.getWorldMatrix().invertToRef(tm);
  40359. if (this._tmpRay) {
  40360. Ray.TransformToRef(this, tm, this._tmpRay);
  40361. }
  40362. else {
  40363. this._tmpRay = Ray.Transform(this, tm);
  40364. }
  40365. return mesh.intersects(this._tmpRay, fastCheck);
  40366. };
  40367. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  40368. if (results) {
  40369. results.length = 0;
  40370. }
  40371. else {
  40372. results = [];
  40373. }
  40374. for (var i = 0; i < meshes.length; i++) {
  40375. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  40376. if (pickInfo.hit) {
  40377. results.push(pickInfo);
  40378. }
  40379. }
  40380. results.sort(this._comparePickingInfo);
  40381. return results;
  40382. };
  40383. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  40384. if (pickingInfoA.distance < pickingInfoB.distance) {
  40385. return -1;
  40386. }
  40387. else if (pickingInfoA.distance > pickingInfoB.distance) {
  40388. return 1;
  40389. }
  40390. else {
  40391. return 0;
  40392. }
  40393. };
  40394. /**
  40395. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  40396. * @param sega the first point of the segment to test the intersection against
  40397. * @param segb the second point of the segment to test the intersection against
  40398. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  40399. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  40400. */
  40401. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  40402. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  40403. var u = segb.subtract(sega);
  40404. var v = rsegb.subtract(this.origin);
  40405. var w = sega.subtract(this.origin);
  40406. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  40407. var b = BABYLON.Vector3.Dot(u, v);
  40408. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  40409. var d = BABYLON.Vector3.Dot(u, w);
  40410. var e = BABYLON.Vector3.Dot(v, w);
  40411. var D = a * c - b * b; // always >= 0
  40412. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  40413. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  40414. // compute the line parameters of the two closest points
  40415. if (D < Ray.smallnum) {
  40416. sN = 0.0; // force using point P0 on segment S1
  40417. sD = 1.0; // to prevent possible division by 0.0 later
  40418. tN = e;
  40419. tD = c;
  40420. }
  40421. else {
  40422. sN = (b * e - c * d);
  40423. tN = (a * e - b * d);
  40424. if (sN < 0.0) {
  40425. sN = 0.0;
  40426. tN = e;
  40427. tD = c;
  40428. }
  40429. else if (sN > sD) {
  40430. sN = sD;
  40431. tN = e + b;
  40432. tD = c;
  40433. }
  40434. }
  40435. if (tN < 0.0) {
  40436. tN = 0.0;
  40437. // recompute sc for this edge
  40438. if (-d < 0.0) {
  40439. sN = 0.0;
  40440. }
  40441. else if (-d > a)
  40442. sN = sD;
  40443. else {
  40444. sN = -d;
  40445. sD = a;
  40446. }
  40447. }
  40448. else if (tN > tD) {
  40449. tN = tD;
  40450. // recompute sc for this edge
  40451. if ((-d + b) < 0.0) {
  40452. sN = 0;
  40453. }
  40454. else if ((-d + b) > a) {
  40455. sN = sD;
  40456. }
  40457. else {
  40458. sN = (-d + b);
  40459. sD = a;
  40460. }
  40461. }
  40462. // finally do the division to get sc and tc
  40463. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  40464. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  40465. // get the difference of the two closest points
  40466. var qtc = v.multiplyByFloats(tc, tc, tc);
  40467. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  40468. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  40469. if (isIntersected) {
  40470. return qtc.length();
  40471. }
  40472. return -1;
  40473. };
  40474. // Statics
  40475. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  40476. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  40477. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  40478. var direction = end.subtract(start);
  40479. direction.normalize();
  40480. return new Ray(start, direction);
  40481. };
  40482. /**
  40483. * 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
  40484. * transformed to the given world matrix.
  40485. * @param origin The origin point
  40486. * @param end The end point
  40487. * @param world a matrix to transform the ray to. Default is the identity matrix.
  40488. */
  40489. Ray.CreateNewFromTo = function (origin, end, world) {
  40490. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  40491. var direction = end.subtract(origin);
  40492. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  40493. direction.normalize();
  40494. return Ray.Transform(new Ray(origin, direction, length), world);
  40495. };
  40496. Ray.Transform = function (ray, matrix) {
  40497. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  40498. Ray.TransformToRef(ray, matrix, result);
  40499. return result;
  40500. };
  40501. Ray.TransformToRef = function (ray, matrix, result) {
  40502. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  40503. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  40504. result.length = ray.length;
  40505. var dir = result.direction;
  40506. var len = dir.length();
  40507. if (!(len === 0 || len === 1)) {
  40508. var num = 1.0 / len;
  40509. dir.x *= num;
  40510. dir.y *= num;
  40511. dir.z *= num;
  40512. result.length *= len;
  40513. }
  40514. };
  40515. Ray.smallnum = 0.00000001;
  40516. Ray.rayl = 10e8;
  40517. return Ray;
  40518. }());
  40519. BABYLON.Ray = Ray;
  40520. })(BABYLON || (BABYLON = {}));
  40521. //# sourceMappingURL=babylon.ray.js.map
  40522. var BABYLON;
  40523. (function (BABYLON) {
  40524. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  40525. if (boxMin.x > sphereCenter.x + sphereRadius)
  40526. return false;
  40527. if (sphereCenter.x - sphereRadius > boxMax.x)
  40528. return false;
  40529. if (boxMin.y > sphereCenter.y + sphereRadius)
  40530. return false;
  40531. if (sphereCenter.y - sphereRadius > boxMax.y)
  40532. return false;
  40533. if (boxMin.z > sphereCenter.z + sphereRadius)
  40534. return false;
  40535. if (sphereCenter.z - sphereRadius > boxMax.z)
  40536. return false;
  40537. return true;
  40538. };
  40539. var getLowestRoot = (function () {
  40540. var result = { root: 0, found: false };
  40541. return function (a, b, c, maxR) {
  40542. result.root = 0;
  40543. result.found = false;
  40544. var determinant = b * b - 4.0 * a * c;
  40545. if (determinant < 0)
  40546. return result;
  40547. var sqrtD = Math.sqrt(determinant);
  40548. var r1 = (-b - sqrtD) / (2.0 * a);
  40549. var r2 = (-b + sqrtD) / (2.0 * a);
  40550. if (r1 > r2) {
  40551. var temp = r2;
  40552. r2 = r1;
  40553. r1 = temp;
  40554. }
  40555. if (r1 > 0 && r1 < maxR) {
  40556. result.root = r1;
  40557. result.found = true;
  40558. return result;
  40559. }
  40560. if (r2 > 0 && r2 < maxR) {
  40561. result.root = r2;
  40562. result.found = true;
  40563. return result;
  40564. }
  40565. return result;
  40566. };
  40567. })();
  40568. var Collider = (function () {
  40569. function Collider() {
  40570. this.radius = BABYLON.Vector3.One();
  40571. this.retry = 0;
  40572. this.basePointWorld = BABYLON.Vector3.Zero();
  40573. this.velocityWorld = BABYLON.Vector3.Zero();
  40574. this.normalizedVelocity = BABYLON.Vector3.Zero();
  40575. this._collisionPoint = BABYLON.Vector3.Zero();
  40576. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  40577. this._tempVector = BABYLON.Vector3.Zero();
  40578. this._tempVector2 = BABYLON.Vector3.Zero();
  40579. this._tempVector3 = BABYLON.Vector3.Zero();
  40580. this._tempVector4 = BABYLON.Vector3.Zero();
  40581. this._edge = BABYLON.Vector3.Zero();
  40582. this._baseToVertex = BABYLON.Vector3.Zero();
  40583. this._destinationPoint = BABYLON.Vector3.Zero();
  40584. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  40585. this._displacementVector = BABYLON.Vector3.Zero();
  40586. this._collisionMask = -1;
  40587. }
  40588. Object.defineProperty(Collider.prototype, "collisionMask", {
  40589. get: function () {
  40590. return this._collisionMask;
  40591. },
  40592. set: function (mask) {
  40593. this._collisionMask = !isNaN(mask) ? mask : -1;
  40594. },
  40595. enumerable: true,
  40596. configurable: true
  40597. });
  40598. // Methods
  40599. Collider.prototype._initialize = function (source, dir, e) {
  40600. this.velocity = dir;
  40601. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  40602. this.basePoint = source;
  40603. source.multiplyToRef(this.radius, this.basePointWorld);
  40604. dir.multiplyToRef(this.radius, this.velocityWorld);
  40605. this.velocityWorldLength = this.velocityWorld.length();
  40606. this.epsilon = e;
  40607. this.collisionFound = false;
  40608. };
  40609. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  40610. pa.subtractToRef(point, this._tempVector);
  40611. pb.subtractToRef(point, this._tempVector2);
  40612. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  40613. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40614. if (d < 0)
  40615. return false;
  40616. pc.subtractToRef(point, this._tempVector3);
  40617. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  40618. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40619. if (d < 0)
  40620. return false;
  40621. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  40622. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40623. return d >= 0;
  40624. };
  40625. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  40626. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  40627. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  40628. if (distance > this.velocityWorldLength + max + sphereRadius) {
  40629. return false;
  40630. }
  40631. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  40632. return false;
  40633. return true;
  40634. };
  40635. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  40636. var t0;
  40637. var embeddedInPlane = false;
  40638. //defensive programming, actually not needed.
  40639. if (!trianglePlaneArray) {
  40640. trianglePlaneArray = [];
  40641. }
  40642. if (!trianglePlaneArray[faceIndex]) {
  40643. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  40644. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  40645. }
  40646. var trianglePlane = trianglePlaneArray[faceIndex];
  40647. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  40648. return;
  40649. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  40650. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  40651. if (normalDotVelocity == 0) {
  40652. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  40653. return;
  40654. embeddedInPlane = true;
  40655. t0 = 0;
  40656. }
  40657. else {
  40658. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40659. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40660. if (t0 > t1) {
  40661. var temp = t1;
  40662. t1 = t0;
  40663. t0 = temp;
  40664. }
  40665. if (t0 > 1.0 || t1 < 0.0)
  40666. return;
  40667. if (t0 < 0)
  40668. t0 = 0;
  40669. if (t0 > 1.0)
  40670. t0 = 1.0;
  40671. }
  40672. this._collisionPoint.copyFromFloats(0, 0, 0);
  40673. var found = false;
  40674. var t = 1.0;
  40675. if (!embeddedInPlane) {
  40676. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  40677. this.velocity.scaleToRef(t0, this._tempVector);
  40678. this._planeIntersectionPoint.addInPlace(this._tempVector);
  40679. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  40680. found = true;
  40681. t = t0;
  40682. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  40683. }
  40684. }
  40685. if (!found) {
  40686. var velocitySquaredLength = this.velocity.lengthSquared();
  40687. var a = velocitySquaredLength;
  40688. this.basePoint.subtractToRef(p1, this._tempVector);
  40689. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40690. var c = this._tempVector.lengthSquared() - 1.0;
  40691. var lowestRoot = getLowestRoot(a, b, c, t);
  40692. if (lowestRoot.found) {
  40693. t = lowestRoot.root;
  40694. found = true;
  40695. this._collisionPoint.copyFrom(p1);
  40696. }
  40697. this.basePoint.subtractToRef(p2, this._tempVector);
  40698. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40699. c = this._tempVector.lengthSquared() - 1.0;
  40700. lowestRoot = getLowestRoot(a, b, c, t);
  40701. if (lowestRoot.found) {
  40702. t = lowestRoot.root;
  40703. found = true;
  40704. this._collisionPoint.copyFrom(p2);
  40705. }
  40706. this.basePoint.subtractToRef(p3, this._tempVector);
  40707. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40708. c = this._tempVector.lengthSquared() - 1.0;
  40709. lowestRoot = getLowestRoot(a, b, c, t);
  40710. if (lowestRoot.found) {
  40711. t = lowestRoot.root;
  40712. found = true;
  40713. this._collisionPoint.copyFrom(p3);
  40714. }
  40715. p2.subtractToRef(p1, this._edge);
  40716. p1.subtractToRef(this.basePoint, this._baseToVertex);
  40717. var edgeSquaredLength = this._edge.lengthSquared();
  40718. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40719. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40720. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40721. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40722. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40723. lowestRoot = getLowestRoot(a, b, c, t);
  40724. if (lowestRoot.found) {
  40725. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40726. if (f >= 0.0 && f <= 1.0) {
  40727. t = lowestRoot.root;
  40728. found = true;
  40729. this._edge.scaleInPlace(f);
  40730. p1.addToRef(this._edge, this._collisionPoint);
  40731. }
  40732. }
  40733. p3.subtractToRef(p2, this._edge);
  40734. p2.subtractToRef(this.basePoint, this._baseToVertex);
  40735. edgeSquaredLength = this._edge.lengthSquared();
  40736. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40737. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40738. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40739. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40740. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40741. lowestRoot = getLowestRoot(a, b, c, t);
  40742. if (lowestRoot.found) {
  40743. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40744. if (f >= 0.0 && f <= 1.0) {
  40745. t = lowestRoot.root;
  40746. found = true;
  40747. this._edge.scaleInPlace(f);
  40748. p2.addToRef(this._edge, this._collisionPoint);
  40749. }
  40750. }
  40751. p1.subtractToRef(p3, this._edge);
  40752. p3.subtractToRef(this.basePoint, this._baseToVertex);
  40753. edgeSquaredLength = this._edge.lengthSquared();
  40754. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40755. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40756. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40757. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40758. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40759. lowestRoot = getLowestRoot(a, b, c, t);
  40760. if (lowestRoot.found) {
  40761. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40762. if (f >= 0.0 && f <= 1.0) {
  40763. t = lowestRoot.root;
  40764. found = true;
  40765. this._edge.scaleInPlace(f);
  40766. p3.addToRef(this._edge, this._collisionPoint);
  40767. }
  40768. }
  40769. }
  40770. if (found) {
  40771. var distToCollision = t * this.velocity.length();
  40772. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  40773. if (!this.intersectionPoint) {
  40774. this.intersectionPoint = this._collisionPoint.clone();
  40775. }
  40776. else {
  40777. this.intersectionPoint.copyFrom(this._collisionPoint);
  40778. }
  40779. this.nearestDistance = distToCollision;
  40780. this.collisionFound = true;
  40781. }
  40782. }
  40783. };
  40784. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  40785. for (var i = indexStart; i < indexEnd; i += 3) {
  40786. var p1 = pts[indices[i] - decal];
  40787. var p2 = pts[indices[i + 1] - decal];
  40788. var p3 = pts[indices[i + 2] - decal];
  40789. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  40790. }
  40791. };
  40792. Collider.prototype._getResponse = function (pos, vel) {
  40793. pos.addToRef(vel, this._destinationPoint);
  40794. vel.scaleInPlace((this.nearestDistance / vel.length()));
  40795. this.basePoint.addToRef(vel, pos);
  40796. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  40797. this._slidePlaneNormal.normalize();
  40798. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  40799. pos.addInPlace(this._displacementVector);
  40800. this.intersectionPoint.addInPlace(this._displacementVector);
  40801. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  40802. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  40803. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  40804. };
  40805. return Collider;
  40806. }());
  40807. BABYLON.Collider = Collider;
  40808. })(BABYLON || (BABYLON = {}));
  40809. //# sourceMappingURL=babylon.collider.js.map
  40810. var BABYLON;
  40811. (function (BABYLON) {
  40812. //WebWorker code will be inserted to this variable.
  40813. BABYLON.CollisionWorker = "";
  40814. var WorkerTaskType;
  40815. (function (WorkerTaskType) {
  40816. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  40817. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  40818. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  40819. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  40820. var WorkerReplyType;
  40821. (function (WorkerReplyType) {
  40822. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  40823. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  40824. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  40825. var CollisionCoordinatorWorker = (function () {
  40826. function CollisionCoordinatorWorker() {
  40827. var _this = this;
  40828. this._scaledPosition = BABYLON.Vector3.Zero();
  40829. this._scaledVelocity = BABYLON.Vector3.Zero();
  40830. this.onMeshUpdated = function (mesh) {
  40831. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  40832. };
  40833. this.onGeometryUpdated = function (geometry) {
  40834. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  40835. };
  40836. this._afterRender = function () {
  40837. if (!_this._init)
  40838. return;
  40839. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  40840. return;
  40841. }
  40842. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  40843. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  40844. if (_this._runningUpdated > 4) {
  40845. return;
  40846. }
  40847. ++_this._runningUpdated;
  40848. var payload = {
  40849. updatedMeshes: _this._addUpdateMeshesList,
  40850. updatedGeometries: _this._addUpdateGeometriesList,
  40851. removedGeometries: _this._toRemoveGeometryArray,
  40852. removedMeshes: _this._toRemoveMeshesArray
  40853. };
  40854. var message = {
  40855. payload: payload,
  40856. taskType: WorkerTaskType.UPDATE
  40857. };
  40858. var serializable = [];
  40859. for (var id in payload.updatedGeometries) {
  40860. if (payload.updatedGeometries.hasOwnProperty(id)) {
  40861. //prepare transferables
  40862. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  40863. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  40864. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  40865. }
  40866. }
  40867. _this._worker.postMessage(message, serializable);
  40868. _this._addUpdateMeshesList = {};
  40869. _this._addUpdateGeometriesList = {};
  40870. _this._toRemoveGeometryArray = [];
  40871. _this._toRemoveMeshesArray = [];
  40872. };
  40873. this._onMessageFromWorker = function (e) {
  40874. var returnData = e.data;
  40875. if (returnData.error != WorkerReplyType.SUCCESS) {
  40876. //TODO what errors can be returned from the worker?
  40877. BABYLON.Tools.Warn("error returned from worker!");
  40878. return;
  40879. }
  40880. switch (returnData.taskType) {
  40881. case WorkerTaskType.INIT:
  40882. _this._init = true;
  40883. //Update the worked with ALL of the scene's current state
  40884. _this._scene.meshes.forEach(function (mesh) {
  40885. _this.onMeshAdded(mesh);
  40886. });
  40887. _this._scene.getGeometries().forEach(function (geometry) {
  40888. _this.onGeometryAdded(geometry);
  40889. });
  40890. break;
  40891. case WorkerTaskType.UPDATE:
  40892. _this._runningUpdated--;
  40893. break;
  40894. case WorkerTaskType.COLLIDE:
  40895. _this._runningCollisionTask = false;
  40896. var returnPayload = returnData.payload;
  40897. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  40898. return;
  40899. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  40900. //cleanup
  40901. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  40902. break;
  40903. }
  40904. };
  40905. this._collisionsCallbackArray = [];
  40906. this._init = false;
  40907. this._runningUpdated = 0;
  40908. this._runningCollisionTask = false;
  40909. this._addUpdateMeshesList = {};
  40910. this._addUpdateGeometriesList = {};
  40911. this._toRemoveGeometryArray = [];
  40912. this._toRemoveMeshesArray = [];
  40913. }
  40914. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40915. if (!this._init)
  40916. return;
  40917. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  40918. return;
  40919. position.divideToRef(collider.radius, this._scaledPosition);
  40920. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40921. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  40922. var payload = {
  40923. collider: {
  40924. position: this._scaledPosition.asArray(),
  40925. velocity: this._scaledVelocity.asArray(),
  40926. radius: collider.radius.asArray()
  40927. },
  40928. collisionId: collisionIndex,
  40929. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  40930. maximumRetry: maximumRetry
  40931. };
  40932. var message = {
  40933. payload: payload,
  40934. taskType: WorkerTaskType.COLLIDE
  40935. };
  40936. this._worker.postMessage(message);
  40937. };
  40938. CollisionCoordinatorWorker.prototype.init = function (scene) {
  40939. this._scene = scene;
  40940. this._scene.registerAfterRender(this._afterRender);
  40941. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  40942. this._worker = new Worker(workerUrl);
  40943. this._worker.onmessage = this._onMessageFromWorker;
  40944. var message = {
  40945. payload: {},
  40946. taskType: WorkerTaskType.INIT
  40947. };
  40948. this._worker.postMessage(message);
  40949. };
  40950. CollisionCoordinatorWorker.prototype.destroy = function () {
  40951. this._scene.unregisterAfterRender(this._afterRender);
  40952. this._worker.terminate();
  40953. };
  40954. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  40955. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  40956. this.onMeshUpdated(mesh);
  40957. };
  40958. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  40959. this._toRemoveMeshesArray.push(mesh.uniqueId);
  40960. };
  40961. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  40962. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  40963. geometry.onGeometryUpdated = this.onGeometryUpdated;
  40964. this.onGeometryUpdated(geometry);
  40965. };
  40966. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  40967. this._toRemoveGeometryArray.push(geometry.id);
  40968. };
  40969. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  40970. var submeshes = [];
  40971. if (mesh.subMeshes) {
  40972. submeshes = mesh.subMeshes.map(function (sm, idx) {
  40973. return {
  40974. position: idx,
  40975. verticesStart: sm.verticesStart,
  40976. verticesCount: sm.verticesCount,
  40977. indexStart: sm.indexStart,
  40978. indexCount: sm.indexCount,
  40979. hasMaterial: !!sm.getMaterial(),
  40980. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40981. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  40982. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40983. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  40984. };
  40985. });
  40986. }
  40987. var geometryId = null;
  40988. if (mesh instanceof BABYLON.Mesh) {
  40989. geometryId = mesh.geometry ? mesh.geometry.id : null;
  40990. }
  40991. else if (mesh instanceof BABYLON.InstancedMesh) {
  40992. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40993. }
  40994. return {
  40995. uniqueId: mesh.uniqueId,
  40996. id: mesh.id,
  40997. name: mesh.name,
  40998. geometryId: geometryId,
  40999. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  41000. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  41001. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  41002. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  41003. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  41004. subMeshes: submeshes,
  41005. checkCollisions: mesh.checkCollisions
  41006. };
  41007. };
  41008. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  41009. return {
  41010. id: geometry.id,
  41011. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  41012. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  41013. indices: new Uint32Array(geometry.getIndices() || []),
  41014. };
  41015. };
  41016. return CollisionCoordinatorWorker;
  41017. }());
  41018. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  41019. var CollisionCoordinatorLegacy = (function () {
  41020. function CollisionCoordinatorLegacy() {
  41021. this._scaledPosition = BABYLON.Vector3.Zero();
  41022. this._scaledVelocity = BABYLON.Vector3.Zero();
  41023. this._finalPosition = BABYLON.Vector3.Zero();
  41024. }
  41025. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  41026. position.divideToRef(collider.radius, this._scaledPosition);
  41027. displacement.divideToRef(collider.radius, this._scaledVelocity);
  41028. collider.collidedMesh = null;
  41029. collider.retry = 0;
  41030. collider.initialVelocity = this._scaledVelocity;
  41031. collider.initialPosition = this._scaledPosition;
  41032. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  41033. this._finalPosition.multiplyInPlace(collider.radius);
  41034. //run the callback
  41035. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  41036. };
  41037. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  41038. this._scene = scene;
  41039. };
  41040. CollisionCoordinatorLegacy.prototype.destroy = function () {
  41041. //Legacy need no destruction method.
  41042. };
  41043. //No update in legacy mode
  41044. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  41045. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  41046. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  41047. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  41048. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  41049. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  41050. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  41051. if (excludedMesh === void 0) { excludedMesh = null; }
  41052. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  41053. if (collider.retry >= maximumRetry) {
  41054. finalPosition.copyFrom(position);
  41055. return;
  41056. }
  41057. // Check if this is a mesh else camera or -1
  41058. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  41059. collider._initialize(position, velocity, closeDistance);
  41060. // Check all meshes
  41061. for (var index = 0; index < this._scene.meshes.length; index++) {
  41062. var mesh = this._scene.meshes[index];
  41063. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  41064. mesh._checkCollision(collider);
  41065. }
  41066. }
  41067. if (!collider.collisionFound) {
  41068. position.addToRef(velocity, finalPosition);
  41069. return;
  41070. }
  41071. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  41072. collider._getResponse(position, velocity);
  41073. }
  41074. if (velocity.length() <= closeDistance) {
  41075. finalPosition.copyFrom(position);
  41076. return;
  41077. }
  41078. collider.retry++;
  41079. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  41080. };
  41081. return CollisionCoordinatorLegacy;
  41082. }());
  41083. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  41084. })(BABYLON || (BABYLON = {}));
  41085. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  41086. var BABYLON;
  41087. (function (BABYLON) {
  41088. var Particle = (function () {
  41089. function Particle(particleSystem) {
  41090. this.particleSystem = particleSystem;
  41091. this.position = BABYLON.Vector3.Zero();
  41092. this.direction = BABYLON.Vector3.Zero();
  41093. this.color = new BABYLON.Color4(0, 0, 0, 0);
  41094. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  41095. this.lifeTime = 1.0;
  41096. this.age = 0;
  41097. this.size = 0;
  41098. this.angle = 0;
  41099. this.angularSpeed = 0;
  41100. this._currentFrameCounter = 0;
  41101. this.cellIndex = 0;
  41102. if (!this.particleSystem.isAnimationSheetEnabled) {
  41103. return;
  41104. }
  41105. this.cellIndex = this.particleSystem.startSpriteCellID;
  41106. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  41107. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  41108. }
  41109. else {
  41110. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  41111. }
  41112. }
  41113. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  41114. // (ageOffset / scaledUpdateSpeed) / available cells
  41115. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  41116. this._currentFrameCounter += scaledUpdateSpeed;
  41117. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  41118. this._currentFrameCounter = 0;
  41119. this.cellIndex++;
  41120. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  41121. this.cellIndex = this.particleSystem.endSpriteCellID;
  41122. }
  41123. }
  41124. };
  41125. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  41126. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  41127. this.cellIndex++;
  41128. this._currentFrameCounter = 0;
  41129. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  41130. if (this.particleSystem.spriteCellLoop) {
  41131. this.cellIndex = this.particleSystem.startSpriteCellID;
  41132. }
  41133. else {
  41134. this.cellIndex = this.particleSystem.endSpriteCellID;
  41135. }
  41136. }
  41137. }
  41138. else {
  41139. this._currentFrameCounter++;
  41140. }
  41141. };
  41142. Particle.prototype.copyTo = function (other) {
  41143. other.position.copyFrom(this.position);
  41144. other.direction.copyFrom(this.direction);
  41145. other.color.copyFrom(this.color);
  41146. other.colorStep.copyFrom(this.colorStep);
  41147. other.lifeTime = this.lifeTime;
  41148. other.age = this.age;
  41149. other.size = this.size;
  41150. other.angle = this.angle;
  41151. other.angularSpeed = this.angularSpeed;
  41152. other.particleSystem = this.particleSystem;
  41153. other.cellIndex = this.cellIndex;
  41154. };
  41155. return Particle;
  41156. }());
  41157. BABYLON.Particle = Particle;
  41158. })(BABYLON || (BABYLON = {}));
  41159. //# sourceMappingURL=babylon.particle.js.map
  41160. var BABYLON;
  41161. (function (BABYLON) {
  41162. var randomNumber = function (min, max) {
  41163. if (min === max) {
  41164. return (min);
  41165. }
  41166. var random = Math.random();
  41167. return ((random * (max - min)) + min);
  41168. };
  41169. var ParticleSystem = (function () {
  41170. // end of sheet animation
  41171. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  41172. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  41173. if (epsilon === void 0) { epsilon = 0.01; }
  41174. var _this = this;
  41175. this.name = name;
  41176. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  41177. // Members
  41178. this.animations = [];
  41179. this.renderingGroupId = 0;
  41180. this.emitter = null;
  41181. this.emitRate = 10;
  41182. this.manualEmitCount = -1;
  41183. this.updateSpeed = 0.01;
  41184. this.targetStopDuration = 0;
  41185. this.disposeOnStop = false;
  41186. this.minEmitPower = 1;
  41187. this.maxEmitPower = 1;
  41188. this.minLifeTime = 1;
  41189. this.maxLifeTime = 1;
  41190. this.minSize = 1;
  41191. this.maxSize = 1;
  41192. this.minAngularSpeed = 0;
  41193. this.maxAngularSpeed = 0;
  41194. this.layerMask = 0x0FFFFFFF;
  41195. this.customShader = null;
  41196. this.preventAutoStart = false;
  41197. /**
  41198. * An event triggered when the system is disposed.
  41199. * @type {BABYLON.Observable}
  41200. */
  41201. this.onDisposeObservable = new BABYLON.Observable();
  41202. this.onAnimationEnd = null;
  41203. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  41204. this.forceDepthWrite = false;
  41205. this.gravity = BABYLON.Vector3.Zero();
  41206. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  41207. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  41208. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  41209. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41210. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41211. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41212. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  41213. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41214. this.particles = new Array();
  41215. this._stockParticles = new Array();
  41216. this._newPartsExcess = 0;
  41217. this._vertexBuffers = {};
  41218. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  41219. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  41220. this._scaledDirection = BABYLON.Vector3.Zero();
  41221. this._scaledGravity = BABYLON.Vector3.Zero();
  41222. this._currentRenderId = -1;
  41223. this._started = false;
  41224. this._stopped = false;
  41225. this._actualFrame = 0;
  41226. // sheet animation
  41227. this.startSpriteCellID = 0;
  41228. this.endSpriteCellID = 0;
  41229. this.spriteCellLoop = true;
  41230. this.spriteCellChangeSpeed = 0;
  41231. this.spriteCellWidth = 0;
  41232. this.spriteCellHeight = 0;
  41233. this._vertexBufferSize = 11;
  41234. this.appendParticleVertexes = null;
  41235. this.id = name;
  41236. this._capacity = capacity;
  41237. this._epsilon = epsilon;
  41238. if (_isAnimationSheetEnabled) {
  41239. this._vertexBufferSize = 12;
  41240. }
  41241. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41242. this._customEffect = customEffect;
  41243. scene.particleSystems.push(this);
  41244. this._createIndexBuffer();
  41245. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  41246. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  41247. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  41248. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  41249. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  41250. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  41251. if (this._isAnimationSheetEnabled) {
  41252. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  41253. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  41254. }
  41255. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  41256. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  41257. this._vertexBuffers["options"] = options;
  41258. // Default behaviors
  41259. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  41260. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  41261. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  41262. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  41263. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  41264. };
  41265. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  41266. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  41267. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  41268. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  41269. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  41270. };
  41271. this.updateFunction = function (particles) {
  41272. for (var index = 0; index < particles.length; index++) {
  41273. var particle = particles[index];
  41274. particle.age += _this._scaledUpdateSpeed;
  41275. if (particle.age >= particle.lifeTime) {
  41276. _this.recycleParticle(particle);
  41277. index--;
  41278. continue;
  41279. }
  41280. else {
  41281. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  41282. particle.color.addInPlace(_this._scaledColorStep);
  41283. if (particle.color.a < 0)
  41284. particle.color.a = 0;
  41285. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  41286. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  41287. particle.position.addInPlace(_this._scaledDirection);
  41288. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  41289. particle.direction.addInPlace(_this._scaledGravity);
  41290. if (_this._isAnimationSheetEnabled) {
  41291. particle.updateCellIndex(_this._scaledUpdateSpeed);
  41292. }
  41293. }
  41294. }
  41295. };
  41296. }
  41297. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  41298. set: function (callback) {
  41299. if (this._onDisposeObserver) {
  41300. this.onDisposeObservable.remove(this._onDisposeObserver);
  41301. }
  41302. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  41303. },
  41304. enumerable: true,
  41305. configurable: true
  41306. });
  41307. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  41308. get: function () {
  41309. return this._isAnimationSheetEnabled;
  41310. },
  41311. enumerable: true,
  41312. configurable: true
  41313. });
  41314. ParticleSystem.prototype._createIndexBuffer = function () {
  41315. var indices = [];
  41316. var index = 0;
  41317. for (var count = 0; count < this._capacity; count++) {
  41318. indices.push(index);
  41319. indices.push(index + 1);
  41320. indices.push(index + 2);
  41321. indices.push(index);
  41322. indices.push(index + 2);
  41323. indices.push(index + 3);
  41324. index += 4;
  41325. }
  41326. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  41327. };
  41328. ParticleSystem.prototype.recycleParticle = function (particle) {
  41329. var lastParticle = this.particles.pop();
  41330. if (lastParticle !== particle) {
  41331. lastParticle.copyTo(particle);
  41332. this._stockParticles.push(lastParticle);
  41333. }
  41334. };
  41335. ParticleSystem.prototype.getCapacity = function () {
  41336. return this._capacity;
  41337. };
  41338. ParticleSystem.prototype.isAlive = function () {
  41339. return this._alive;
  41340. };
  41341. ParticleSystem.prototype.isStarted = function () {
  41342. return this._started;
  41343. };
  41344. ParticleSystem.prototype.start = function () {
  41345. this._started = true;
  41346. this._stopped = false;
  41347. this._actualFrame = 0;
  41348. };
  41349. ParticleSystem.prototype.stop = function () {
  41350. this._stopped = true;
  41351. };
  41352. // animation sheet
  41353. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  41354. var offset = index * this._vertexBufferSize;
  41355. this._vertexData[offset] = particle.position.x;
  41356. this._vertexData[offset + 1] = particle.position.y;
  41357. this._vertexData[offset + 2] = particle.position.z;
  41358. this._vertexData[offset + 3] = particle.color.r;
  41359. this._vertexData[offset + 4] = particle.color.g;
  41360. this._vertexData[offset + 5] = particle.color.b;
  41361. this._vertexData[offset + 6] = particle.color.a;
  41362. this._vertexData[offset + 7] = particle.angle;
  41363. this._vertexData[offset + 8] = particle.size;
  41364. this._vertexData[offset + 9] = offsetX;
  41365. this._vertexData[offset + 10] = offsetY;
  41366. };
  41367. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  41368. if (offsetX === 0)
  41369. offsetX = this._epsilon;
  41370. else if (offsetX === 1)
  41371. offsetX = 1 - this._epsilon;
  41372. if (offsetY === 0)
  41373. offsetY = this._epsilon;
  41374. else if (offsetY === 1)
  41375. offsetY = 1 - this._epsilon;
  41376. var offset = index * this._vertexBufferSize;
  41377. this._vertexData[offset] = particle.position.x;
  41378. this._vertexData[offset + 1] = particle.position.y;
  41379. this._vertexData[offset + 2] = particle.position.z;
  41380. this._vertexData[offset + 3] = particle.color.r;
  41381. this._vertexData[offset + 4] = particle.color.g;
  41382. this._vertexData[offset + 5] = particle.color.b;
  41383. this._vertexData[offset + 6] = particle.color.a;
  41384. this._vertexData[offset + 7] = particle.angle;
  41385. this._vertexData[offset + 8] = particle.size;
  41386. this._vertexData[offset + 9] = offsetX;
  41387. this._vertexData[offset + 10] = offsetY;
  41388. this._vertexData[offset + 11] = particle.cellIndex;
  41389. };
  41390. ParticleSystem.prototype._update = function (newParticles) {
  41391. // Update current
  41392. this._alive = this.particles.length > 0;
  41393. this.updateFunction(this.particles);
  41394. // Add new ones
  41395. var worldMatrix;
  41396. if (this.emitter.position) {
  41397. var emitterMesh = this.emitter;
  41398. worldMatrix = emitterMesh.getWorldMatrix();
  41399. }
  41400. else {
  41401. var emitterPosition = this.emitter;
  41402. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  41403. }
  41404. var particle;
  41405. for (var index = 0; index < newParticles; index++) {
  41406. if (this.particles.length === this._capacity) {
  41407. break;
  41408. }
  41409. if (this._stockParticles.length !== 0) {
  41410. particle = this._stockParticles.pop();
  41411. particle.age = 0;
  41412. particle.cellIndex = this.startSpriteCellID;
  41413. }
  41414. else {
  41415. particle = new BABYLON.Particle(this);
  41416. }
  41417. this.particles.push(particle);
  41418. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  41419. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  41420. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  41421. particle.size = randomNumber(this.minSize, this.maxSize);
  41422. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  41423. this.startPositionFunction(worldMatrix, particle.position, particle);
  41424. var step = randomNumber(0, 1.0);
  41425. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  41426. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  41427. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  41428. }
  41429. };
  41430. ParticleSystem.prototype._getEffect = function () {
  41431. if (this._customEffect) {
  41432. return this._customEffect;
  41433. }
  41434. ;
  41435. var defines = [];
  41436. if (this._scene.clipPlane) {
  41437. defines.push("#define CLIPPLANE");
  41438. }
  41439. if (this._isAnimationSheetEnabled) {
  41440. defines.push("#define ANIMATESHEET");
  41441. }
  41442. // Effect
  41443. var join = defines.join("\n");
  41444. if (this._cachedDefines !== join) {
  41445. this._cachedDefines = join;
  41446. var attributesNamesOrOptions;
  41447. var effectCreationOption;
  41448. if (this._isAnimationSheetEnabled) {
  41449. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  41450. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  41451. }
  41452. else {
  41453. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  41454. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  41455. }
  41456. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  41457. }
  41458. return this._effect;
  41459. };
  41460. ParticleSystem.prototype.animate = function () {
  41461. if (!this._started)
  41462. return;
  41463. var effect = this._getEffect();
  41464. // Check
  41465. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  41466. return;
  41467. if (this._currentRenderId === this._scene.getRenderId()) {
  41468. return;
  41469. }
  41470. this._currentRenderId = this._scene.getRenderId();
  41471. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  41472. // determine the number of particles we need to create
  41473. var newParticles;
  41474. if (this.manualEmitCount > -1) {
  41475. newParticles = this.manualEmitCount;
  41476. this._newPartsExcess = 0;
  41477. this.manualEmitCount = 0;
  41478. }
  41479. else {
  41480. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  41481. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  41482. }
  41483. if (this._newPartsExcess > 1.0) {
  41484. newParticles += this._newPartsExcess >> 0;
  41485. this._newPartsExcess -= this._newPartsExcess >> 0;
  41486. }
  41487. this._alive = false;
  41488. if (!this._stopped) {
  41489. this._actualFrame += this._scaledUpdateSpeed;
  41490. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  41491. this.stop();
  41492. }
  41493. else {
  41494. newParticles = 0;
  41495. }
  41496. this._update(newParticles);
  41497. // Stopped?
  41498. if (this._stopped) {
  41499. if (!this._alive) {
  41500. this._started = false;
  41501. if (this.onAnimationEnd) {
  41502. this.onAnimationEnd();
  41503. }
  41504. if (this.disposeOnStop) {
  41505. this._scene._toBeDisposed.push(this);
  41506. }
  41507. }
  41508. }
  41509. // Animation sheet
  41510. if (this._isAnimationSheetEnabled) {
  41511. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  41512. }
  41513. else {
  41514. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  41515. }
  41516. // Update VBO
  41517. var offset = 0;
  41518. for (var index = 0; index < this.particles.length; index++) {
  41519. var particle = this.particles[index];
  41520. this.appendParticleVertexes(offset, particle);
  41521. offset += 4;
  41522. }
  41523. this._vertexBuffer.update(this._vertexData);
  41524. };
  41525. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  41526. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  41527. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  41528. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  41529. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  41530. };
  41531. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  41532. this._appendParticleVertex(offset++, particle, 0, 0);
  41533. this._appendParticleVertex(offset++, particle, 1, 0);
  41534. this._appendParticleVertex(offset++, particle, 1, 1);
  41535. this._appendParticleVertex(offset++, particle, 0, 1);
  41536. };
  41537. ParticleSystem.prototype.rebuild = function () {
  41538. this._createIndexBuffer();
  41539. this._vertexBuffer._rebuild();
  41540. };
  41541. ParticleSystem.prototype.render = function () {
  41542. var effect = this._getEffect();
  41543. // Check
  41544. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  41545. return 0;
  41546. var engine = this._scene.getEngine();
  41547. // Render
  41548. engine.enableEffect(effect);
  41549. engine.setState(false);
  41550. var viewMatrix = this._scene.getViewMatrix();
  41551. effect.setTexture("diffuseSampler", this.particleTexture);
  41552. effect.setMatrix("view", viewMatrix);
  41553. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  41554. if (this._isAnimationSheetEnabled) {
  41555. var baseSize = this.particleTexture.getBaseSize();
  41556. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  41557. }
  41558. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  41559. if (this._scene.clipPlane) {
  41560. var clipPlane = this._scene.clipPlane;
  41561. var invView = viewMatrix.clone();
  41562. invView.invert();
  41563. effect.setMatrix("invView", invView);
  41564. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41565. }
  41566. // VBOs
  41567. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41568. // Draw order
  41569. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  41570. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  41571. }
  41572. else {
  41573. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41574. }
  41575. if (this.forceDepthWrite) {
  41576. engine.setDepthWrite(true);
  41577. }
  41578. engine.draw(true, 0, this.particles.length * 6);
  41579. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41580. return this.particles.length;
  41581. };
  41582. ParticleSystem.prototype.dispose = function () {
  41583. if (this._vertexBuffer) {
  41584. this._vertexBuffer.dispose();
  41585. this._vertexBuffer = null;
  41586. }
  41587. if (this._indexBuffer) {
  41588. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41589. this._indexBuffer = null;
  41590. }
  41591. if (this.particleTexture) {
  41592. this.particleTexture.dispose();
  41593. this.particleTexture = null;
  41594. }
  41595. // Remove from scene
  41596. var index = this._scene.particleSystems.indexOf(this);
  41597. if (index > -1) {
  41598. this._scene.particleSystems.splice(index, 1);
  41599. }
  41600. // Callback
  41601. this.onDisposeObservable.notifyObservers(this);
  41602. this.onDisposeObservable.clear();
  41603. };
  41604. // Clone
  41605. ParticleSystem.prototype.clone = function (name, newEmitter) {
  41606. var custom = null;
  41607. var program = null;
  41608. if (this.customShader != null) {
  41609. program = this.customShader;
  41610. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41611. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41612. }
  41613. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  41614. result.customShader = program;
  41615. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  41616. if (newEmitter === undefined) {
  41617. newEmitter = this.emitter;
  41618. }
  41619. result.emitter = newEmitter;
  41620. if (this.particleTexture) {
  41621. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  41622. }
  41623. if (!this.preventAutoStart) {
  41624. result.start();
  41625. }
  41626. return result;
  41627. };
  41628. ParticleSystem.prototype.serialize = function () {
  41629. var serializationObject = {};
  41630. serializationObject.name = this.name;
  41631. serializationObject.id = this.id;
  41632. // Emitter
  41633. if (this.emitter.position) {
  41634. var emitterMesh = this.emitter;
  41635. serializationObject.emitterId = emitterMesh.id;
  41636. }
  41637. else {
  41638. var emitterPosition = this.emitter;
  41639. serializationObject.emitter = emitterPosition.asArray();
  41640. }
  41641. serializationObject.capacity = this.getCapacity();
  41642. if (this.particleTexture) {
  41643. serializationObject.textureName = this.particleTexture.name;
  41644. }
  41645. // Animations
  41646. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  41647. // Particle system
  41648. serializationObject.minAngularSpeed = this.minAngularSpeed;
  41649. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  41650. serializationObject.minSize = this.minSize;
  41651. serializationObject.maxSize = this.maxSize;
  41652. serializationObject.minEmitPower = this.minEmitPower;
  41653. serializationObject.maxEmitPower = this.maxEmitPower;
  41654. serializationObject.minLifeTime = this.minLifeTime;
  41655. serializationObject.maxLifeTime = this.maxLifeTime;
  41656. serializationObject.emitRate = this.emitRate;
  41657. serializationObject.minEmitBox = this.minEmitBox.asArray();
  41658. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  41659. serializationObject.gravity = this.gravity.asArray();
  41660. serializationObject.direction1 = this.direction1.asArray();
  41661. serializationObject.direction2 = this.direction2.asArray();
  41662. serializationObject.color1 = this.color1.asArray();
  41663. serializationObject.color2 = this.color2.asArray();
  41664. serializationObject.colorDead = this.colorDead.asArray();
  41665. serializationObject.updateSpeed = this.updateSpeed;
  41666. serializationObject.targetStopDuration = this.targetStopDuration;
  41667. serializationObject.textureMask = this.textureMask.asArray();
  41668. serializationObject.blendMode = this.blendMode;
  41669. serializationObject.customShader = this.customShader;
  41670. serializationObject.preventAutoStart = this.preventAutoStart;
  41671. return serializationObject;
  41672. };
  41673. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  41674. var name = parsedParticleSystem.name;
  41675. var custom = null;
  41676. var program = null;
  41677. if (parsedParticleSystem.customShader) {
  41678. program = parsedParticleSystem.customShader;
  41679. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41680. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41681. }
  41682. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  41683. particleSystem.customShader = program;
  41684. if (parsedParticleSystem.id) {
  41685. particleSystem.id = parsedParticleSystem.id;
  41686. }
  41687. // Auto start
  41688. if (parsedParticleSystem.preventAutoStart) {
  41689. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  41690. }
  41691. // Texture
  41692. if (parsedParticleSystem.textureName) {
  41693. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  41694. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  41695. }
  41696. // Emitter
  41697. if (parsedParticleSystem.emitterId) {
  41698. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  41699. }
  41700. else {
  41701. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  41702. }
  41703. // Animations
  41704. if (parsedParticleSystem.animations) {
  41705. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  41706. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  41707. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  41708. }
  41709. }
  41710. if (parsedParticleSystem.autoAnimate) {
  41711. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  41712. }
  41713. // Particle system
  41714. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  41715. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  41716. particleSystem.minSize = parsedParticleSystem.minSize;
  41717. particleSystem.maxSize = parsedParticleSystem.maxSize;
  41718. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  41719. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  41720. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  41721. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  41722. particleSystem.emitRate = parsedParticleSystem.emitRate;
  41723. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  41724. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  41725. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  41726. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  41727. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  41728. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  41729. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  41730. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  41731. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  41732. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  41733. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  41734. particleSystem.blendMode = parsedParticleSystem.blendMode;
  41735. if (!particleSystem.preventAutoStart) {
  41736. particleSystem.start();
  41737. }
  41738. return particleSystem;
  41739. };
  41740. // Statics
  41741. ParticleSystem.BLENDMODE_ONEONE = 0;
  41742. ParticleSystem.BLENDMODE_STANDARD = 1;
  41743. return ParticleSystem;
  41744. }());
  41745. BABYLON.ParticleSystem = ParticleSystem;
  41746. })(BABYLON || (BABYLON = {}));
  41747. //# sourceMappingURL=babylon.particleSystem.js.map
  41748. var BABYLON;
  41749. (function (BABYLON) {
  41750. var SolidParticle = (function () {
  41751. /**
  41752. * Creates a Solid Particle object.
  41753. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  41754. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  41755. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  41756. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  41757. * `shapeId` (integer) is the model shape identifier in the SPS.
  41758. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  41759. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  41760. */
  41761. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  41762. this.idx = 0; // particle global index
  41763. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  41764. this.position = BABYLON.Vector3.Zero(); // position
  41765. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41766. this.scaling = BABYLON.Vector3.One(); // scaling
  41767. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  41768. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41769. this.alive = true; // alive
  41770. this.isVisible = true; // visibility
  41771. this._pos = 0; // index of this particle in the global "positions" array
  41772. this.shapeId = 0; // model shape id
  41773. this.idxInShape = 0; // index of the particle in its shape id
  41774. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  41775. this.idx = particleIndex;
  41776. this._pos = positionIndex;
  41777. this._model = model;
  41778. this.shapeId = shapeId;
  41779. this.idxInShape = idxInShape;
  41780. this._sps = sps;
  41781. if (modelBoundingInfo) {
  41782. this._modelBoundingInfo = modelBoundingInfo;
  41783. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  41784. }
  41785. }
  41786. Object.defineProperty(SolidParticle.prototype, "scale", {
  41787. /**
  41788. * legacy support, changed scale to scaling
  41789. */
  41790. get: function () {
  41791. return this.scaling;
  41792. },
  41793. set: function (scale) {
  41794. this.scaling = scale;
  41795. },
  41796. enumerable: true,
  41797. configurable: true
  41798. });
  41799. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41800. /**
  41801. * legacy support, changed quaternion to rotationQuaternion
  41802. */
  41803. get: function () {
  41804. return this.rotationQuaternion;
  41805. },
  41806. set: function (q) {
  41807. this.rotationQuaternion = q;
  41808. },
  41809. enumerable: true,
  41810. configurable: true
  41811. });
  41812. /**
  41813. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  41814. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  41815. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  41816. */
  41817. SolidParticle.prototype.intersectsMesh = function (target) {
  41818. if (!this._boundingInfo || !target._boundingInfo) {
  41819. return false;
  41820. }
  41821. if (this._sps._bSphereOnly) {
  41822. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  41823. }
  41824. return this._boundingInfo.intersects(target._boundingInfo, false);
  41825. };
  41826. return SolidParticle;
  41827. }());
  41828. BABYLON.SolidParticle = SolidParticle;
  41829. var ModelShape = (function () {
  41830. /**
  41831. * 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.
  41832. * SPS internal tool, don't use it manually.
  41833. */
  41834. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41835. this.shapeID = id;
  41836. this._shape = shape;
  41837. this._shapeUV = shapeUV;
  41838. this._positionFunction = posFunction;
  41839. this._vertexFunction = vtxFunction;
  41840. }
  41841. return ModelShape;
  41842. }());
  41843. BABYLON.ModelShape = ModelShape;
  41844. })(BABYLON || (BABYLON = {}));
  41845. //# sourceMappingURL=babylon.solidParticle.js.map
  41846. var BABYLON;
  41847. (function (BABYLON) {
  41848. /**
  41849. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  41850. */
  41851. var SolidParticleSystem = (function () {
  41852. /**
  41853. * Creates a SPS (Solid Particle System) object.
  41854. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41855. * `scene` (Scene) is the scene in which the SPS is added.
  41856. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  41857. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  41858. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  41859. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  41860. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  41861. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  41862. */
  41863. function SolidParticleSystem(name, scene, options) {
  41864. // public members
  41865. /**
  41866. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41867. * Example : var p = SPS.particles[i];
  41868. */
  41869. this.particles = new Array();
  41870. /**
  41871. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41872. */
  41873. this.nbParticles = 0;
  41874. /**
  41875. * If the particles must ever face the camera (default false). Useful for planar particles.
  41876. */
  41877. this.billboard = false;
  41878. /**
  41879. * Recompute normals when adding a shape
  41880. */
  41881. this.recomputeNormals = true;
  41882. /**
  41883. * This a counter ofr your own usage. It's not set by any SPS functions.
  41884. */
  41885. this.counter = 0;
  41886. /**
  41887. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41888. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  41889. */
  41890. this.vars = {};
  41891. this._positions = new Array();
  41892. this._indices = new Array();
  41893. this._normals = new Array();
  41894. this._colors = new Array();
  41895. this._uvs = new Array();
  41896. this._index = 0; // indices index
  41897. this._updatable = true;
  41898. this._pickable = false;
  41899. this._isVisibilityBoxLocked = false;
  41900. this._alwaysVisible = false;
  41901. this._shapeCounter = 0;
  41902. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  41903. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41904. this._computeParticleColor = true;
  41905. this._computeParticleTexture = true;
  41906. this._computeParticleRotation = true;
  41907. this._computeParticleVertex = false;
  41908. this._computeBoundingBox = false;
  41909. this._cam_axisZ = BABYLON.Vector3.Zero();
  41910. this._cam_axisY = BABYLON.Vector3.Zero();
  41911. this._cam_axisX = BABYLON.Vector3.Zero();
  41912. this._axisX = BABYLON.Axis.X;
  41913. this._axisY = BABYLON.Axis.Y;
  41914. this._axisZ = BABYLON.Axis.Z;
  41915. this._camDir = BABYLON.Vector3.Zero();
  41916. this._rotMatrix = new BABYLON.Matrix();
  41917. this._invertMatrix = new BABYLON.Matrix();
  41918. this._rotated = BABYLON.Vector3.Zero();
  41919. this._quaternion = new BABYLON.Quaternion();
  41920. this._vertex = BABYLON.Vector3.Zero();
  41921. this._normal = BABYLON.Vector3.Zero();
  41922. this._yaw = 0.0;
  41923. this._pitch = 0.0;
  41924. this._roll = 0.0;
  41925. this._halfroll = 0.0;
  41926. this._halfpitch = 0.0;
  41927. this._halfyaw = 0.0;
  41928. this._sinRoll = 0.0;
  41929. this._cosRoll = 0.0;
  41930. this._sinPitch = 0.0;
  41931. this._cosPitch = 0.0;
  41932. this._sinYaw = 0.0;
  41933. this._cosYaw = 0.0;
  41934. this._mustUnrotateFixedNormals = false;
  41935. this._minimum = BABYLON.Tmp.Vector3[0];
  41936. this._maximum = BABYLON.Tmp.Vector3[1];
  41937. this._scale = BABYLON.Tmp.Vector3[2];
  41938. this._translation = BABYLON.Tmp.Vector3[3];
  41939. this._minBbox = BABYLON.Tmp.Vector3[4];
  41940. this._maxBbox = BABYLON.Tmp.Vector3[5];
  41941. this._particlesIntersect = false;
  41942. this._bSphereOnly = false;
  41943. this._bSphereRadiusFactor = 1.0;
  41944. this.name = name;
  41945. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41946. this._camera = scene.activeCamera;
  41947. this._pickable = options ? options.isPickable : false;
  41948. this._particlesIntersect = options ? options.particleIntersection : false;
  41949. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  41950. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  41951. if (options && options.updatable) {
  41952. this._updatable = options.updatable;
  41953. }
  41954. else {
  41955. this._updatable = true;
  41956. }
  41957. if (this._pickable) {
  41958. this.pickedParticles = [];
  41959. }
  41960. }
  41961. /**
  41962. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41963. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41964. */
  41965. SolidParticleSystem.prototype.buildMesh = function () {
  41966. if (this.nbParticles === 0) {
  41967. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41968. this.addShape(triangle, 1);
  41969. triangle.dispose();
  41970. }
  41971. this._positions32 = new Float32Array(this._positions);
  41972. this._uvs32 = new Float32Array(this._uvs);
  41973. this._colors32 = new Float32Array(this._colors);
  41974. if (this.recomputeNormals) {
  41975. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41976. }
  41977. this._normals32 = new Float32Array(this._normals);
  41978. this._fixedNormal32 = new Float32Array(this._normals);
  41979. if (this._mustUnrotateFixedNormals) {
  41980. this._unrotateFixedNormals();
  41981. }
  41982. var vertexData = new BABYLON.VertexData();
  41983. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41984. vertexData.indices = this._indices;
  41985. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41986. if (this._uvs32) {
  41987. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41988. ;
  41989. }
  41990. if (this._colors32) {
  41991. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41992. }
  41993. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41994. vertexData.applyToMesh(mesh, this._updatable);
  41995. this.mesh = mesh;
  41996. this.mesh.isPickable = this._pickable;
  41997. // free memory
  41998. this._positions = null;
  41999. this._normals = null;
  42000. this._uvs = null;
  42001. this._colors = null;
  42002. if (!this._updatable) {
  42003. this.particles.length = 0;
  42004. }
  42005. return mesh;
  42006. };
  42007. /**
  42008. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  42009. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  42010. * Thus the particles generated from `digest()` have their property `position` set yet.
  42011. * `mesh` ( Mesh ) is the mesh to be digested
  42012. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  42013. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  42014. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  42015. */
  42016. SolidParticleSystem.prototype.digest = function (mesh, options) {
  42017. var size = (options && options.facetNb) || 1;
  42018. var number = (options && options.number);
  42019. var delta = (options && options.delta) || 0;
  42020. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42021. var meshInd = mesh.getIndices();
  42022. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42023. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42024. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42025. var f = 0; // facet counter
  42026. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  42027. // compute size from number
  42028. if (number) {
  42029. number = (number > totalFacets) ? totalFacets : number;
  42030. size = Math.round(totalFacets / number);
  42031. delta = 0;
  42032. }
  42033. else {
  42034. size = (size > totalFacets) ? totalFacets : size;
  42035. }
  42036. var facetPos = []; // submesh positions
  42037. var facetInd = []; // submesh indices
  42038. var facetUV = []; // submesh UV
  42039. var facetCol = []; // submesh colors
  42040. var barycenter = BABYLON.Tmp.Vector3[0];
  42041. var rand;
  42042. var sizeO = size;
  42043. while (f < totalFacets) {
  42044. size = sizeO + Math.floor((1 + delta) * Math.random());
  42045. if (f > totalFacets - size) {
  42046. size = totalFacets - f;
  42047. }
  42048. // reset temp arrays
  42049. facetPos.length = 0;
  42050. facetInd.length = 0;
  42051. facetUV.length = 0;
  42052. facetCol.length = 0;
  42053. // iterate over "size" facets
  42054. var fi = 0;
  42055. for (var j = f * 3; j < (f + size) * 3; j++) {
  42056. facetInd.push(fi);
  42057. var i = meshInd[j];
  42058. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  42059. if (meshUV) {
  42060. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  42061. }
  42062. if (meshCol) {
  42063. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  42064. }
  42065. fi++;
  42066. }
  42067. // create a model shape for each single particle
  42068. var idx = this.nbParticles;
  42069. var shape = this._posToShape(facetPos);
  42070. var shapeUV = this._uvsToShapeUV(facetUV);
  42071. // compute the barycenter of the shape
  42072. var v;
  42073. for (v = 0; v < shape.length; v++) {
  42074. barycenter.addInPlace(shape[v]);
  42075. }
  42076. barycenter.scaleInPlace(1 / shape.length);
  42077. // shift the shape from its barycenter to the origin
  42078. for (v = 0; v < shape.length; v++) {
  42079. shape[v].subtractInPlace(barycenter);
  42080. }
  42081. var bInfo;
  42082. if (this._particlesIntersect) {
  42083. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  42084. }
  42085. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  42086. // add the particle in the SPS
  42087. var currentPos = this._positions.length;
  42088. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  42089. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  42090. // initialize the particle position
  42091. this.particles[this.nbParticles].position.addInPlace(barycenter);
  42092. this._index += shape.length;
  42093. idx++;
  42094. this.nbParticles++;
  42095. this._shapeCounter++;
  42096. f += size;
  42097. }
  42098. return this;
  42099. };
  42100. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  42101. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  42102. var index = 0;
  42103. var idx = 0;
  42104. for (var p = 0; p < this.particles.length; p++) {
  42105. this._particle = this.particles[p];
  42106. this._shape = this._particle._model._shape;
  42107. if (this._particle.rotationQuaternion) {
  42108. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42109. }
  42110. else {
  42111. this._yaw = this._particle.rotation.y;
  42112. this._pitch = this._particle.rotation.x;
  42113. this._roll = this._particle.rotation.z;
  42114. this._quaternionRotationYPR();
  42115. }
  42116. this._quaternionToRotationMatrix();
  42117. this._rotMatrix.invertToRef(this._invertMatrix);
  42118. for (var pt = 0; pt < this._shape.length; pt++) {
  42119. idx = index + pt * 3;
  42120. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  42121. this._fixedNormal32[idx] = this._normal.x;
  42122. this._fixedNormal32[idx + 1] = this._normal.y;
  42123. this._fixedNormal32[idx + 2] = this._normal.z;
  42124. }
  42125. index = idx + 3;
  42126. }
  42127. };
  42128. //reset copy
  42129. SolidParticleSystem.prototype._resetCopy = function () {
  42130. this._copy.position.x = 0;
  42131. this._copy.position.y = 0;
  42132. this._copy.position.z = 0;
  42133. this._copy.rotation.x = 0;
  42134. this._copy.rotation.y = 0;
  42135. this._copy.rotation.z = 0;
  42136. this._copy.rotationQuaternion = null;
  42137. this._copy.scaling.x = 1;
  42138. this._copy.scaling.y = 1;
  42139. this._copy.scaling.z = 1;
  42140. this._copy.uvs.x = 0;
  42141. this._copy.uvs.y = 0;
  42142. this._copy.uvs.z = 1;
  42143. this._copy.uvs.w = 1;
  42144. this._copy.color = null;
  42145. };
  42146. // _meshBuilder : inserts the shape model in the global SPS mesh
  42147. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  42148. var i;
  42149. var u = 0;
  42150. var c = 0;
  42151. var n = 0;
  42152. this._resetCopy();
  42153. if (options && options.positionFunction) {
  42154. options.positionFunction(this._copy, idx, idxInShape);
  42155. this._mustUnrotateFixedNormals = true;
  42156. }
  42157. if (this._copy.rotationQuaternion) {
  42158. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42159. }
  42160. else {
  42161. this._yaw = this._copy.rotation.y;
  42162. this._pitch = this._copy.rotation.x;
  42163. this._roll = this._copy.rotation.z;
  42164. this._quaternionRotationYPR();
  42165. }
  42166. this._quaternionToRotationMatrix();
  42167. for (i = 0; i < shape.length; i++) {
  42168. this._vertex.x = shape[i].x;
  42169. this._vertex.y = shape[i].y;
  42170. this._vertex.z = shape[i].z;
  42171. if (options && options.vertexFunction) {
  42172. options.vertexFunction(this._copy, this._vertex, i);
  42173. }
  42174. this._vertex.x *= this._copy.scaling.x;
  42175. this._vertex.y *= this._copy.scaling.y;
  42176. this._vertex.z *= this._copy.scaling.z;
  42177. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42178. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  42179. if (meshUV) {
  42180. 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);
  42181. u += 2;
  42182. }
  42183. if (this._copy.color) {
  42184. this._color = this._copy.color;
  42185. }
  42186. else if (meshCol && meshCol[c] !== undefined) {
  42187. this._color.r = meshCol[c];
  42188. this._color.g = meshCol[c + 1];
  42189. this._color.b = meshCol[c + 2];
  42190. this._color.a = meshCol[c + 3];
  42191. }
  42192. else {
  42193. this._color.r = 1;
  42194. this._color.g = 1;
  42195. this._color.b = 1;
  42196. this._color.a = 1;
  42197. }
  42198. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  42199. c += 4;
  42200. if (!this.recomputeNormals && meshNor) {
  42201. this._normal.x = meshNor[n];
  42202. this._normal.y = meshNor[n + 1];
  42203. this._normal.z = meshNor[n + 2];
  42204. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  42205. normals.push(this._normal.x, this._normal.y, this._normal.z);
  42206. n += 3;
  42207. }
  42208. }
  42209. for (i = 0; i < meshInd.length; i++) {
  42210. indices.push(p + meshInd[i]);
  42211. }
  42212. if (this._pickable) {
  42213. var nbfaces = meshInd.length / 3;
  42214. for (i = 0; i < nbfaces; i++) {
  42215. this.pickedParticles.push({ idx: idx, faceId: i });
  42216. }
  42217. }
  42218. return this._copy;
  42219. };
  42220. // returns a shape array from positions array
  42221. SolidParticleSystem.prototype._posToShape = function (positions) {
  42222. var shape = [];
  42223. for (var i = 0; i < positions.length; i += 3) {
  42224. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  42225. }
  42226. return shape;
  42227. };
  42228. // returns a shapeUV array from a Vector4 uvs
  42229. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  42230. var shapeUV = [];
  42231. if (uvs) {
  42232. for (var i = 0; i < uvs.length; i++)
  42233. shapeUV.push(uvs[i]);
  42234. }
  42235. return shapeUV;
  42236. };
  42237. // adds a new particle object in the particles array
  42238. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  42239. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  42240. this.particles.push(sp);
  42241. return sp;
  42242. };
  42243. /**
  42244. * Adds some particles to the SPS from the model shape. Returns the shape id.
  42245. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  42246. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  42247. * `nb` (positive integer) the number of particles to be created from this model
  42248. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  42249. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  42250. */
  42251. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  42252. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42253. var meshInd = mesh.getIndices();
  42254. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42255. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42256. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42257. var bbInfo;
  42258. if (this._particlesIntersect) {
  42259. bbInfo = mesh.getBoundingInfo();
  42260. }
  42261. var shape = this._posToShape(meshPos);
  42262. var shapeUV = this._uvsToShapeUV(meshUV);
  42263. var posfunc = options ? options.positionFunction : null;
  42264. var vtxfunc = options ? options.vertexFunction : null;
  42265. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  42266. // particles
  42267. var sp;
  42268. var currentCopy;
  42269. var idx = this.nbParticles;
  42270. for (var i = 0; i < nb; i++) {
  42271. var currentPos = this._positions.length;
  42272. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  42273. if (this._updatable) {
  42274. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  42275. sp.position.copyFrom(currentCopy.position);
  42276. sp.rotation.copyFrom(currentCopy.rotation);
  42277. if (currentCopy.rotationQuaternion) {
  42278. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  42279. }
  42280. if (currentCopy.color) {
  42281. sp.color.copyFrom(currentCopy.color);
  42282. }
  42283. sp.scaling.copyFrom(currentCopy.scaling);
  42284. sp.uvs.copyFrom(currentCopy.uvs);
  42285. }
  42286. this._index += shape.length;
  42287. idx++;
  42288. }
  42289. this.nbParticles += nb;
  42290. this._shapeCounter++;
  42291. return this._shapeCounter - 1;
  42292. };
  42293. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  42294. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  42295. this._resetCopy();
  42296. if (particle._model._positionFunction) {
  42297. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  42298. }
  42299. if (this._copy.rotationQuaternion) {
  42300. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42301. }
  42302. else {
  42303. this._yaw = this._copy.rotation.y;
  42304. this._pitch = this._copy.rotation.x;
  42305. this._roll = this._copy.rotation.z;
  42306. this._quaternionRotationYPR();
  42307. }
  42308. this._quaternionToRotationMatrix();
  42309. this._shape = particle._model._shape;
  42310. for (var pt = 0; pt < this._shape.length; pt++) {
  42311. this._vertex.x = this._shape[pt].x;
  42312. this._vertex.y = this._shape[pt].y;
  42313. this._vertex.z = this._shape[pt].z;
  42314. if (particle._model._vertexFunction) {
  42315. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  42316. }
  42317. this._vertex.x *= this._copy.scaling.x;
  42318. this._vertex.y *= this._copy.scaling.y;
  42319. this._vertex.z *= this._copy.scaling.z;
  42320. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42321. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  42322. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  42323. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  42324. }
  42325. particle.position.x = 0.0;
  42326. particle.position.y = 0.0;
  42327. particle.position.z = 0.0;
  42328. particle.rotation.x = 0.0;
  42329. particle.rotation.y = 0.0;
  42330. particle.rotation.z = 0.0;
  42331. particle.rotationQuaternion = null;
  42332. particle.scaling.x = 1.0;
  42333. particle.scaling.y = 1.0;
  42334. particle.scaling.z = 1.0;
  42335. };
  42336. /**
  42337. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  42338. * Returns the SPS.
  42339. */
  42340. SolidParticleSystem.prototype.rebuildMesh = function () {
  42341. for (var p = 0; p < this.particles.length; p++) {
  42342. this._rebuildParticle(this.particles[p]);
  42343. }
  42344. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42345. return this;
  42346. };
  42347. /**
  42348. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  42349. * This method calls `updateParticle()` for each particle of the SPS.
  42350. * For an animated SPS, it is usually called within the render loop.
  42351. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  42352. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  42353. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  42354. * Returns the SPS.
  42355. */
  42356. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  42357. if (start === void 0) { start = 0; }
  42358. if (end === void 0) { end = this.nbParticles - 1; }
  42359. if (update === void 0) { update = true; }
  42360. if (!this._updatable) {
  42361. return;
  42362. }
  42363. // custom beforeUpdate
  42364. this.beforeUpdateParticles(start, end, update);
  42365. this._cam_axisX.x = 1.0;
  42366. this._cam_axisX.y = 0.0;
  42367. this._cam_axisX.z = 0.0;
  42368. this._cam_axisY.x = 0.0;
  42369. this._cam_axisY.y = 1.0;
  42370. this._cam_axisY.z = 0.0;
  42371. this._cam_axisZ.x = 0.0;
  42372. this._cam_axisZ.y = 0.0;
  42373. this._cam_axisZ.z = 1.0;
  42374. // if the particles will always face the camera
  42375. if (this.billboard) {
  42376. this.mesh.computeWorldMatrix(true);
  42377. // compute the camera position and un-rotate it by the current mesh rotation
  42378. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  42379. this._quaternionToRotationMatrix();
  42380. this._rotMatrix.invertToRef(this._invertMatrix);
  42381. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  42382. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  42383. this._cam_axisZ.normalize();
  42384. // same for camera up vector extracted from the cam view matrix
  42385. var view = this._camera.getViewMatrix(true);
  42386. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  42387. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  42388. this._cam_axisY.normalize();
  42389. this._cam_axisX.normalize();
  42390. }
  42391. }
  42392. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  42393. var idx = 0; // current position index in the global array positions32
  42394. var index = 0; // position start index in the global array positions32 of the current particle
  42395. var colidx = 0; // current color index in the global array colors32
  42396. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  42397. var uvidx = 0; // current uv index in the global array uvs32
  42398. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  42399. var pt = 0; // current index in the particle model shape
  42400. if (this.mesh.isFacetDataEnabled) {
  42401. this._computeBoundingBox = true;
  42402. }
  42403. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  42404. if (this._computeBoundingBox) {
  42405. if (start == 0 && end == this.nbParticles - 1) {
  42406. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  42407. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  42408. }
  42409. else {
  42410. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  42411. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  42412. }
  42413. }
  42414. // particle loop
  42415. index = this.particles[start]._pos;
  42416. var vpos = (index / 3) | 0;
  42417. colorIndex = vpos * 4;
  42418. uvIndex = vpos * 2;
  42419. for (var p = start; p <= end; p++) {
  42420. this._particle = this.particles[p];
  42421. this._shape = this._particle._model._shape;
  42422. this._shapeUV = this._particle._model._shapeUV;
  42423. // call to custom user function to update the particle properties
  42424. this.updateParticle(this._particle);
  42425. // skip the computations for inactive or already invisible particles
  42426. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  42427. // increment indexes for the next particle
  42428. pt = this._shape.length;
  42429. index += pt * 3;
  42430. colorIndex += pt * 4;
  42431. uvIndex += pt * 2;
  42432. continue;
  42433. }
  42434. if (this._particle.isVisible) {
  42435. this._particle._stillInvisible = false; // un-mark permanent invisibility
  42436. // particle rotation matrix
  42437. if (this.billboard) {
  42438. this._particle.rotation.x = 0.0;
  42439. this._particle.rotation.y = 0.0;
  42440. }
  42441. if (this._computeParticleRotation || this.billboard) {
  42442. if (this._particle.rotationQuaternion) {
  42443. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42444. }
  42445. else {
  42446. this._yaw = this._particle.rotation.y;
  42447. this._pitch = this._particle.rotation.x;
  42448. this._roll = this._particle.rotation.z;
  42449. this._quaternionRotationYPR();
  42450. }
  42451. this._quaternionToRotationMatrix();
  42452. }
  42453. // particle vertex loop
  42454. for (pt = 0; pt < this._shape.length; pt++) {
  42455. idx = index + pt * 3;
  42456. colidx = colorIndex + pt * 4;
  42457. uvidx = uvIndex + pt * 2;
  42458. this._vertex.x = this._shape[pt].x;
  42459. this._vertex.y = this._shape[pt].y;
  42460. this._vertex.z = this._shape[pt].z;
  42461. if (this._computeParticleVertex) {
  42462. this.updateParticleVertex(this._particle, this._vertex, pt);
  42463. }
  42464. // positions
  42465. this._vertex.x *= this._particle.scaling.x;
  42466. this._vertex.y *= this._particle.scaling.y;
  42467. this._vertex.z *= this._particle.scaling.z;
  42468. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  42469. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  42470. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  42471. 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;
  42472. 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;
  42473. 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;
  42474. if (this._computeBoundingBox) {
  42475. if (this._positions32[idx] < this._minimum.x) {
  42476. this._minimum.x = this._positions32[idx];
  42477. }
  42478. if (this._positions32[idx] > this._maximum.x) {
  42479. this._maximum.x = this._positions32[idx];
  42480. }
  42481. if (this._positions32[idx + 1] < this._minimum.y) {
  42482. this._minimum.y = this._positions32[idx + 1];
  42483. }
  42484. if (this._positions32[idx + 1] > this._maximum.y) {
  42485. this._maximum.y = this._positions32[idx + 1];
  42486. }
  42487. if (this._positions32[idx + 2] < this._minimum.z) {
  42488. this._minimum.z = this._positions32[idx + 2];
  42489. }
  42490. if (this._positions32[idx + 2] > this._maximum.z) {
  42491. this._maximum.z = this._positions32[idx + 2];
  42492. }
  42493. }
  42494. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  42495. if (!this._computeParticleVertex) {
  42496. this._normal.x = this._fixedNormal32[idx];
  42497. this._normal.y = this._fixedNormal32[idx + 1];
  42498. this._normal.z = this._fixedNormal32[idx + 2];
  42499. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  42500. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  42501. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  42502. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42503. 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;
  42504. 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;
  42505. }
  42506. if (this._computeParticleColor) {
  42507. this._colors32[colidx] = this._particle.color.r;
  42508. this._colors32[colidx + 1] = this._particle.color.g;
  42509. this._colors32[colidx + 2] = this._particle.color.b;
  42510. this._colors32[colidx + 3] = this._particle.color.a;
  42511. }
  42512. if (this._computeParticleTexture) {
  42513. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42514. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42515. }
  42516. }
  42517. }
  42518. else {
  42519. this._particle._stillInvisible = true; // mark the particle as invisible
  42520. for (pt = 0; pt < this._shape.length; pt++) {
  42521. idx = index + pt * 3;
  42522. colidx = colorIndex + pt * 4;
  42523. uvidx = uvIndex + pt * 2;
  42524. this._positions32[idx] = 0.0;
  42525. this._positions32[idx + 1] = 0.0;
  42526. this._positions32[idx + 2] = 0.0;
  42527. this._normals32[idx] = 0.0;
  42528. this._normals32[idx + 1] = 0.0;
  42529. this._normals32[idx + 2] = 0.0;
  42530. if (this._computeParticleColor) {
  42531. this._colors32[colidx] = this._particle.color.r;
  42532. this._colors32[colidx + 1] = this._particle.color.g;
  42533. this._colors32[colidx + 2] = this._particle.color.b;
  42534. this._colors32[colidx + 3] = this._particle.color.a;
  42535. }
  42536. if (this._computeParticleTexture) {
  42537. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42538. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42539. }
  42540. }
  42541. }
  42542. // if the particle intersections must be computed : update the bbInfo
  42543. if (this._particlesIntersect) {
  42544. var bInfo = this._particle._boundingInfo;
  42545. var bBox = bInfo.boundingBox;
  42546. var bSphere = bInfo.boundingSphere;
  42547. if (!this._bSphereOnly) {
  42548. // place, scale and rotate the particle bbox within the SPS local system, then update it
  42549. for (var b = 0; b < bBox.vectors.length; b++) {
  42550. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  42551. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  42552. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  42553. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  42554. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  42555. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  42556. 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;
  42557. 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;
  42558. 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;
  42559. }
  42560. bBox._update(this.mesh._worldMatrix);
  42561. }
  42562. // place and scale the particle bouding sphere in the SPS local system, then update it
  42563. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  42564. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  42565. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  42566. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  42567. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  42568. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  42569. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  42570. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  42571. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  42572. 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));
  42573. bSphere._update(this.mesh._worldMatrix);
  42574. }
  42575. // increment indexes for the next particle
  42576. index = idx + 3;
  42577. colorIndex = colidx + 4;
  42578. uvIndex = uvidx + 2;
  42579. }
  42580. // if the VBO must be updated
  42581. if (update) {
  42582. if (this._computeParticleColor) {
  42583. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42584. }
  42585. if (this._computeParticleTexture) {
  42586. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42587. }
  42588. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42589. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  42590. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  42591. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  42592. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  42593. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  42594. for (var i = 0; i < this._normals32.length; i++) {
  42595. this._fixedNormal32[i] = this._normals32[i];
  42596. }
  42597. }
  42598. if (!this.mesh.areNormalsFrozen) {
  42599. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42600. }
  42601. }
  42602. }
  42603. if (this._computeBoundingBox) {
  42604. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42605. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42606. }
  42607. this.afterUpdateParticles(start, end, update);
  42608. return this;
  42609. };
  42610. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42611. this._halfroll = this._roll * 0.5;
  42612. this._halfpitch = this._pitch * 0.5;
  42613. this._halfyaw = this._yaw * 0.5;
  42614. this._sinRoll = Math.sin(this._halfroll);
  42615. this._cosRoll = Math.cos(this._halfroll);
  42616. this._sinPitch = Math.sin(this._halfpitch);
  42617. this._cosPitch = Math.cos(this._halfpitch);
  42618. this._sinYaw = Math.sin(this._halfyaw);
  42619. this._cosYaw = Math.cos(this._halfyaw);
  42620. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  42621. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  42622. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  42623. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  42624. };
  42625. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42626. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42627. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42628. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42629. this._rotMatrix.m[3] = 0;
  42630. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42631. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42632. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42633. this._rotMatrix.m[7] = 0;
  42634. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42635. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42636. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42637. this._rotMatrix.m[11] = 0;
  42638. this._rotMatrix.m[12] = 0;
  42639. this._rotMatrix.m[13] = 0;
  42640. this._rotMatrix.m[14] = 0;
  42641. this._rotMatrix.m[15] = 1.0;
  42642. };
  42643. /**
  42644. * Disposes the SPS.
  42645. * Returns nothing.
  42646. */
  42647. SolidParticleSystem.prototype.dispose = function () {
  42648. this.mesh.dispose();
  42649. this.vars = null;
  42650. // drop references to internal big arrays for the GC
  42651. this._positions = null;
  42652. this._indices = null;
  42653. this._normals = null;
  42654. this._uvs = null;
  42655. this._colors = null;
  42656. this._positions32 = null;
  42657. this._normals32 = null;
  42658. this._fixedNormal32 = null;
  42659. this._uvs32 = null;
  42660. this._colors32 = null;
  42661. this.pickedParticles = null;
  42662. };
  42663. /**
  42664. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42665. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42666. * Returns the SPS.
  42667. */
  42668. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42669. if (!this._isVisibilityBoxLocked) {
  42670. this.mesh.refreshBoundingInfo();
  42671. }
  42672. return this;
  42673. };
  42674. /**
  42675. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42676. * @param size the size (float) of the visibility box
  42677. * note : this doesn't lock the SPS mesh bounding box.
  42678. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42679. */
  42680. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42681. var vis = size / 2;
  42682. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42683. };
  42684. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42685. // getter and setter
  42686. get: function () {
  42687. return this._alwaysVisible;
  42688. },
  42689. /**
  42690. * Sets the SPS as always visible or not
  42691. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42692. */
  42693. set: function (val) {
  42694. this._alwaysVisible = val;
  42695. this.mesh.alwaysSelectAsActiveMesh = val;
  42696. },
  42697. enumerable: true,
  42698. configurable: true
  42699. });
  42700. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42701. get: function () {
  42702. return this._isVisibilityBoxLocked;
  42703. },
  42704. /**
  42705. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42706. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42707. */
  42708. set: function (val) {
  42709. this._isVisibilityBoxLocked = val;
  42710. this.mesh.getBoundingInfo().isLocked = val;
  42711. },
  42712. enumerable: true,
  42713. configurable: true
  42714. });
  42715. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42716. // getters
  42717. get: function () {
  42718. return this._computeParticleRotation;
  42719. },
  42720. // Optimizer setters
  42721. /**
  42722. * Tells to `setParticles()` to compute the particle rotations or not.
  42723. * Default value : true. The SPS is faster when it's set to false.
  42724. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42725. */
  42726. set: function (val) {
  42727. this._computeParticleRotation = val;
  42728. },
  42729. enumerable: true,
  42730. configurable: true
  42731. });
  42732. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42733. get: function () {
  42734. return this._computeParticleColor;
  42735. },
  42736. /**
  42737. * Tells to `setParticles()` to compute the particle colors or not.
  42738. * Default value : true. The SPS is faster when it's set to false.
  42739. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42740. */
  42741. set: function (val) {
  42742. this._computeParticleColor = val;
  42743. },
  42744. enumerable: true,
  42745. configurable: true
  42746. });
  42747. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42748. get: function () {
  42749. return this._computeParticleTexture;
  42750. },
  42751. /**
  42752. * Tells to `setParticles()` to compute the particle textures or not.
  42753. * Default value : true. The SPS is faster when it's set to false.
  42754. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42755. */
  42756. set: function (val) {
  42757. this._computeParticleTexture = val;
  42758. },
  42759. enumerable: true,
  42760. configurable: true
  42761. });
  42762. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42763. get: function () {
  42764. return this._computeParticleVertex;
  42765. },
  42766. /**
  42767. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42768. * Default value : false. The SPS is faster when it's set to false.
  42769. * Note : the particle custom vertex positions aren't stored values.
  42770. */
  42771. set: function (val) {
  42772. this._computeParticleVertex = val;
  42773. },
  42774. enumerable: true,
  42775. configurable: true
  42776. });
  42777. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42778. get: function () {
  42779. return this._computeBoundingBox;
  42780. },
  42781. /**
  42782. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42783. */
  42784. set: function (val) {
  42785. this._computeBoundingBox = val;
  42786. },
  42787. enumerable: true,
  42788. configurable: true
  42789. });
  42790. // =======================================================================
  42791. // Particle behavior logic
  42792. // these following methods may be overwritten by the user to fit his needs
  42793. /**
  42794. * This function does nothing. It may be overwritten to set all the particle first values.
  42795. * The SPS doesn't call this function, you may have to call it by your own.
  42796. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42797. */
  42798. SolidParticleSystem.prototype.initParticles = function () {
  42799. };
  42800. /**
  42801. * This function does nothing. It may be overwritten to recycle a particle.
  42802. * The SPS doesn't call this function, you may have to call it by your own.
  42803. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42804. */
  42805. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42806. return particle;
  42807. };
  42808. /**
  42809. * Updates a particle : this function should be overwritten by the user.
  42810. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42811. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42812. * ex : just set a particle position or velocity and recycle conditions
  42813. */
  42814. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42815. return particle;
  42816. };
  42817. /**
  42818. * Updates a vertex of a particle : it can be overwritten by the user.
  42819. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42820. * @param particle the current particle
  42821. * @param vertex the current index of the current particle
  42822. * @param pt the index of the current vertex in the particle shape
  42823. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  42824. * ex : just set a vertex particle position
  42825. */
  42826. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42827. return vertex;
  42828. };
  42829. /**
  42830. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42831. * This does nothing and may be overwritten by the user.
  42832. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42833. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42834. * @param update the boolean update value actually passed to setParticles()
  42835. */
  42836. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42837. };
  42838. /**
  42839. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42840. * This will be passed three parameters.
  42841. * This does nothing and may be overwritten by the user.
  42842. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42843. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42844. * @param update the boolean update value actually passed to setParticles()
  42845. */
  42846. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42847. };
  42848. return SolidParticleSystem;
  42849. }());
  42850. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42851. })(BABYLON || (BABYLON = {}));
  42852. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  42853. /// <reference path="babylon.mesh.ts" />
  42854. var BABYLON;
  42855. (function (BABYLON) {
  42856. var GroundMesh = (function (_super) {
  42857. __extends(GroundMesh, _super);
  42858. function GroundMesh(name, scene) {
  42859. var _this = _super.call(this, name, scene) || this;
  42860. _this.generateOctree = false;
  42861. _this._worldInverse = new BABYLON.Matrix();
  42862. return _this;
  42863. }
  42864. GroundMesh.prototype.getClassName = function () {
  42865. return "GroundMesh";
  42866. };
  42867. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42868. get: function () {
  42869. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42870. },
  42871. enumerable: true,
  42872. configurable: true
  42873. });
  42874. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42875. get: function () {
  42876. return this._subdivisionsX;
  42877. },
  42878. enumerable: true,
  42879. configurable: true
  42880. });
  42881. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42882. get: function () {
  42883. return this._subdivisionsY;
  42884. },
  42885. enumerable: true,
  42886. configurable: true
  42887. });
  42888. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42889. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42890. this._subdivisionsX = chunksCount;
  42891. this._subdivisionsY = chunksCount;
  42892. this.subdivide(chunksCount);
  42893. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42894. };
  42895. /**
  42896. * Returns a height (y) value in the Worl system :
  42897. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42898. * Returns the ground y position if (x, z) are outside the ground surface.
  42899. */
  42900. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42901. var world = this.getWorldMatrix();
  42902. var invMat = BABYLON.Tmp.Matrix[5];
  42903. world.invertToRef(invMat);
  42904. var tmpVect = BABYLON.Tmp.Vector3[8];
  42905. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42906. x = tmpVect.x;
  42907. z = tmpVect.z;
  42908. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42909. return this.position.y;
  42910. }
  42911. if (!this._heightQuads || this._heightQuads.length == 0) {
  42912. this._initHeightQuads();
  42913. this._computeHeightQuads();
  42914. }
  42915. var facet = this._getFacetAt(x, z);
  42916. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42917. // return y in the World system
  42918. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42919. return tmpVect.y;
  42920. };
  42921. /**
  42922. * Returns a normalized vector (Vector3) orthogonal to the ground
  42923. * at the ground coordinates (x, z) expressed in the World system.
  42924. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42925. */
  42926. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42927. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42928. this.getNormalAtCoordinatesToRef(x, z, normal);
  42929. return normal;
  42930. };
  42931. /**
  42932. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42933. * at the ground coordinates (x, z) expressed in the World system.
  42934. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42935. * Returns the GroundMesh.
  42936. */
  42937. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42938. var world = this.getWorldMatrix();
  42939. var tmpMat = BABYLON.Tmp.Matrix[5];
  42940. world.invertToRef(tmpMat);
  42941. var tmpVect = BABYLON.Tmp.Vector3[8];
  42942. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42943. x = tmpVect.x;
  42944. z = tmpVect.z;
  42945. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42946. return this;
  42947. }
  42948. if (!this._heightQuads || this._heightQuads.length == 0) {
  42949. this._initHeightQuads();
  42950. this._computeHeightQuads();
  42951. }
  42952. var facet = this._getFacetAt(x, z);
  42953. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42954. return this;
  42955. };
  42956. /**
  42957. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42958. * if the ground has been updated.
  42959. * This can be used in the render loop.
  42960. * Returns the GroundMesh.
  42961. */
  42962. GroundMesh.prototype.updateCoordinateHeights = function () {
  42963. if (!this._heightQuads || this._heightQuads.length == 0) {
  42964. this._initHeightQuads();
  42965. }
  42966. this._computeHeightQuads();
  42967. return this;
  42968. };
  42969. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42970. GroundMesh.prototype._getFacetAt = function (x, z) {
  42971. // retrieve col and row from x, z coordinates in the ground local system
  42972. var subdivisionsX = this._subdivisionsX;
  42973. var subdivisionsY = this._subdivisionsY;
  42974. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42975. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42976. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42977. var facet;
  42978. if (z < quad.slope.x * x + quad.slope.y) {
  42979. facet = quad.facet1;
  42980. }
  42981. else {
  42982. facet = quad.facet2;
  42983. }
  42984. return facet;
  42985. };
  42986. // Creates and populates the heightMap array with "facet" elements :
  42987. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42988. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42989. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42990. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42991. // Returns the GroundMesh.
  42992. GroundMesh.prototype._initHeightQuads = function () {
  42993. var subdivisionsX = this._subdivisionsX;
  42994. var subdivisionsY = this._subdivisionsY;
  42995. this._heightQuads = new Array();
  42996. for (var row = 0; row < subdivisionsY; row++) {
  42997. for (var col = 0; col < subdivisionsX; col++) {
  42998. 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) };
  42999. this._heightQuads[row * subdivisionsX + col] = quad;
  43000. }
  43001. }
  43002. return this;
  43003. };
  43004. // Compute each quad element values and update the the heightMap array :
  43005. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43006. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43007. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43008. // Returns the GroundMesh.
  43009. GroundMesh.prototype._computeHeightQuads = function () {
  43010. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43011. var v1 = BABYLON.Tmp.Vector3[3];
  43012. var v2 = BABYLON.Tmp.Vector3[2];
  43013. var v3 = BABYLON.Tmp.Vector3[1];
  43014. var v4 = BABYLON.Tmp.Vector3[0];
  43015. var v1v2 = BABYLON.Tmp.Vector3[4];
  43016. var v1v3 = BABYLON.Tmp.Vector3[5];
  43017. var v1v4 = BABYLON.Tmp.Vector3[6];
  43018. var norm1 = BABYLON.Tmp.Vector3[7];
  43019. var norm2 = BABYLON.Tmp.Vector3[8];
  43020. var i = 0;
  43021. var j = 0;
  43022. var k = 0;
  43023. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43024. var h = 0;
  43025. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43026. var d2 = 0;
  43027. var subdivisionsX = this._subdivisionsX;
  43028. var subdivisionsY = this._subdivisionsY;
  43029. for (var row = 0; row < subdivisionsY; row++) {
  43030. for (var col = 0; col < subdivisionsX; col++) {
  43031. i = col * 3;
  43032. j = row * (subdivisionsX + 1) * 3;
  43033. k = (row + 1) * (subdivisionsX + 1) * 3;
  43034. v1.x = positions[j + i];
  43035. v1.y = positions[j + i + 1];
  43036. v1.z = positions[j + i + 2];
  43037. v2.x = positions[j + i + 3];
  43038. v2.y = positions[j + i + 4];
  43039. v2.z = positions[j + i + 5];
  43040. v3.x = positions[k + i];
  43041. v3.y = positions[k + i + 1];
  43042. v3.z = positions[k + i + 2];
  43043. v4.x = positions[k + i + 3];
  43044. v4.y = positions[k + i + 4];
  43045. v4.z = positions[k + i + 5];
  43046. // 2D slope V1V4
  43047. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43048. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43049. // facet equations :
  43050. // we compute each facet normal vector
  43051. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43052. // we compute the value d by applying the equation to v1 which belongs to the plane
  43053. // then we store the facet equation in a Vector4
  43054. v2.subtractToRef(v1, v1v2);
  43055. v3.subtractToRef(v1, v1v3);
  43056. v4.subtractToRef(v1, v1v4);
  43057. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43058. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43059. norm1.normalize();
  43060. norm2.normalize();
  43061. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43062. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43063. var quad = this._heightQuads[row * subdivisionsX + col];
  43064. quad.slope.copyFromFloats(cd, h);
  43065. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43066. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43067. }
  43068. }
  43069. return this;
  43070. };
  43071. GroundMesh.prototype.serialize = function (serializationObject) {
  43072. _super.prototype.serialize.call(this, serializationObject);
  43073. serializationObject.subdivisionsX = this._subdivisionsX;
  43074. serializationObject.subdivisionsY = this._subdivisionsY;
  43075. serializationObject.minX = this._minX;
  43076. serializationObject.maxX = this._maxX;
  43077. serializationObject.minZ = this._minZ;
  43078. serializationObject.maxZ = this._maxZ;
  43079. serializationObject.width = this._width;
  43080. serializationObject.height = this._height;
  43081. };
  43082. GroundMesh.Parse = function (parsedMesh, scene) {
  43083. var result = new GroundMesh(parsedMesh.name, scene);
  43084. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43085. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43086. result._minX = parsedMesh.minX;
  43087. result._maxX = parsedMesh.maxX;
  43088. result._minZ = parsedMesh.minZ;
  43089. result._maxZ = parsedMesh.maxZ;
  43090. result._width = parsedMesh.width;
  43091. result._height = parsedMesh.height;
  43092. return result;
  43093. };
  43094. return GroundMesh;
  43095. }(BABYLON.Mesh));
  43096. BABYLON.GroundMesh = GroundMesh;
  43097. })(BABYLON || (BABYLON = {}));
  43098. //# sourceMappingURL=babylon.groundMesh.js.map
  43099. var BABYLON;
  43100. (function (BABYLON) {
  43101. /**
  43102. * Creates an instance based on a source mesh.
  43103. */
  43104. var InstancedMesh = (function (_super) {
  43105. __extends(InstancedMesh, _super);
  43106. function InstancedMesh(name, source) {
  43107. var _this = _super.call(this, name, source.getScene()) || this;
  43108. source.instances.push(_this);
  43109. _this._sourceMesh = source;
  43110. _this.position.copyFrom(source.position);
  43111. _this.rotation.copyFrom(source.rotation);
  43112. _this.scaling.copyFrom(source.scaling);
  43113. if (source.rotationQuaternion) {
  43114. _this.rotationQuaternion = source.rotationQuaternion.clone();
  43115. }
  43116. _this.infiniteDistance = source.infiniteDistance;
  43117. _this.setPivotMatrix(source.getPivotMatrix());
  43118. _this.refreshBoundingInfo();
  43119. _this._syncSubMeshes();
  43120. return _this;
  43121. }
  43122. /**
  43123. * Returns the string "InstancedMesh".
  43124. */
  43125. InstancedMesh.prototype.getClassName = function () {
  43126. return "InstancedMesh";
  43127. };
  43128. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  43129. // Methods
  43130. get: function () {
  43131. return this._sourceMesh.receiveShadows;
  43132. },
  43133. enumerable: true,
  43134. configurable: true
  43135. });
  43136. Object.defineProperty(InstancedMesh.prototype, "material", {
  43137. get: function () {
  43138. return this._sourceMesh.material;
  43139. },
  43140. enumerable: true,
  43141. configurable: true
  43142. });
  43143. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  43144. get: function () {
  43145. return this._sourceMesh.visibility;
  43146. },
  43147. enumerable: true,
  43148. configurable: true
  43149. });
  43150. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  43151. get: function () {
  43152. return this._sourceMesh.skeleton;
  43153. },
  43154. enumerable: true,
  43155. configurable: true
  43156. });
  43157. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  43158. get: function () {
  43159. return this._sourceMesh.renderingGroupId;
  43160. },
  43161. enumerable: true,
  43162. configurable: true
  43163. });
  43164. /**
  43165. * Returns the total number of vertices (integer).
  43166. */
  43167. InstancedMesh.prototype.getTotalVertices = function () {
  43168. return this._sourceMesh.getTotalVertices();
  43169. };
  43170. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  43171. get: function () {
  43172. return this._sourceMesh;
  43173. },
  43174. enumerable: true,
  43175. configurable: true
  43176. });
  43177. /**
  43178. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  43179. */
  43180. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  43181. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  43182. };
  43183. /**
  43184. * Sets the vertex data of the mesh geometry for the requested `kind`.
  43185. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  43186. * The `data` are either a numeric array either a Float32Array.
  43187. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  43188. * 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).
  43189. * Note that a new underlying VertexBuffer object is created each call.
  43190. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  43191. *
  43192. * Possible `kind` values :
  43193. * - BABYLON.VertexBuffer.PositionKind
  43194. * - BABYLON.VertexBuffer.UVKind
  43195. * - BABYLON.VertexBuffer.UV2Kind
  43196. * - BABYLON.VertexBuffer.UV3Kind
  43197. * - BABYLON.VertexBuffer.UV4Kind
  43198. * - BABYLON.VertexBuffer.UV5Kind
  43199. * - BABYLON.VertexBuffer.UV6Kind
  43200. * - BABYLON.VertexBuffer.ColorKind
  43201. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43202. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43203. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43204. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43205. *
  43206. * Returns the Mesh.
  43207. */
  43208. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  43209. if (this.sourceMesh) {
  43210. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  43211. }
  43212. return this.sourceMesh;
  43213. };
  43214. /**
  43215. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  43216. * If the mesh has no geometry, it is simply returned as it is.
  43217. * The `data` are either a numeric array either a Float32Array.
  43218. * No new underlying VertexBuffer object is created.
  43219. * 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.
  43220. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  43221. *
  43222. * Possible `kind` values :
  43223. * - BABYLON.VertexBuffer.PositionKind
  43224. * - BABYLON.VertexBuffer.UVKind
  43225. * - BABYLON.VertexBuffer.UV2Kind
  43226. * - BABYLON.VertexBuffer.UV3Kind
  43227. * - BABYLON.VertexBuffer.UV4Kind
  43228. * - BABYLON.VertexBuffer.UV5Kind
  43229. * - BABYLON.VertexBuffer.UV6Kind
  43230. * - BABYLON.VertexBuffer.ColorKind
  43231. * - BABYLON.VertexBuffer.MatricesIndicesKind
  43232. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  43233. * - BABYLON.VertexBuffer.MatricesWeightsKind
  43234. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  43235. *
  43236. * Returns the Mesh.
  43237. */
  43238. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  43239. if (this.sourceMesh) {
  43240. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  43241. }
  43242. return this.sourceMesh;
  43243. };
  43244. /**
  43245. * Sets the mesh indices.
  43246. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  43247. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  43248. * This method creates a new index buffer each call.
  43249. * Returns the Mesh.
  43250. */
  43251. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  43252. if (this.sourceMesh) {
  43253. this.sourceMesh.setIndices(indices, totalVertices);
  43254. }
  43255. return this.sourceMesh;
  43256. };
  43257. /**
  43258. * Boolean : True if the mesh owns the requested kind of data.
  43259. */
  43260. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  43261. return this._sourceMesh.isVerticesDataPresent(kind);
  43262. };
  43263. /**
  43264. * Returns an array of indices (IndicesArray).
  43265. */
  43266. InstancedMesh.prototype.getIndices = function () {
  43267. return this._sourceMesh.getIndices();
  43268. };
  43269. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  43270. get: function () {
  43271. return this._sourceMesh._positions;
  43272. },
  43273. enumerable: true,
  43274. configurable: true
  43275. });
  43276. /**
  43277. * Sets a new updated BoundingInfo to the mesh.
  43278. * Returns the mesh.
  43279. */
  43280. InstancedMesh.prototype.refreshBoundingInfo = function () {
  43281. var meshBB = this._sourceMesh.getBoundingInfo();
  43282. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  43283. this._updateBoundingInfo();
  43284. return this;
  43285. };
  43286. InstancedMesh.prototype._preActivate = function () {
  43287. if (this._currentLOD) {
  43288. this._currentLOD._preActivate();
  43289. }
  43290. return this;
  43291. };
  43292. InstancedMesh.prototype._activate = function (renderId) {
  43293. if (this._currentLOD) {
  43294. this._currentLOD._registerInstanceForRenderId(this, renderId);
  43295. }
  43296. return this;
  43297. };
  43298. /**
  43299. * Returns the current associated LOD AbstractMesh.
  43300. */
  43301. InstancedMesh.prototype.getLOD = function (camera) {
  43302. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  43303. if (this._currentLOD === this.sourceMesh) {
  43304. return this;
  43305. }
  43306. return this._currentLOD;
  43307. };
  43308. InstancedMesh.prototype._syncSubMeshes = function () {
  43309. this.releaseSubMeshes();
  43310. if (this._sourceMesh.subMeshes) {
  43311. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  43312. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  43313. }
  43314. }
  43315. return this;
  43316. };
  43317. InstancedMesh.prototype._generatePointsArray = function () {
  43318. return this._sourceMesh._generatePointsArray();
  43319. };
  43320. /**
  43321. * Creates a new InstancedMesh from the current mesh.
  43322. * - name (string) : the cloned mesh name
  43323. * - newParent (optional Node) : the optional Node to parent the clone to.
  43324. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  43325. *
  43326. * Returns the clone.
  43327. */
  43328. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43329. var result = this._sourceMesh.createInstance(name);
  43330. // Deep copy
  43331. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  43332. // Bounding info
  43333. this.refreshBoundingInfo();
  43334. // Parent
  43335. if (newParent) {
  43336. result.parent = newParent;
  43337. }
  43338. if (!doNotCloneChildren) {
  43339. // Children
  43340. for (var index = 0; index < this.getScene().meshes.length; index++) {
  43341. var mesh = this.getScene().meshes[index];
  43342. if (mesh.parent === this) {
  43343. mesh.clone(mesh.name, result);
  43344. }
  43345. }
  43346. }
  43347. result.computeWorldMatrix(true);
  43348. return result;
  43349. };
  43350. /**
  43351. * Disposes the InstancedMesh.
  43352. * Returns nothing.
  43353. */
  43354. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  43355. // Remove from mesh
  43356. var index = this._sourceMesh.instances.indexOf(this);
  43357. this._sourceMesh.instances.splice(index, 1);
  43358. _super.prototype.dispose.call(this, doNotRecurse);
  43359. };
  43360. return InstancedMesh;
  43361. }(BABYLON.AbstractMesh));
  43362. BABYLON.InstancedMesh = InstancedMesh;
  43363. })(BABYLON || (BABYLON = {}));
  43364. //# sourceMappingURL=babylon.instancedMesh.js.map
  43365. /// <reference path="babylon.mesh.ts" />
  43366. var BABYLON;
  43367. (function (BABYLON) {
  43368. var LinesMesh = (function (_super) {
  43369. __extends(LinesMesh, _super);
  43370. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  43371. if (parent === void 0) { parent = null; }
  43372. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43373. _this.useVertexColor = useVertexColor;
  43374. _this.color = new BABYLON.Color3(1, 1, 1);
  43375. _this.alpha = 1;
  43376. if (source) {
  43377. _this.color = source.color.clone();
  43378. _this.alpha = source.alpha;
  43379. _this.useVertexColor = source.useVertexColor;
  43380. }
  43381. _this._intersectionThreshold = 0.1;
  43382. var options = {
  43383. attributes: [BABYLON.VertexBuffer.PositionKind],
  43384. uniforms: ["world", "viewProjection"],
  43385. needAlphaBlending: false,
  43386. };
  43387. if (!useVertexColor) {
  43388. options.uniforms.push("color");
  43389. options.needAlphaBlending = true;
  43390. }
  43391. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  43392. return _this;
  43393. }
  43394. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43395. /**
  43396. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43397. * This margin is expressed in world space coordinates, so its value may vary.
  43398. * Default value is 0.1
  43399. * @returns the intersection Threshold value.
  43400. */
  43401. get: function () {
  43402. return this._intersectionThreshold;
  43403. },
  43404. /**
  43405. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43406. * This margin is expressed in world space coordinates, so its value may vary.
  43407. * @param value the new threshold to apply
  43408. */
  43409. set: function (value) {
  43410. if (this._intersectionThreshold === value) {
  43411. return;
  43412. }
  43413. this._intersectionThreshold = value;
  43414. if (this.geometry) {
  43415. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43416. }
  43417. },
  43418. enumerable: true,
  43419. configurable: true
  43420. });
  43421. /**
  43422. * Returns the string "LineMesh"
  43423. */
  43424. LinesMesh.prototype.getClassName = function () {
  43425. return "LinesMesh";
  43426. };
  43427. Object.defineProperty(LinesMesh.prototype, "material", {
  43428. get: function () {
  43429. return this._colorShader;
  43430. },
  43431. enumerable: true,
  43432. configurable: true
  43433. });
  43434. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43435. get: function () {
  43436. return false;
  43437. },
  43438. enumerable: true,
  43439. configurable: true
  43440. });
  43441. LinesMesh.prototype.createInstance = function (name) {
  43442. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43443. return null;
  43444. };
  43445. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43446. // VBOs
  43447. this._geometry._bind(this._colorShader.getEffect());
  43448. // Color
  43449. if (!this.useVertexColor) {
  43450. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43451. }
  43452. return this;
  43453. };
  43454. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43455. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43456. return this;
  43457. }
  43458. var engine = this.getScene().getEngine();
  43459. // Draw order
  43460. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43461. return this;
  43462. };
  43463. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43464. this._colorShader.dispose();
  43465. _super.prototype.dispose.call(this, doNotRecurse);
  43466. };
  43467. /**
  43468. * Returns a new LineMesh object cloned from the current one.
  43469. */
  43470. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43471. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43472. };
  43473. return LinesMesh;
  43474. }(BABYLON.Mesh));
  43475. BABYLON.LinesMesh = LinesMesh;
  43476. })(BABYLON || (BABYLON = {}));
  43477. //# sourceMappingURL=babylon.linesMesh.js.map
  43478. var BABYLON;
  43479. (function (BABYLON) {
  43480. var ShaderMaterial = (function (_super) {
  43481. __extends(ShaderMaterial, _super);
  43482. function ShaderMaterial(name, scene, shaderPath, options) {
  43483. var _this = _super.call(this, name, scene) || this;
  43484. _this._textures = {};
  43485. _this._textureArrays = {};
  43486. _this._floats = {};
  43487. _this._floatsArrays = {};
  43488. _this._colors3 = {};
  43489. _this._colors3Arrays = {};
  43490. _this._colors4 = {};
  43491. _this._vectors2 = {};
  43492. _this._vectors3 = {};
  43493. _this._vectors4 = {};
  43494. _this._matrices = {};
  43495. _this._matrices3x3 = {};
  43496. _this._matrices2x2 = {};
  43497. _this._vectors3Arrays = {};
  43498. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  43499. _this._shaderPath = shaderPath;
  43500. options.needAlphaBlending = options.needAlphaBlending || false;
  43501. options.needAlphaTesting = options.needAlphaTesting || false;
  43502. options.attributes = options.attributes || ["position", "normal", "uv"];
  43503. options.uniforms = options.uniforms || ["worldViewProjection"];
  43504. options.uniformBuffers = options.uniformBuffers || [];
  43505. options.samplers = options.samplers || [];
  43506. options.defines = options.defines || [];
  43507. _this._options = options;
  43508. return _this;
  43509. }
  43510. ShaderMaterial.prototype.getClassName = function () {
  43511. return "ShaderMaterial";
  43512. };
  43513. ShaderMaterial.prototype.needAlphaBlending = function () {
  43514. return this._options.needAlphaBlending;
  43515. };
  43516. ShaderMaterial.prototype.needAlphaTesting = function () {
  43517. return this._options.needAlphaTesting;
  43518. };
  43519. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43520. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43521. this._options.uniforms.push(uniformName);
  43522. }
  43523. };
  43524. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43525. if (this._options.samplers.indexOf(name) === -1) {
  43526. this._options.samplers.push(name);
  43527. }
  43528. this._textures[name] = texture;
  43529. return this;
  43530. };
  43531. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  43532. if (this._options.samplers.indexOf(name) === -1) {
  43533. this._options.samplers.push(name);
  43534. }
  43535. this._checkUniform(name);
  43536. this._textureArrays[name] = textures;
  43537. return this;
  43538. };
  43539. ShaderMaterial.prototype.setFloat = function (name, value) {
  43540. this._checkUniform(name);
  43541. this._floats[name] = value;
  43542. return this;
  43543. };
  43544. ShaderMaterial.prototype.setFloats = function (name, value) {
  43545. this._checkUniform(name);
  43546. this._floatsArrays[name] = value;
  43547. return this;
  43548. };
  43549. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43550. this._checkUniform(name);
  43551. this._colors3[name] = value;
  43552. return this;
  43553. };
  43554. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  43555. this._checkUniform(name);
  43556. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  43557. color.toArray(arr, arr.length);
  43558. return arr;
  43559. }, []);
  43560. return this;
  43561. };
  43562. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43563. this._checkUniform(name);
  43564. this._colors4[name] = value;
  43565. return this;
  43566. };
  43567. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43568. this._checkUniform(name);
  43569. this._vectors2[name] = value;
  43570. return this;
  43571. };
  43572. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43573. this._checkUniform(name);
  43574. this._vectors3[name] = value;
  43575. return this;
  43576. };
  43577. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43578. this._checkUniform(name);
  43579. this._vectors4[name] = value;
  43580. return this;
  43581. };
  43582. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43583. this._checkUniform(name);
  43584. this._matrices[name] = value;
  43585. return this;
  43586. };
  43587. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43588. this._checkUniform(name);
  43589. this._matrices3x3[name] = value;
  43590. return this;
  43591. };
  43592. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43593. this._checkUniform(name);
  43594. this._matrices2x2[name] = value;
  43595. return this;
  43596. };
  43597. ShaderMaterial.prototype.setArray3 = function (name, value) {
  43598. this._checkUniform(name);
  43599. this._vectors3Arrays[name] = value;
  43600. return this;
  43601. };
  43602. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  43603. if (!mesh) {
  43604. return true;
  43605. }
  43606. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  43607. return false;
  43608. }
  43609. return false;
  43610. };
  43611. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43612. var scene = this.getScene();
  43613. var engine = scene.getEngine();
  43614. if (!this.checkReadyOnEveryCall) {
  43615. if (this._renderId === scene.getRenderId()) {
  43616. if (this._checkCache(scene, mesh, useInstances)) {
  43617. return true;
  43618. }
  43619. }
  43620. }
  43621. // Instances
  43622. var defines = [];
  43623. var attribs = [];
  43624. var fallbacks = new BABYLON.EffectFallbacks();
  43625. if (useInstances) {
  43626. defines.push("#define INSTANCES");
  43627. }
  43628. for (var index = 0; index < this._options.defines.length; index++) {
  43629. defines.push(this._options.defines[index]);
  43630. }
  43631. for (var index = 0; index < this._options.attributes.length; index++) {
  43632. attribs.push(this._options.attributes[index]);
  43633. }
  43634. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  43635. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43636. defines.push("#define VERTEXCOLOR");
  43637. }
  43638. // Bones
  43639. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43640. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43641. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43642. if (mesh.numBoneInfluencers > 4) {
  43643. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43644. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43645. }
  43646. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43647. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43648. fallbacks.addCPUSkinningFallback(0, mesh);
  43649. if (this._options.uniforms.indexOf("mBones") === -1) {
  43650. this._options.uniforms.push("mBones");
  43651. }
  43652. }
  43653. else {
  43654. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43655. }
  43656. // Textures
  43657. for (var name in this._textures) {
  43658. if (!this._textures[name].isReady()) {
  43659. return false;
  43660. }
  43661. }
  43662. // Alpha test
  43663. if (engine.getAlphaTesting()) {
  43664. defines.push("#define ALPHATEST");
  43665. }
  43666. var previousEffect = this._effect;
  43667. var join = defines.join("\n");
  43668. this._effect = engine.createEffect(this._shaderPath, {
  43669. attributes: attribs,
  43670. uniformsNames: this._options.uniforms,
  43671. uniformBuffersNames: this._options.uniformBuffers,
  43672. samplers: this._options.samplers,
  43673. defines: join,
  43674. fallbacks: fallbacks,
  43675. onCompiled: this.onCompiled,
  43676. onError: this.onError
  43677. }, engine);
  43678. if (!this._effect.isReady()) {
  43679. return false;
  43680. }
  43681. if (previousEffect !== this._effect) {
  43682. scene.resetCachedMaterial();
  43683. }
  43684. this._renderId = scene.getRenderId();
  43685. return true;
  43686. };
  43687. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43688. var scene = this.getScene();
  43689. if (this._options.uniforms.indexOf("world") !== -1) {
  43690. this._effect.setMatrix("world", world);
  43691. }
  43692. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43693. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43694. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43695. }
  43696. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43697. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43698. }
  43699. };
  43700. ShaderMaterial.prototype.bind = function (world, mesh) {
  43701. // Std values
  43702. this.bindOnlyWorldMatrix(world);
  43703. if (this.getScene().getCachedMaterial() !== this) {
  43704. if (this._options.uniforms.indexOf("view") !== -1) {
  43705. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43706. }
  43707. if (this._options.uniforms.indexOf("projection") !== -1) {
  43708. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43709. }
  43710. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43711. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43712. }
  43713. // Bones
  43714. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43715. var name;
  43716. // Texture
  43717. for (name in this._textures) {
  43718. this._effect.setTexture(name, this._textures[name]);
  43719. }
  43720. // Texture arrays
  43721. for (name in this._textureArrays) {
  43722. this._effect.setTextureArray(name, this._textureArrays[name]);
  43723. }
  43724. // Float
  43725. for (name in this._floats) {
  43726. this._effect.setFloat(name, this._floats[name]);
  43727. }
  43728. // Float s
  43729. for (name in this._floatsArrays) {
  43730. this._effect.setArray(name, this._floatsArrays[name]);
  43731. }
  43732. // Color3
  43733. for (name in this._colors3) {
  43734. this._effect.setColor3(name, this._colors3[name]);
  43735. }
  43736. for (name in this._colors3Arrays) {
  43737. this._effect.setArray3(name, this._colors3Arrays[name]);
  43738. }
  43739. // Color4
  43740. for (name in this._colors4) {
  43741. var color = this._colors4[name];
  43742. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43743. }
  43744. // Vector2
  43745. for (name in this._vectors2) {
  43746. this._effect.setVector2(name, this._vectors2[name]);
  43747. }
  43748. // Vector3
  43749. for (name in this._vectors3) {
  43750. this._effect.setVector3(name, this._vectors3[name]);
  43751. }
  43752. // Vector4
  43753. for (name in this._vectors4) {
  43754. this._effect.setVector4(name, this._vectors4[name]);
  43755. }
  43756. // Matrix
  43757. for (name in this._matrices) {
  43758. this._effect.setMatrix(name, this._matrices[name]);
  43759. }
  43760. // Matrix 3x3
  43761. for (name in this._matrices3x3) {
  43762. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43763. }
  43764. // Matrix 2x2
  43765. for (name in this._matrices2x2) {
  43766. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43767. }
  43768. // Vector3Array
  43769. for (name in this._vectors3Arrays) {
  43770. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43771. }
  43772. }
  43773. this._afterBind(mesh);
  43774. };
  43775. ShaderMaterial.prototype.getActiveTextures = function () {
  43776. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43777. for (var name in this._textures) {
  43778. activeTextures.push(this._textures[name]);
  43779. }
  43780. for (var name in this._textureArrays) {
  43781. var array = this._textureArrays[name];
  43782. for (var index = 0; index < array.length; index++) {
  43783. activeTextures.push(array[index]);
  43784. }
  43785. }
  43786. return activeTextures;
  43787. };
  43788. ShaderMaterial.prototype.hasTexture = function (texture) {
  43789. if (_super.prototype.hasTexture.call(this, texture)) {
  43790. return true;
  43791. }
  43792. for (var name in this._textures) {
  43793. if (this._textures[name] === texture) {
  43794. return true;
  43795. }
  43796. }
  43797. for (var name in this._textureArrays) {
  43798. var array = this._textureArrays[name];
  43799. for (var index = 0; index < array.length; index++) {
  43800. if (array[index] === texture) {
  43801. return true;
  43802. }
  43803. }
  43804. }
  43805. return false;
  43806. };
  43807. ShaderMaterial.prototype.clone = function (name) {
  43808. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43809. return newShaderMaterial;
  43810. };
  43811. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43812. if (forceDisposeTextures) {
  43813. var name;
  43814. for (name in this._textures) {
  43815. this._textures[name].dispose();
  43816. }
  43817. for (name in this._textureArrays) {
  43818. var array = this._textureArrays[name];
  43819. for (var index = 0; index < array.length; index++) {
  43820. array[index].dispose();
  43821. }
  43822. }
  43823. }
  43824. this._textures = {};
  43825. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43826. };
  43827. ShaderMaterial.prototype.serialize = function () {
  43828. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43829. serializationObject.customType = "BABYLON.ShaderMaterial";
  43830. serializationObject.options = this._options;
  43831. serializationObject.shaderPath = this._shaderPath;
  43832. var name;
  43833. // Texture
  43834. serializationObject.textures = {};
  43835. for (name in this._textures) {
  43836. serializationObject.textures[name] = this._textures[name].serialize();
  43837. }
  43838. // Texture arrays
  43839. serializationObject.textureArrays = {};
  43840. for (name in this._textureArrays) {
  43841. serializationObject.textureArrays[name] = [];
  43842. var array = this._textureArrays[name];
  43843. for (var index = 0; index < array.length; index++) {
  43844. serializationObject.textureArrays[name].push(array[index].serialize());
  43845. }
  43846. }
  43847. // Float
  43848. serializationObject.floats = {};
  43849. for (name in this._floats) {
  43850. serializationObject.floats[name] = this._floats[name];
  43851. }
  43852. // Float s
  43853. serializationObject.floatArrays = {};
  43854. for (name in this._floatsArrays) {
  43855. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43856. }
  43857. // Color3
  43858. serializationObject.colors3 = {};
  43859. for (name in this._colors3) {
  43860. serializationObject.colors3[name] = this._colors3[name].asArray();
  43861. }
  43862. // Color3 array
  43863. serializationObject.colors3Arrays = {};
  43864. for (name in this._colors3Arrays) {
  43865. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  43866. }
  43867. // Color4
  43868. serializationObject.colors4 = {};
  43869. for (name in this._colors4) {
  43870. serializationObject.colors4[name] = this._colors4[name].asArray();
  43871. }
  43872. // Vector2
  43873. serializationObject.vectors2 = {};
  43874. for (name in this._vectors2) {
  43875. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43876. }
  43877. // Vector3
  43878. serializationObject.vectors3 = {};
  43879. for (name in this._vectors3) {
  43880. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43881. }
  43882. // Vector4
  43883. serializationObject.vectors4 = {};
  43884. for (name in this._vectors4) {
  43885. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43886. }
  43887. // Matrix
  43888. serializationObject.matrices = {};
  43889. for (name in this._matrices) {
  43890. serializationObject.matrices[name] = this._matrices[name].asArray();
  43891. }
  43892. // Matrix 3x3
  43893. serializationObject.matrices3x3 = {};
  43894. for (name in this._matrices3x3) {
  43895. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43896. }
  43897. // Matrix 2x2
  43898. serializationObject.matrices2x2 = {};
  43899. for (name in this._matrices2x2) {
  43900. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43901. }
  43902. // Vector3Array
  43903. serializationObject.vectors3Arrays = {};
  43904. for (name in this._vectors3Arrays) {
  43905. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43906. }
  43907. return serializationObject;
  43908. };
  43909. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43910. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43911. var name;
  43912. // Texture
  43913. for (name in source.textures) {
  43914. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43915. }
  43916. // Texture arrays
  43917. for (name in source.textureArrays) {
  43918. var array = source.textureArrays[name];
  43919. var textureArray = new Array();
  43920. for (var index = 0; index < array.length; index++) {
  43921. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43922. }
  43923. material.setTextureArray(name, textureArray);
  43924. }
  43925. // Float
  43926. for (name in source.floats) {
  43927. material.setFloat(name, source.floats[name]);
  43928. }
  43929. // Float s
  43930. for (name in source.floatsArrays) {
  43931. material.setFloats(name, source.floatsArrays[name]);
  43932. }
  43933. // Color3
  43934. for (name in source.colors3) {
  43935. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43936. }
  43937. // Color3 arrays
  43938. for (name in source.colors3Arrays) {
  43939. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  43940. if (i % 3 === 0) {
  43941. arr.push([num]);
  43942. }
  43943. else {
  43944. arr[arr.length - 1].push(num);
  43945. }
  43946. return arr;
  43947. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  43948. material.setColor3Array(name, colors);
  43949. }
  43950. // Color4
  43951. for (name in source.colors4) {
  43952. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43953. }
  43954. // Vector2
  43955. for (name in source.vectors2) {
  43956. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43957. }
  43958. // Vector3
  43959. for (name in source.vectors3) {
  43960. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43961. }
  43962. // Vector4
  43963. for (name in source.vectors4) {
  43964. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43965. }
  43966. // Matrix
  43967. for (name in source.matrices) {
  43968. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43969. }
  43970. // Matrix 3x3
  43971. for (name in source.matrices3x3) {
  43972. material.setMatrix3x3(name, source.matrices3x3[name]);
  43973. }
  43974. // Matrix 2x2
  43975. for (name in source.matrices2x2) {
  43976. material.setMatrix2x2(name, source.matrices2x2[name]);
  43977. }
  43978. // Vector3Array
  43979. for (name in source.vectors3Arrays) {
  43980. material.setArray3(name, source.vectors3Arrays[name]);
  43981. }
  43982. return material;
  43983. };
  43984. return ShaderMaterial;
  43985. }(BABYLON.Material));
  43986. BABYLON.ShaderMaterial = ShaderMaterial;
  43987. })(BABYLON || (BABYLON = {}));
  43988. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43989. var BABYLON;
  43990. (function (BABYLON) {
  43991. var MeshBuilder = (function () {
  43992. function MeshBuilder() {
  43993. }
  43994. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  43995. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  43996. return BABYLON.Mesh.DOUBLESIDE;
  43997. }
  43998. if (orientation === undefined || orientation === null) {
  43999. return BABYLON.Mesh.FRONTSIDE;
  44000. }
  44001. return orientation;
  44002. };
  44003. /**
  44004. * Creates a box mesh.
  44005. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  44006. * The parameter `size` sets the size (float) of each box side (default 1).
  44007. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  44008. * 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).
  44009. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  44010. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44011. * 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).
  44012. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44014. */
  44015. MeshBuilder.CreateBox = function (name, options, scene) {
  44016. var box = new BABYLON.Mesh(name, scene);
  44017. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44018. box._originalBuilderSideOrientation = options.sideOrientation;
  44019. var vertexData = BABYLON.VertexData.CreateBox(options);
  44020. vertexData.applyToMesh(box, options.updatable);
  44021. return box;
  44022. };
  44023. /**
  44024. * Creates a sphere mesh.
  44025. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  44026. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  44027. * 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`).
  44028. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  44029. * 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
  44030. * 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).
  44031. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44032. * 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).
  44033. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44035. */
  44036. MeshBuilder.CreateSphere = function (name, options, scene) {
  44037. var sphere = new BABYLON.Mesh(name, scene);
  44038. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44039. sphere._originalBuilderSideOrientation = options.sideOrientation;
  44040. var vertexData = BABYLON.VertexData.CreateSphere(options);
  44041. vertexData.applyToMesh(sphere, options.updatable);
  44042. return sphere;
  44043. };
  44044. /**
  44045. * Creates a plane polygonal mesh. By default, this is a disc.
  44046. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  44047. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  44048. * 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.
  44049. * 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
  44050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44051. * 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).
  44052. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44054. */
  44055. MeshBuilder.CreateDisc = function (name, options, scene) {
  44056. var disc = new BABYLON.Mesh(name, scene);
  44057. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44058. disc._originalBuilderSideOrientation = options.sideOrientation;
  44059. var vertexData = BABYLON.VertexData.CreateDisc(options);
  44060. vertexData.applyToMesh(disc, options.updatable);
  44061. return disc;
  44062. };
  44063. /**
  44064. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  44065. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  44066. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  44067. * 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`).
  44068. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  44069. * 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.
  44070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44071. * 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).
  44072. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44073. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44074. */
  44075. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  44076. var sphere = new BABYLON.Mesh(name, scene);
  44077. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44078. sphere._originalBuilderSideOrientation = options.sideOrientation;
  44079. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  44080. vertexData.applyToMesh(sphere, options.updatable);
  44081. return sphere;
  44082. };
  44083. ;
  44084. /**
  44085. * Creates a ribbon mesh.
  44086. * 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.
  44087. *
  44088. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  44089. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  44090. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  44091. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  44092. * 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.
  44093. * 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.
  44094. * 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
  44095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44096. * 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).
  44097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44098. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44099. * 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.
  44100. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  44101. * 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
  44102. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  44103. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  44104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44105. */
  44106. MeshBuilder.CreateRibbon = function (name, options, scene) {
  44107. var pathArray = options.pathArray;
  44108. var closeArray = options.closeArray;
  44109. var closePath = options.closePath;
  44110. var offset = options.offset;
  44111. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44112. var instance = options.instance;
  44113. var updatable = options.updatable;
  44114. if (instance) {
  44115. // positionFunction : ribbon case
  44116. // only pathArray and sideOrientation parameters are taken into account for positions update
  44117. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  44118. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  44119. var positionFunction = function (positions) {
  44120. var minlg = pathArray[0].length;
  44121. var i = 0;
  44122. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  44123. for (var si = 1; si <= ns; si++) {
  44124. for (var p = 0; p < pathArray.length; p++) {
  44125. var path = pathArray[p];
  44126. var l = path.length;
  44127. minlg = (minlg < l) ? minlg : l;
  44128. var j = 0;
  44129. while (j < minlg) {
  44130. positions[i] = path[j].x;
  44131. positions[i + 1] = path[j].y;
  44132. positions[i + 2] = path[j].z;
  44133. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  44134. BABYLON.Tmp.Vector3[0].x = path[j].x;
  44135. }
  44136. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  44137. BABYLON.Tmp.Vector3[1].x = path[j].x;
  44138. }
  44139. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  44140. BABYLON.Tmp.Vector3[0].y = path[j].y;
  44141. }
  44142. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  44143. BABYLON.Tmp.Vector3[1].y = path[j].y;
  44144. }
  44145. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  44146. BABYLON.Tmp.Vector3[0].z = path[j].z;
  44147. }
  44148. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  44149. BABYLON.Tmp.Vector3[1].z = path[j].z;
  44150. }
  44151. j++;
  44152. i += 3;
  44153. }
  44154. if (instance._closePath) {
  44155. positions[i] = path[0].x;
  44156. positions[i + 1] = path[0].y;
  44157. positions[i + 2] = path[0].z;
  44158. i += 3;
  44159. }
  44160. }
  44161. }
  44162. };
  44163. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44164. positionFunction(positions);
  44165. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  44166. instance._boundingInfo.update(instance._worldMatrix);
  44167. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  44168. if (options.colors) {
  44169. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44170. for (var c = 0; c < options.colors.length; c++) {
  44171. colors[c * 4] = options.colors[c].r;
  44172. colors[c * 4 + 1] = options.colors[c].g;
  44173. colors[c * 4 + 2] = options.colors[c].b;
  44174. colors[c * 4 + 3] = options.colors[c].a;
  44175. }
  44176. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  44177. }
  44178. if (options.uvs) {
  44179. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44180. for (var i = 0; i < options.uvs.length; i++) {
  44181. uvs[i * 2] = options.uvs[i].x;
  44182. uvs[i * 2 + 1] = options.uvs[i].y;
  44183. }
  44184. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  44185. }
  44186. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  44187. var indices = instance.getIndices();
  44188. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44189. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  44190. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  44191. if (instance._closePath) {
  44192. var indexFirst = 0;
  44193. var indexLast = 0;
  44194. for (var p = 0; p < pathArray.length; p++) {
  44195. indexFirst = instance._idx[p] * 3;
  44196. if (p + 1 < pathArray.length) {
  44197. indexLast = (instance._idx[p + 1] - 1) * 3;
  44198. }
  44199. else {
  44200. indexLast = normals.length - 3;
  44201. }
  44202. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  44203. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  44204. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  44205. normals[indexLast] = normals[indexFirst];
  44206. normals[indexLast + 1] = normals[indexFirst + 1];
  44207. normals[indexLast + 2] = normals[indexFirst + 2];
  44208. }
  44209. }
  44210. if (!(instance.areNormalsFrozen)) {
  44211. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  44212. }
  44213. }
  44214. return instance;
  44215. }
  44216. else {
  44217. var ribbon = new BABYLON.Mesh(name, scene);
  44218. ribbon._originalBuilderSideOrientation = sideOrientation;
  44219. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  44220. if (closePath) {
  44221. ribbon._idx = vertexData._idx;
  44222. }
  44223. ribbon._closePath = closePath;
  44224. ribbon._closeArray = closeArray;
  44225. vertexData.applyToMesh(ribbon, updatable);
  44226. return ribbon;
  44227. }
  44228. };
  44229. /**
  44230. * Creates a cylinder or a cone mesh.
  44231. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  44232. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  44233. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  44234. * 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.
  44235. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  44236. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  44237. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  44238. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  44239. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  44240. * 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).
  44241. * 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
  44242. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  44243. * 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
  44244. * 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.
  44245. * If `enclose` is false, a ring surface is one element.
  44246. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  44247. * 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
  44248. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44249. * 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).
  44250. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44252. */
  44253. MeshBuilder.CreateCylinder = function (name, options, scene) {
  44254. var cylinder = new BABYLON.Mesh(name, scene);
  44255. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44256. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  44257. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  44258. vertexData.applyToMesh(cylinder, options.updatable);
  44259. return cylinder;
  44260. };
  44261. /**
  44262. * Creates a torus mesh.
  44263. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  44264. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  44265. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  44266. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  44267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44268. * 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).
  44269. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44270. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44271. */
  44272. MeshBuilder.CreateTorus = function (name, options, scene) {
  44273. var torus = new BABYLON.Mesh(name, scene);
  44274. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44275. torus._originalBuilderSideOrientation = options.sideOrientation;
  44276. var vertexData = BABYLON.VertexData.CreateTorus(options);
  44277. vertexData.applyToMesh(torus, options.updatable);
  44278. return torus;
  44279. };
  44280. /**
  44281. * Creates a torus knot mesh.
  44282. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  44283. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  44284. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  44285. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  44286. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  44287. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44288. * 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).
  44289. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44291. */
  44292. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  44293. var torusKnot = new BABYLON.Mesh(name, scene);
  44294. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44295. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  44296. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  44297. vertexData.applyToMesh(torusKnot, options.updatable);
  44298. return torusKnot;
  44299. };
  44300. /**
  44301. * Creates a line system mesh.
  44302. * A line system is a pool of many lines gathered in a single mesh.
  44303. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  44304. * 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.
  44305. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  44306. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  44307. * 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
  44308. * 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
  44309. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  44310. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44311. */
  44312. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  44313. var instance = options.instance;
  44314. var lines = options.lines;
  44315. if (instance) {
  44316. var positionFunction = function (positions) {
  44317. var i = 0;
  44318. for (var l = 0; l < lines.length; l++) {
  44319. var points = lines[l];
  44320. for (var p = 0; p < points.length; p++) {
  44321. positions[i] = points[p].x;
  44322. positions[i + 1] = points[p].y;
  44323. positions[i + 2] = points[p].z;
  44324. i += 3;
  44325. }
  44326. }
  44327. };
  44328. instance.updateMeshPositions(positionFunction, false);
  44329. return instance;
  44330. }
  44331. // line system creation
  44332. var lineSystem = new BABYLON.LinesMesh(name, scene);
  44333. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  44334. vertexData.applyToMesh(lineSystem, options.updatable);
  44335. return lineSystem;
  44336. };
  44337. /**
  44338. * Creates a line mesh.
  44339. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  44340. * 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.
  44341. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  44342. * The parameter `points` is an array successive Vector3.
  44343. * 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
  44344. * When updating an instance, remember that only point positions can change, not the number of points.
  44345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44346. */
  44347. MeshBuilder.CreateLines = function (name, options, scene) {
  44348. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  44349. return lines;
  44350. };
  44351. /**
  44352. * Creates a dashed line mesh.
  44353. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  44354. * 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.
  44355. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  44356. * The parameter `points` is an array successive Vector3.
  44357. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  44358. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  44359. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  44360. * 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
  44361. * When updating an instance, remember that only point positions can change, not the number of points.
  44362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44363. */
  44364. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  44365. var points = options.points;
  44366. var instance = options.instance;
  44367. var gapSize = options.gapSize || 1;
  44368. var dashSize = options.dashSize || 3;
  44369. if (instance) {
  44370. var positionFunction = function (positions) {
  44371. var curvect = BABYLON.Vector3.Zero();
  44372. var nbSeg = positions.length / 6;
  44373. var lg = 0;
  44374. var nb = 0;
  44375. var shft = 0;
  44376. var dashshft = 0;
  44377. var curshft = 0;
  44378. var p = 0;
  44379. var i = 0;
  44380. var j = 0;
  44381. for (i = 0; i < points.length - 1; i++) {
  44382. points[i + 1].subtractToRef(points[i], curvect);
  44383. lg += curvect.length();
  44384. }
  44385. shft = lg / nbSeg;
  44386. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  44387. for (i = 0; i < points.length - 1; i++) {
  44388. points[i + 1].subtractToRef(points[i], curvect);
  44389. nb = Math.floor(curvect.length() / shft);
  44390. curvect.normalize();
  44391. j = 0;
  44392. while (j < nb && p < positions.length) {
  44393. curshft = shft * j;
  44394. positions[p] = points[i].x + curshft * curvect.x;
  44395. positions[p + 1] = points[i].y + curshft * curvect.y;
  44396. positions[p + 2] = points[i].z + curshft * curvect.z;
  44397. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  44398. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  44399. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  44400. p += 6;
  44401. j++;
  44402. }
  44403. }
  44404. while (p < positions.length) {
  44405. positions[p] = points[i].x;
  44406. positions[p + 1] = points[i].y;
  44407. positions[p + 2] = points[i].z;
  44408. p += 3;
  44409. }
  44410. };
  44411. instance.updateMeshPositions(positionFunction, false);
  44412. return instance;
  44413. }
  44414. // dashed lines creation
  44415. var dashedLines = new BABYLON.LinesMesh(name, scene);
  44416. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  44417. vertexData.applyToMesh(dashedLines, options.updatable);
  44418. dashedLines.dashSize = dashSize;
  44419. dashedLines.gapSize = gapSize;
  44420. return dashedLines;
  44421. };
  44422. /**
  44423. * Creates an extruded shape mesh.
  44424. * 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.
  44425. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  44426. *
  44427. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  44428. * 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
  44429. * extruded along the Z axis.
  44430. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  44431. * 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.
  44432. * The parameter `scale` (float, default 1) is the value to scale the shape.
  44433. * 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
  44434. * 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
  44435. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  44436. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44437. * 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).
  44438. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44439. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44441. */
  44442. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  44443. var path = options.path;
  44444. var shape = options.shape;
  44445. var scale = options.scale || 1;
  44446. var rotation = options.rotation || 0;
  44447. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  44448. var updatable = options.updatable;
  44449. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44450. var instance = options.instance;
  44451. var invertUV = options.invertUV || false;
  44452. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  44453. };
  44454. /**
  44455. * Creates an custom extruded shape mesh.
  44456. * 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.
  44457. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  44458. *
  44459. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  44460. * 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
  44461. * extruded along the Z axis.
  44462. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  44463. * 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
  44464. * and the distance of this point from the begining of the path :
  44465. * ```javascript
  44466. * var rotationFunction = function(i, distance) {
  44467. * // do things
  44468. * return rotationValue; }
  44469. * ```
  44470. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  44471. * 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
  44472. * and the distance of this point from the begining of the path :
  44473. * ```javascript
  44474. * var scaleFunction = function(i, distance) {
  44475. * // do things
  44476. * return scaleValue;}
  44477. * ```
  44478. * It must returns a float value that will be the scale value applied to the shape on each path point.
  44479. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  44480. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  44481. * 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
  44482. * 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
  44483. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  44484. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44485. * 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).
  44486. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44487. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44489. */
  44490. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  44491. var path = options.path;
  44492. var shape = options.shape;
  44493. var scaleFunction = options.scaleFunction || (function () { return 1; });
  44494. var rotationFunction = options.rotationFunction || (function () { return 0; });
  44495. var ribbonCloseArray = options.ribbonCloseArray || false;
  44496. var ribbonClosePath = options.ribbonClosePath || false;
  44497. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  44498. var updatable = options.updatable;
  44499. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44500. var instance = options.instance;
  44501. var invertUV = options.invertUV || false;
  44502. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  44503. };
  44504. /**
  44505. * Creates lathe mesh.
  44506. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  44507. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  44508. *
  44509. * 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
  44510. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  44511. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  44512. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  44513. * 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.
  44514. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  44515. * 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
  44516. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44517. * 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).
  44518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44519. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44520. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44521. */
  44522. MeshBuilder.CreateLathe = function (name, options, scene) {
  44523. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  44524. var closed = (options.closed === undefined) ? true : options.closed;
  44525. var shape = options.shape;
  44526. var radius = options.radius || 1;
  44527. var tessellation = options.tessellation || 64;
  44528. var updatable = options.updatable;
  44529. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44530. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44531. var pi2 = Math.PI * 2;
  44532. var paths = new Array();
  44533. var invertUV = options.invertUV || false;
  44534. var i = 0;
  44535. var p = 0;
  44536. var step = pi2 / tessellation * arc;
  44537. var rotated;
  44538. var path = new Array();
  44539. ;
  44540. for (i = 0; i <= tessellation; i++) {
  44541. var path = [];
  44542. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  44543. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  44544. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  44545. }
  44546. for (p = 0; p < shape.length; p++) {
  44547. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  44548. path.push(rotated);
  44549. }
  44550. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  44551. 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));
  44552. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  44553. }
  44554. paths.push(path);
  44555. }
  44556. // lathe ribbon
  44557. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44558. return lathe;
  44559. };
  44560. /**
  44561. * Creates a plane mesh.
  44562. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44563. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  44564. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  44565. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  44566. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44567. * 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).
  44568. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44570. */
  44571. MeshBuilder.CreatePlane = function (name, options, scene) {
  44572. var plane = new BABYLON.Mesh(name, scene);
  44573. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44574. plane._originalBuilderSideOrientation = options.sideOrientation;
  44575. var vertexData = BABYLON.VertexData.CreatePlane(options);
  44576. vertexData.applyToMesh(plane, options.updatable);
  44577. if (options.sourcePlane) {
  44578. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  44579. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  44580. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  44581. plane.rotate(vectorProduct, product);
  44582. }
  44583. return plane;
  44584. };
  44585. /**
  44586. * Creates a ground mesh.
  44587. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44588. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  44589. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  44590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44591. */
  44592. MeshBuilder.CreateGround = function (name, options, scene) {
  44593. var ground = new BABYLON.GroundMesh(name, scene);
  44594. ground._setReady(false);
  44595. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  44596. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  44597. ground._width = options.width || 1;
  44598. ground._height = options.height || 1;
  44599. ground._maxX = ground._width / 2;
  44600. ground._maxZ = ground._height / 2;
  44601. ground._minX = -ground._maxX;
  44602. ground._minZ = -ground._maxZ;
  44603. var vertexData = BABYLON.VertexData.CreateGround(options);
  44604. vertexData.applyToMesh(ground, options.updatable);
  44605. ground._setReady(true);
  44606. return ground;
  44607. };
  44608. /**
  44609. * Creates a tiled ground mesh.
  44610. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  44611. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  44612. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  44613. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  44614. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  44615. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  44616. * numbers of subdivisions on the ground width and height of each tile.
  44617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44618. */
  44619. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  44620. var tiledGround = new BABYLON.Mesh(name, scene);
  44621. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  44622. vertexData.applyToMesh(tiledGround, options.updatable);
  44623. return tiledGround;
  44624. };
  44625. /**
  44626. * Creates a ground mesh from a height map.
  44627. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  44628. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  44629. * The parameter `url` sets the URL of the height map image resource.
  44630. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  44631. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  44632. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  44633. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  44634. * 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.
  44635. * 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).
  44636. * This function is passed the newly built mesh :
  44637. * ```javascript
  44638. * function(mesh) { // do things
  44639. * return; }
  44640. * ```
  44641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44642. */
  44643. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  44644. var width = options.width || 10.0;
  44645. var height = options.height || 10.0;
  44646. var subdivisions = options.subdivisions || 1 | 0;
  44647. var minHeight = options.minHeight || 0.0;
  44648. var maxHeight = options.maxHeight || 1.0;
  44649. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  44650. var updatable = options.updatable;
  44651. var onReady = options.onReady;
  44652. var ground = new BABYLON.GroundMesh(name, scene);
  44653. ground._subdivisionsX = subdivisions;
  44654. ground._subdivisionsY = subdivisions;
  44655. ground._width = width;
  44656. ground._height = height;
  44657. ground._maxX = ground._width / 2.0;
  44658. ground._maxZ = ground._height / 2.0;
  44659. ground._minX = -ground._maxX;
  44660. ground._minZ = -ground._maxZ;
  44661. ground._setReady(false);
  44662. var onload = function (img) {
  44663. // Getting height map data
  44664. var canvas = document.createElement("canvas");
  44665. var context = canvas.getContext("2d");
  44666. var bufferWidth = img.width;
  44667. var bufferHeight = img.height;
  44668. canvas.width = bufferWidth;
  44669. canvas.height = bufferHeight;
  44670. context.drawImage(img, 0, 0);
  44671. // Create VertexData from map data
  44672. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  44673. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  44674. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  44675. width: width, height: height,
  44676. subdivisions: subdivisions,
  44677. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  44678. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  44679. });
  44680. vertexData.applyToMesh(ground, updatable);
  44681. ground._setReady(true);
  44682. //execute ready callback, if set
  44683. if (onReady) {
  44684. onReady(ground);
  44685. }
  44686. };
  44687. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  44688. return ground;
  44689. };
  44690. /**
  44691. * Creates a polygon mesh.
  44692. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  44693. * 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.
  44694. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44696. * 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).
  44697. * Remember you can only change the shape positions, not their number when updating a polygon.
  44698. */
  44699. MeshBuilder.CreatePolygon = function (name, options, scene) {
  44700. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44701. var shape = options.shape;
  44702. var holes = options.holes || [];
  44703. var depth = options.depth || 0;
  44704. var contours = [];
  44705. var hole = [];
  44706. for (var i = 0; i < shape.length; i++) {
  44707. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  44708. }
  44709. var epsilon = 0.00000001;
  44710. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  44711. contours.pop();
  44712. }
  44713. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  44714. for (var hNb = 0; hNb < holes.length; hNb++) {
  44715. hole = [];
  44716. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  44717. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  44718. }
  44719. polygonTriangulation.addHole(hole);
  44720. }
  44721. var polygon = polygonTriangulation.build(options.updatable, depth);
  44722. polygon._originalBuilderSideOrientation = options.sideOrientation;
  44723. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  44724. vertexData.applyToMesh(polygon, options.updatable);
  44725. return polygon;
  44726. };
  44727. ;
  44728. /**
  44729. * Creates an extruded polygon mesh, with depth in the Y direction.
  44730. * 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).
  44731. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  44732. */
  44733. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  44734. return MeshBuilder.CreatePolygon(name, options, scene);
  44735. };
  44736. ;
  44737. /**
  44738. * Creates a tube mesh.
  44739. * 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.
  44740. *
  44741. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  44742. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  44743. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  44744. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  44745. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  44746. * 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.
  44747. * It must return a radius value (positive float) :
  44748. * ```javascript
  44749. * var radiusFunction = function(i, distance) {
  44750. * // do things
  44751. * return radius; }
  44752. * ```
  44753. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  44754. * 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
  44755. * 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
  44756. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44757. * 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).
  44758. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44759. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44761. */
  44762. MeshBuilder.CreateTube = function (name, options, scene) {
  44763. var path = options.path;
  44764. var instance = options.instance;
  44765. var radius = 1.0;
  44766. if (instance) {
  44767. radius = instance.radius;
  44768. }
  44769. if (options.radius !== undefined) {
  44770. radius = options.radius;
  44771. }
  44772. ;
  44773. var tessellation = options.tessellation || 64 | 0;
  44774. var radiusFunction = options.radiusFunction;
  44775. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44776. var invertUV = options.invertUV || false;
  44777. var updatable = options.updatable;
  44778. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44779. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  44780. // tube geometry
  44781. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  44782. var tangents = path3D.getTangents();
  44783. var normals = path3D.getNormals();
  44784. var distances = path3D.getDistances();
  44785. var pi2 = Math.PI * 2;
  44786. var step = pi2 / tessellation * arc;
  44787. var returnRadius = function () { return radius; };
  44788. var radiusFunctionFinal = radiusFunction || returnRadius;
  44789. var circlePath;
  44790. var rad;
  44791. var normal;
  44792. var rotated;
  44793. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44794. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44795. for (var i = 0; i < path.length; i++) {
  44796. rad = radiusFunctionFinal(i, distances[i]); // current radius
  44797. circlePath = Array(); // current circle array
  44798. normal = normals[i]; // current normal
  44799. for (var t = 0; t < tessellation; t++) {
  44800. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  44801. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  44802. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  44803. rotated.scaleInPlace(rad).addInPlace(path[i]);
  44804. circlePath[t] = rotated;
  44805. }
  44806. circlePaths[index] = circlePath;
  44807. index++;
  44808. }
  44809. // cap
  44810. var capPath = function (nbPoints, pathIndex) {
  44811. var pointCap = Array();
  44812. for (var i = 0; i < nbPoints; i++) {
  44813. pointCap.push(path[pathIndex]);
  44814. }
  44815. return pointCap;
  44816. };
  44817. switch (cap) {
  44818. case BABYLON.Mesh.NO_CAP:
  44819. break;
  44820. case BABYLON.Mesh.CAP_START:
  44821. circlePaths[0] = capPath(tessellation, 0);
  44822. circlePaths[1] = circlePaths[2].slice(0);
  44823. break;
  44824. case BABYLON.Mesh.CAP_END:
  44825. circlePaths[index] = circlePaths[index - 1].slice(0);
  44826. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44827. break;
  44828. case BABYLON.Mesh.CAP_ALL:
  44829. circlePaths[0] = capPath(tessellation, 0);
  44830. circlePaths[1] = circlePaths[2].slice(0);
  44831. circlePaths[index] = circlePaths[index - 1].slice(0);
  44832. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44833. break;
  44834. default:
  44835. break;
  44836. }
  44837. return circlePaths;
  44838. };
  44839. var path3D;
  44840. var pathArray;
  44841. if (instance) {
  44842. var arc = options.arc || instance.arc;
  44843. path3D = (instance.path3D).update(path);
  44844. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  44845. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  44846. instance.path3D = path3D;
  44847. instance.pathArray = pathArray;
  44848. instance.arc = arc;
  44849. instance.radius = radius;
  44850. return instance;
  44851. }
  44852. // tube creation
  44853. path3D = new BABYLON.Path3D(path);
  44854. var newPathArray = new Array();
  44855. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44856. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  44857. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44858. tube.pathArray = pathArray;
  44859. tube.path3D = path3D;
  44860. tube.tessellation = tessellation;
  44861. tube.cap = cap;
  44862. tube.arc = options.arc;
  44863. tube.radius = radius;
  44864. return tube;
  44865. };
  44866. /**
  44867. * Creates a polyhedron mesh.
  44868. *
  44869. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  44870. * 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
  44871. * to choose the wanted type.
  44872. * The parameter `size` (positive float, default 1) sets the polygon size.
  44873. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  44874. * 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`.
  44875. * 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
  44876. * 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)`).
  44877. * 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
  44878. * 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.
  44879. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44880. * 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).
  44881. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44882. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44883. */
  44884. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  44885. var polyhedron = new BABYLON.Mesh(name, scene);
  44886. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44887. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  44888. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  44889. vertexData.applyToMesh(polyhedron, options.updatable);
  44890. return polyhedron;
  44891. };
  44892. /**
  44893. * Creates a decal mesh.
  44894. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  44895. * 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.
  44896. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  44897. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  44898. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  44899. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  44900. */
  44901. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  44902. var indices = sourceMesh.getIndices();
  44903. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44904. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44905. var position = options.position || BABYLON.Vector3.Zero();
  44906. var normal = options.normal || BABYLON.Vector3.Up();
  44907. var size = options.size || BABYLON.Vector3.One();
  44908. var angle = options.angle || 0;
  44909. // Getting correct rotation
  44910. if (!normal) {
  44911. var target = new BABYLON.Vector3(0, 0, 1);
  44912. var camera = sourceMesh.getScene().activeCamera;
  44913. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  44914. normal = camera.globalPosition.subtract(cameraWorldTarget);
  44915. }
  44916. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  44917. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  44918. var pitch = Math.atan2(normal.y, len);
  44919. // Matrix
  44920. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  44921. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  44922. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  44923. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  44924. var vertexData = new BABYLON.VertexData();
  44925. vertexData.indices = [];
  44926. vertexData.positions = [];
  44927. vertexData.normals = [];
  44928. vertexData.uvs = [];
  44929. var currentVertexDataIndex = 0;
  44930. var extractDecalVector3 = function (indexId) {
  44931. var vertexId = indices[indexId];
  44932. var result = new BABYLON.PositionNormalVertex();
  44933. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  44934. // Send vector to decal local world
  44935. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  44936. // Get normal
  44937. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  44938. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  44939. return result;
  44940. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  44941. var clip = function (vertices, axis) {
  44942. if (vertices.length === 0) {
  44943. return vertices;
  44944. }
  44945. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  44946. var clipVertices = function (v0, v1) {
  44947. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  44948. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  44949. };
  44950. var result = new Array();
  44951. for (var index = 0; index < vertices.length; index += 3) {
  44952. var v1Out;
  44953. var v2Out;
  44954. var v3Out;
  44955. var total = 0;
  44956. var nV1, nV2, nV3, nV4;
  44957. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  44958. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  44959. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  44960. v1Out = d1 > 0;
  44961. v2Out = d2 > 0;
  44962. v3Out = d3 > 0;
  44963. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  44964. switch (total) {
  44965. case 0:
  44966. result.push(vertices[index]);
  44967. result.push(vertices[index + 1]);
  44968. result.push(vertices[index + 2]);
  44969. break;
  44970. case 1:
  44971. if (v1Out) {
  44972. nV1 = vertices[index + 1];
  44973. nV2 = vertices[index + 2];
  44974. nV3 = clipVertices(vertices[index], nV1);
  44975. nV4 = clipVertices(vertices[index], nV2);
  44976. }
  44977. if (v2Out) {
  44978. nV1 = vertices[index];
  44979. nV2 = vertices[index + 2];
  44980. nV3 = clipVertices(vertices[index + 1], nV1);
  44981. nV4 = clipVertices(vertices[index + 1], nV2);
  44982. result.push(nV3);
  44983. result.push(nV2.clone());
  44984. result.push(nV1.clone());
  44985. result.push(nV2.clone());
  44986. result.push(nV3.clone());
  44987. result.push(nV4);
  44988. break;
  44989. }
  44990. if (v3Out) {
  44991. nV1 = vertices[index];
  44992. nV2 = vertices[index + 1];
  44993. nV3 = clipVertices(vertices[index + 2], nV1);
  44994. nV4 = clipVertices(vertices[index + 2], nV2);
  44995. }
  44996. result.push(nV1.clone());
  44997. result.push(nV2.clone());
  44998. result.push(nV3);
  44999. result.push(nV4);
  45000. result.push(nV3.clone());
  45001. result.push(nV2.clone());
  45002. break;
  45003. case 2:
  45004. if (!v1Out) {
  45005. nV1 = vertices[index].clone();
  45006. nV2 = clipVertices(nV1, vertices[index + 1]);
  45007. nV3 = clipVertices(nV1, vertices[index + 2]);
  45008. result.push(nV1);
  45009. result.push(nV2);
  45010. result.push(nV3);
  45011. }
  45012. if (!v2Out) {
  45013. nV1 = vertices[index + 1].clone();
  45014. nV2 = clipVertices(nV1, vertices[index + 2]);
  45015. nV3 = clipVertices(nV1, vertices[index]);
  45016. result.push(nV1);
  45017. result.push(nV2);
  45018. result.push(nV3);
  45019. }
  45020. if (!v3Out) {
  45021. nV1 = vertices[index + 2].clone();
  45022. nV2 = clipVertices(nV1, vertices[index]);
  45023. nV3 = clipVertices(nV1, vertices[index + 1]);
  45024. result.push(nV1);
  45025. result.push(nV2);
  45026. result.push(nV3);
  45027. }
  45028. break;
  45029. case 3:
  45030. break;
  45031. }
  45032. }
  45033. return result;
  45034. };
  45035. for (var index = 0; index < indices.length; index += 3) {
  45036. var faceVertices = new Array();
  45037. faceVertices.push(extractDecalVector3(index));
  45038. faceVertices.push(extractDecalVector3(index + 1));
  45039. faceVertices.push(extractDecalVector3(index + 2));
  45040. // Clip
  45041. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  45042. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  45043. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  45044. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  45045. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  45046. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  45047. if (faceVertices.length === 0) {
  45048. continue;
  45049. }
  45050. // Add UVs and get back to world
  45051. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  45052. var vertex = faceVertices[vIndex];
  45053. //TODO check for Int32Array | Uint32Array | Uint16Array
  45054. vertexData.indices.push(currentVertexDataIndex);
  45055. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  45056. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  45057. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  45058. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  45059. currentVertexDataIndex++;
  45060. }
  45061. }
  45062. // Return mesh
  45063. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  45064. vertexData.applyToMesh(decal);
  45065. decal.position = position.clone();
  45066. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  45067. return decal;
  45068. };
  45069. // Privates
  45070. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  45071. // extrusion geometry
  45072. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  45073. var tangents = path3D.getTangents();
  45074. var normals = path3D.getNormals();
  45075. var binormals = path3D.getBinormals();
  45076. var distances = path3D.getDistances();
  45077. var angle = 0;
  45078. var returnScale = function () { return scale; };
  45079. var returnRotation = function () { return rotation; };
  45080. var rotate = custom ? rotateFunction : returnRotation;
  45081. var scl = custom ? scaleFunction : returnScale;
  45082. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  45083. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  45084. for (var i = 0; i < curve.length; i++) {
  45085. var shapePath = new Array();
  45086. var angleStep = rotate(i, distances[i]);
  45087. var scaleRatio = scl(i, distances[i]);
  45088. for (var p = 0; p < shape.length; p++) {
  45089. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  45090. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  45091. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  45092. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  45093. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  45094. shapePath[p] = rotated;
  45095. }
  45096. shapePaths[index] = shapePath;
  45097. angle += angleStep;
  45098. index++;
  45099. }
  45100. // cap
  45101. var capPath = function (shapePath) {
  45102. var pointCap = Array();
  45103. var barycenter = BABYLON.Vector3.Zero();
  45104. var i;
  45105. for (i = 0; i < shapePath.length; i++) {
  45106. barycenter.addInPlace(shapePath[i]);
  45107. }
  45108. barycenter.scaleInPlace(1.0 / shapePath.length);
  45109. for (i = 0; i < shapePath.length; i++) {
  45110. pointCap.push(barycenter);
  45111. }
  45112. return pointCap;
  45113. };
  45114. switch (cap) {
  45115. case BABYLON.Mesh.NO_CAP:
  45116. break;
  45117. case BABYLON.Mesh.CAP_START:
  45118. shapePaths[0] = capPath(shapePaths[2]);
  45119. shapePaths[1] = shapePaths[2];
  45120. break;
  45121. case BABYLON.Mesh.CAP_END:
  45122. shapePaths[index] = shapePaths[index - 1];
  45123. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  45124. break;
  45125. case BABYLON.Mesh.CAP_ALL:
  45126. shapePaths[0] = capPath(shapePaths[2]);
  45127. shapePaths[1] = shapePaths[2];
  45128. shapePaths[index] = shapePaths[index - 1];
  45129. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  45130. break;
  45131. default:
  45132. break;
  45133. }
  45134. return shapePaths;
  45135. };
  45136. var path3D;
  45137. var pathArray;
  45138. if (instance) {
  45139. path3D = (instance.path3D).update(curve);
  45140. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  45141. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  45142. return instance;
  45143. }
  45144. // extruded shape creation
  45145. path3D = new BABYLON.Path3D(curve);
  45146. var newShapePaths = new Array();
  45147. cap = (cap < 0 || cap > 3) ? 0 : cap;
  45148. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  45149. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  45150. extrudedGeneric.pathArray = pathArray;
  45151. extrudedGeneric.path3D = path3D;
  45152. extrudedGeneric.cap = cap;
  45153. return extrudedGeneric;
  45154. };
  45155. return MeshBuilder;
  45156. }());
  45157. BABYLON.MeshBuilder = MeshBuilder;
  45158. })(BABYLON || (BABYLON = {}));
  45159. //# sourceMappingURL=babylon.meshBuilder.js.map
  45160. var BABYLON;
  45161. (function (BABYLON) {
  45162. var AudioEngine = (function () {
  45163. function AudioEngine() {
  45164. this._audioContext = null;
  45165. this._audioContextInitialized = false;
  45166. this.canUseWebAudio = false;
  45167. this.WarnedWebAudioUnsupported = false;
  45168. this.unlocked = false;
  45169. this.isMP3supported = false;
  45170. this.isOGGsupported = false;
  45171. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  45172. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  45173. this.canUseWebAudio = true;
  45174. }
  45175. var audioElem = document.createElement('audio');
  45176. try {
  45177. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  45178. this.isMP3supported = true;
  45179. }
  45180. }
  45181. catch (e) {
  45182. // protect error during capability check.
  45183. }
  45184. try {
  45185. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  45186. this.isOGGsupported = true;
  45187. }
  45188. }
  45189. catch (e) {
  45190. // protect error during capability check.
  45191. }
  45192. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  45193. this._unlockiOSaudio();
  45194. }
  45195. else {
  45196. this.unlocked = true;
  45197. }
  45198. }
  45199. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  45200. get: function () {
  45201. if (!this._audioContextInitialized) {
  45202. this._initializeAudioContext();
  45203. }
  45204. return this._audioContext;
  45205. },
  45206. enumerable: true,
  45207. configurable: true
  45208. });
  45209. AudioEngine.prototype._unlockiOSaudio = function () {
  45210. var _this = this;
  45211. var unlockaudio = function () {
  45212. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  45213. var source = _this.audioContext.createBufferSource();
  45214. source.buffer = buffer;
  45215. source.connect(_this.audioContext.destination);
  45216. source.start(0);
  45217. setTimeout(function () {
  45218. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  45219. _this.unlocked = true;
  45220. window.removeEventListener('touchend', unlockaudio, false);
  45221. if (_this.onAudioUnlocked) {
  45222. _this.onAudioUnlocked();
  45223. }
  45224. }
  45225. }, 0);
  45226. };
  45227. window.addEventListener('touchend', unlockaudio, false);
  45228. };
  45229. AudioEngine.prototype._initializeAudioContext = function () {
  45230. try {
  45231. if (this.canUseWebAudio) {
  45232. this._audioContext = new AudioContext();
  45233. // create a global volume gain node
  45234. this.masterGain = this._audioContext.createGain();
  45235. this.masterGain.gain.value = 1;
  45236. this.masterGain.connect(this._audioContext.destination);
  45237. this._audioContextInitialized = true;
  45238. }
  45239. }
  45240. catch (e) {
  45241. this.canUseWebAudio = false;
  45242. BABYLON.Tools.Error("Web Audio: " + e.message);
  45243. }
  45244. };
  45245. AudioEngine.prototype.dispose = function () {
  45246. if (this.canUseWebAudio && this._audioContextInitialized) {
  45247. if (this._connectedAnalyser) {
  45248. this._connectedAnalyser.stopDebugCanvas();
  45249. this._connectedAnalyser.dispose();
  45250. this.masterGain.disconnect();
  45251. this.masterGain.connect(this._audioContext.destination);
  45252. this._connectedAnalyser = null;
  45253. }
  45254. this.masterGain.gain.value = 1;
  45255. }
  45256. this.WarnedWebAudioUnsupported = false;
  45257. };
  45258. AudioEngine.prototype.getGlobalVolume = function () {
  45259. if (this.canUseWebAudio && this._audioContextInitialized) {
  45260. return this.masterGain.gain.value;
  45261. }
  45262. else {
  45263. return -1;
  45264. }
  45265. };
  45266. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  45267. if (this.canUseWebAudio && this._audioContextInitialized) {
  45268. this.masterGain.gain.value = newVolume;
  45269. }
  45270. };
  45271. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  45272. if (this._connectedAnalyser) {
  45273. this._connectedAnalyser.stopDebugCanvas();
  45274. }
  45275. if (this.canUseWebAudio && this._audioContextInitialized) {
  45276. this._connectedAnalyser = analyser;
  45277. this.masterGain.disconnect();
  45278. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  45279. }
  45280. };
  45281. return AudioEngine;
  45282. }());
  45283. BABYLON.AudioEngine = AudioEngine;
  45284. })(BABYLON || (BABYLON = {}));
  45285. //# sourceMappingURL=babylon.audioEngine.js.map
  45286. var BABYLON;
  45287. (function (BABYLON) {
  45288. var Sound = (function () {
  45289. /**
  45290. * Create a sound and attach it to a scene
  45291. * @param name Name of your sound
  45292. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  45293. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  45294. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  45295. */
  45296. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  45297. var _this = this;
  45298. this.autoplay = false;
  45299. this.loop = false;
  45300. this.useCustomAttenuation = false;
  45301. this.spatialSound = false;
  45302. this.refDistance = 1;
  45303. this.rolloffFactor = 1;
  45304. this.maxDistance = 100;
  45305. this.distanceModel = "linear";
  45306. this._panningModel = "equalpower";
  45307. this._playbackRate = 1;
  45308. this._streaming = false;
  45309. this._startTime = 0;
  45310. this._startOffset = 0;
  45311. this._position = BABYLON.Vector3.Zero();
  45312. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  45313. this._volume = 1;
  45314. this._isLoaded = false;
  45315. this._isReadyToPlay = false;
  45316. this.isPlaying = false;
  45317. this.isPaused = false;
  45318. this._isDirectional = false;
  45319. // Used if you'd like to create a directional sound.
  45320. // If not set, the sound will be omnidirectional
  45321. this._coneInnerAngle = 360;
  45322. this._coneOuterAngle = 360;
  45323. this._coneOuterGain = 0;
  45324. this._isOutputConnected = false;
  45325. this._urlType = "Unknown";
  45326. this.name = name;
  45327. this._scene = scene;
  45328. this._readyToPlayCallback = readyToPlayCallback;
  45329. // Default custom attenuation function is a linear attenuation
  45330. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  45331. if (currentDistance < maxDistance) {
  45332. return currentVolume * (1 - currentDistance / maxDistance);
  45333. }
  45334. else {
  45335. return 0;
  45336. }
  45337. };
  45338. if (options) {
  45339. this.autoplay = options.autoplay || false;
  45340. this.loop = options.loop || false;
  45341. // if volume === 0, we need another way to check this option
  45342. if (options.volume !== undefined) {
  45343. this._volume = options.volume;
  45344. }
  45345. this.spatialSound = options.spatialSound || false;
  45346. this.maxDistance = options.maxDistance || 100;
  45347. this.useCustomAttenuation = options.useCustomAttenuation || false;
  45348. this.rolloffFactor = options.rolloffFactor || 1;
  45349. this.refDistance = options.refDistance || 1;
  45350. this.distanceModel = options.distanceModel || "linear";
  45351. this._playbackRate = options.playbackRate || 1;
  45352. this._streaming = options.streaming || false;
  45353. }
  45354. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45355. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  45356. this._soundGain.gain.value = this._volume;
  45357. this._inputAudioNode = this._soundGain;
  45358. this._ouputAudioNode = this._soundGain;
  45359. if (this.spatialSound) {
  45360. this._createSpatialParameters();
  45361. }
  45362. this._scene.mainSoundTrack.AddSound(this);
  45363. var validParameter = true;
  45364. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  45365. if (urlOrArrayBuffer) {
  45366. if (typeof (urlOrArrayBuffer) === "string")
  45367. this._urlType = "String";
  45368. if (Array.isArray(urlOrArrayBuffer))
  45369. this._urlType = "Array";
  45370. if (urlOrArrayBuffer instanceof ArrayBuffer)
  45371. this._urlType = "ArrayBuffer";
  45372. var urls = [];
  45373. var codecSupportedFound = false;
  45374. switch (this._urlType) {
  45375. case "ArrayBuffer":
  45376. if (urlOrArrayBuffer.byteLength > 0) {
  45377. codecSupportedFound = true;
  45378. this._soundLoaded(urlOrArrayBuffer);
  45379. }
  45380. break;
  45381. case "String":
  45382. urls.push(urlOrArrayBuffer);
  45383. case "Array":
  45384. if (urls.length === 0)
  45385. urls = urlOrArrayBuffer;
  45386. // If we found a supported format, we load it immediately and stop the loop
  45387. for (var i = 0; i < urls.length; i++) {
  45388. var url = urls[i];
  45389. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  45390. codecSupportedFound = true;
  45391. }
  45392. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  45393. codecSupportedFound = true;
  45394. }
  45395. if (url.indexOf(".wav", url.length - 4) !== -1) {
  45396. codecSupportedFound = true;
  45397. }
  45398. if (url.indexOf("blob:") !== -1) {
  45399. codecSupportedFound = true;
  45400. }
  45401. if (codecSupportedFound) {
  45402. // Loading sound using XHR2
  45403. if (!this._streaming) {
  45404. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  45405. }
  45406. else {
  45407. this._htmlAudioElement = new Audio(url);
  45408. this._htmlAudioElement.controls = false;
  45409. this._htmlAudioElement.loop = this.loop;
  45410. this._htmlAudioElement.crossOrigin = "anonymous";
  45411. this._htmlAudioElement.preload = "auto";
  45412. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  45413. _this._isReadyToPlay = true;
  45414. if (_this.autoplay) {
  45415. _this.play();
  45416. }
  45417. if (_this._readyToPlayCallback) {
  45418. _this._readyToPlayCallback();
  45419. }
  45420. });
  45421. document.body.appendChild(this._htmlAudioElement);
  45422. }
  45423. break;
  45424. }
  45425. }
  45426. break;
  45427. default:
  45428. validParameter = false;
  45429. break;
  45430. }
  45431. if (!validParameter) {
  45432. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  45433. }
  45434. else {
  45435. if (!codecSupportedFound) {
  45436. this._isReadyToPlay = true;
  45437. // Simulating a ready to play event to avoid breaking code path
  45438. if (this._readyToPlayCallback) {
  45439. window.setTimeout(function () {
  45440. _this._readyToPlayCallback();
  45441. }, 1000);
  45442. }
  45443. }
  45444. }
  45445. }
  45446. }
  45447. else {
  45448. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  45449. this._scene.mainSoundTrack.AddSound(this);
  45450. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  45451. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  45452. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  45453. }
  45454. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  45455. if (this._readyToPlayCallback) {
  45456. window.setTimeout(function () {
  45457. _this._readyToPlayCallback();
  45458. }, 1000);
  45459. }
  45460. }
  45461. }
  45462. Sound.prototype.dispose = function () {
  45463. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  45464. if (this.isPlaying) {
  45465. this.stop();
  45466. }
  45467. this._isReadyToPlay = false;
  45468. if (this.soundTrackId === -1) {
  45469. this._scene.mainSoundTrack.RemoveSound(this);
  45470. }
  45471. else {
  45472. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  45473. }
  45474. if (this._soundGain) {
  45475. this._soundGain.disconnect();
  45476. this._soundGain = null;
  45477. }
  45478. if (this._soundPanner) {
  45479. this._soundPanner.disconnect();
  45480. this._soundPanner = null;
  45481. }
  45482. if (this._soundSource) {
  45483. this._soundSource.disconnect();
  45484. this._soundSource = null;
  45485. }
  45486. this._audioBuffer = null;
  45487. if (this._htmlAudioElement) {
  45488. this._htmlAudioElement.pause();
  45489. this._htmlAudioElement.src = "";
  45490. document.body.removeChild(this._htmlAudioElement);
  45491. }
  45492. if (this._connectedMesh) {
  45493. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45494. this._connectedMesh = null;
  45495. }
  45496. }
  45497. };
  45498. Sound.prototype.isReady = function () {
  45499. return this._isReadyToPlay;
  45500. };
  45501. Sound.prototype._soundLoaded = function (audioData) {
  45502. var _this = this;
  45503. this._isLoaded = true;
  45504. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  45505. _this._audioBuffer = buffer;
  45506. _this._isReadyToPlay = true;
  45507. if (_this.autoplay) {
  45508. _this.play();
  45509. }
  45510. if (_this._readyToPlayCallback) {
  45511. _this._readyToPlayCallback();
  45512. }
  45513. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  45514. };
  45515. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  45516. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45517. this._audioBuffer = audioBuffer;
  45518. this._isReadyToPlay = true;
  45519. }
  45520. };
  45521. Sound.prototype.updateOptions = function (options) {
  45522. if (options) {
  45523. this.loop = options.loop || this.loop;
  45524. this.maxDistance = options.maxDistance || this.maxDistance;
  45525. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  45526. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  45527. this.refDistance = options.refDistance || this.refDistance;
  45528. this.distanceModel = options.distanceModel || this.distanceModel;
  45529. this._playbackRate = options.playbackRate || this._playbackRate;
  45530. this._updateSpatialParameters();
  45531. if (this.isPlaying) {
  45532. if (this._streaming) {
  45533. this._htmlAudioElement.playbackRate = this._playbackRate;
  45534. }
  45535. else {
  45536. this._soundSource.playbackRate.value = this._playbackRate;
  45537. }
  45538. }
  45539. }
  45540. };
  45541. Sound.prototype._createSpatialParameters = function () {
  45542. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45543. if (this._scene.headphone) {
  45544. this._panningModel = "HRTF";
  45545. }
  45546. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  45547. this._updateSpatialParameters();
  45548. this._soundPanner.connect(this._ouputAudioNode);
  45549. this._inputAudioNode = this._soundPanner;
  45550. }
  45551. };
  45552. Sound.prototype._updateSpatialParameters = function () {
  45553. if (this.spatialSound) {
  45554. if (this.useCustomAttenuation) {
  45555. // Tricks to disable in a way embedded Web Audio attenuation
  45556. this._soundPanner.distanceModel = "linear";
  45557. this._soundPanner.maxDistance = Number.MAX_VALUE;
  45558. this._soundPanner.refDistance = 1;
  45559. this._soundPanner.rolloffFactor = 1;
  45560. this._soundPanner.panningModel = this._panningModel;
  45561. }
  45562. else {
  45563. this._soundPanner.distanceModel = this.distanceModel;
  45564. this._soundPanner.maxDistance = this.maxDistance;
  45565. this._soundPanner.refDistance = this.refDistance;
  45566. this._soundPanner.rolloffFactor = this.rolloffFactor;
  45567. this._soundPanner.panningModel = this._panningModel;
  45568. }
  45569. }
  45570. };
  45571. Sound.prototype.switchPanningModelToHRTF = function () {
  45572. this._panningModel = "HRTF";
  45573. this._switchPanningModel();
  45574. };
  45575. Sound.prototype.switchPanningModelToEqualPower = function () {
  45576. this._panningModel = "equalpower";
  45577. this._switchPanningModel();
  45578. };
  45579. Sound.prototype._switchPanningModel = function () {
  45580. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45581. this._soundPanner.panningModel = this._panningModel;
  45582. }
  45583. };
  45584. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  45585. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45586. if (this._isOutputConnected) {
  45587. this._ouputAudioNode.disconnect();
  45588. }
  45589. this._ouputAudioNode.connect(soundTrackAudioNode);
  45590. this._isOutputConnected = true;
  45591. }
  45592. };
  45593. /**
  45594. * Transform this sound into a directional source
  45595. * @param coneInnerAngle Size of the inner cone in degree
  45596. * @param coneOuterAngle Size of the outer cone in degree
  45597. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  45598. */
  45599. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  45600. if (coneOuterAngle < coneInnerAngle) {
  45601. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  45602. return;
  45603. }
  45604. this._coneInnerAngle = coneInnerAngle;
  45605. this._coneOuterAngle = coneOuterAngle;
  45606. this._coneOuterGain = coneOuterGain;
  45607. this._isDirectional = true;
  45608. if (this.isPlaying && this.loop) {
  45609. this.stop();
  45610. this.play();
  45611. }
  45612. };
  45613. Sound.prototype.setPosition = function (newPosition) {
  45614. this._position = newPosition;
  45615. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45616. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45617. }
  45618. };
  45619. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  45620. this._localDirection = newLocalDirection;
  45621. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  45622. this._updateDirection();
  45623. }
  45624. };
  45625. Sound.prototype._updateDirection = function () {
  45626. var mat = this._connectedMesh.getWorldMatrix();
  45627. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  45628. direction.normalize();
  45629. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  45630. };
  45631. Sound.prototype.updateDistanceFromListener = function () {
  45632. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  45633. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  45634. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  45635. }
  45636. };
  45637. Sound.prototype.setAttenuationFunction = function (callback) {
  45638. this._customAttenuationFunction = callback;
  45639. };
  45640. /**
  45641. * Play the sound
  45642. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  45643. * @param offset (optional) Start the sound setting it at a specific time
  45644. */
  45645. Sound.prototype.play = function (time, offset) {
  45646. var _this = this;
  45647. if (this._isReadyToPlay && this._scene.audioEnabled) {
  45648. try {
  45649. if (this._startOffset < 0) {
  45650. time = -this._startOffset;
  45651. this._startOffset = 0;
  45652. }
  45653. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45654. if (!this._soundSource || !this._streamingSource) {
  45655. if (this.spatialSound) {
  45656. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45657. if (this._isDirectional) {
  45658. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  45659. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  45660. this._soundPanner.coneOuterGain = this._coneOuterGain;
  45661. if (this._connectedMesh) {
  45662. this._updateDirection();
  45663. }
  45664. else {
  45665. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  45666. }
  45667. }
  45668. }
  45669. }
  45670. if (this._streaming) {
  45671. if (!this._streamingSource) {
  45672. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  45673. this._htmlAudioElement.onended = function () { _this._onended(); };
  45674. this._htmlAudioElement.playbackRate = this._playbackRate;
  45675. }
  45676. this._streamingSource.disconnect();
  45677. this._streamingSource.connect(this._inputAudioNode);
  45678. this._htmlAudioElement.play();
  45679. }
  45680. else {
  45681. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  45682. this._soundSource.buffer = this._audioBuffer;
  45683. this._soundSource.connect(this._inputAudioNode);
  45684. this._soundSource.loop = this.loop;
  45685. this._soundSource.playbackRate.value = this._playbackRate;
  45686. this._soundSource.onended = function () { _this._onended(); };
  45687. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  45688. }
  45689. this._startTime = startTime;
  45690. this.isPlaying = true;
  45691. this.isPaused = false;
  45692. }
  45693. catch (ex) {
  45694. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  45695. }
  45696. }
  45697. };
  45698. Sound.prototype._onended = function () {
  45699. this.isPlaying = false;
  45700. if (this.onended) {
  45701. this.onended();
  45702. }
  45703. };
  45704. /**
  45705. * Stop the sound
  45706. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  45707. */
  45708. Sound.prototype.stop = function (time) {
  45709. if (this.isPlaying) {
  45710. if (this._streaming) {
  45711. this._htmlAudioElement.pause();
  45712. // Test needed for Firefox or it will generate an Invalid State Error
  45713. if (this._htmlAudioElement.currentTime > 0) {
  45714. this._htmlAudioElement.currentTime = 0;
  45715. }
  45716. }
  45717. else {
  45718. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45719. this._soundSource.stop(stopTime);
  45720. this._soundSource.onended = null;
  45721. if (!this.isPaused) {
  45722. this._startOffset = 0;
  45723. }
  45724. }
  45725. this.isPlaying = false;
  45726. }
  45727. };
  45728. Sound.prototype.pause = function () {
  45729. if (this.isPlaying) {
  45730. this.isPaused = true;
  45731. if (this._streaming) {
  45732. this._htmlAudioElement.pause();
  45733. }
  45734. else {
  45735. this.stop(0);
  45736. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  45737. }
  45738. }
  45739. };
  45740. Sound.prototype.setVolume = function (newVolume, time) {
  45741. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45742. if (time) {
  45743. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  45744. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  45745. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  45746. }
  45747. else {
  45748. this._soundGain.gain.value = newVolume;
  45749. }
  45750. }
  45751. this._volume = newVolume;
  45752. };
  45753. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  45754. this._playbackRate = newPlaybackRate;
  45755. if (this.isPlaying) {
  45756. if (this._streaming) {
  45757. this._htmlAudioElement.playbackRate = this._playbackRate;
  45758. }
  45759. else {
  45760. this._soundSource.playbackRate.value = this._playbackRate;
  45761. }
  45762. }
  45763. };
  45764. Sound.prototype.getVolume = function () {
  45765. return this._volume;
  45766. };
  45767. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  45768. var _this = this;
  45769. if (this._connectedMesh) {
  45770. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45771. this._registerFunc = null;
  45772. }
  45773. this._connectedMesh = meshToConnectTo;
  45774. if (!this.spatialSound) {
  45775. this.spatialSound = true;
  45776. this._createSpatialParameters();
  45777. if (this.isPlaying && this.loop) {
  45778. this.stop();
  45779. this.play();
  45780. }
  45781. }
  45782. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  45783. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  45784. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  45785. };
  45786. Sound.prototype.detachFromMesh = function () {
  45787. if (this._connectedMesh) {
  45788. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45789. this._registerFunc = null;
  45790. this._connectedMesh = null;
  45791. }
  45792. };
  45793. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  45794. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  45795. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  45796. this._updateDirection();
  45797. }
  45798. };
  45799. Sound.prototype.clone = function () {
  45800. var _this = this;
  45801. if (!this._streaming) {
  45802. var setBufferAndRun = function () {
  45803. if (_this._isReadyToPlay) {
  45804. clonedSound._audioBuffer = _this.getAudioBuffer();
  45805. clonedSound._isReadyToPlay = true;
  45806. if (clonedSound.autoplay) {
  45807. clonedSound.play();
  45808. }
  45809. }
  45810. else {
  45811. window.setTimeout(setBufferAndRun, 300);
  45812. }
  45813. };
  45814. var currentOptions = {
  45815. autoplay: this.autoplay, loop: this.loop,
  45816. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  45817. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  45818. refDistance: this.refDistance, distanceModel: this.distanceModel
  45819. };
  45820. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  45821. if (this.useCustomAttenuation) {
  45822. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  45823. }
  45824. clonedSound.setPosition(this._position);
  45825. clonedSound.setPlaybackRate(this._playbackRate);
  45826. setBufferAndRun();
  45827. return clonedSound;
  45828. }
  45829. else {
  45830. return null;
  45831. }
  45832. };
  45833. Sound.prototype.getAudioBuffer = function () {
  45834. return this._audioBuffer;
  45835. };
  45836. Sound.prototype.serialize = function () {
  45837. var serializationObject = {
  45838. name: this.name,
  45839. url: this.name,
  45840. autoplay: this.autoplay,
  45841. loop: this.loop,
  45842. volume: this._volume,
  45843. spatialSound: this.spatialSound,
  45844. maxDistance: this.maxDistance,
  45845. rolloffFactor: this.rolloffFactor,
  45846. refDistance: this.refDistance,
  45847. distanceModel: this.distanceModel,
  45848. playbackRate: this._playbackRate,
  45849. panningModel: this._panningModel,
  45850. soundTrackId: this.soundTrackId
  45851. };
  45852. if (this.spatialSound) {
  45853. if (this._connectedMesh)
  45854. serializationObject.connectedMeshId = this._connectedMesh.id;
  45855. serializationObject.position = this._position.asArray();
  45856. serializationObject.refDistance = this.refDistance;
  45857. serializationObject.distanceModel = this.distanceModel;
  45858. serializationObject.isDirectional = this._isDirectional;
  45859. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  45860. serializationObject.coneInnerAngle = this._coneInnerAngle;
  45861. serializationObject.coneOuterAngle = this._coneOuterAngle;
  45862. serializationObject.coneOuterGain = this._coneOuterGain;
  45863. }
  45864. return serializationObject;
  45865. };
  45866. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  45867. var soundName = parsedSound.name;
  45868. var soundUrl;
  45869. if (parsedSound.url) {
  45870. soundUrl = rootUrl + parsedSound.url;
  45871. }
  45872. else {
  45873. soundUrl = rootUrl + soundName;
  45874. }
  45875. var options = {
  45876. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  45877. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  45878. rolloffFactor: parsedSound.rolloffFactor,
  45879. refDistance: parsedSound.refDistance,
  45880. distanceModel: parsedSound.distanceModel,
  45881. playbackRate: parsedSound.playbackRate
  45882. };
  45883. var newSound;
  45884. if (!sourceSound) {
  45885. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  45886. scene._addPendingData(newSound);
  45887. }
  45888. else {
  45889. var setBufferAndRun = function () {
  45890. if (sourceSound._isReadyToPlay) {
  45891. newSound._audioBuffer = sourceSound.getAudioBuffer();
  45892. newSound._isReadyToPlay = true;
  45893. if (newSound.autoplay) {
  45894. newSound.play();
  45895. }
  45896. }
  45897. else {
  45898. window.setTimeout(setBufferAndRun, 300);
  45899. }
  45900. };
  45901. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  45902. setBufferAndRun();
  45903. }
  45904. if (parsedSound.position) {
  45905. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  45906. newSound.setPosition(soundPosition);
  45907. }
  45908. if (parsedSound.isDirectional) {
  45909. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  45910. if (parsedSound.localDirectionToMesh) {
  45911. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  45912. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  45913. }
  45914. }
  45915. if (parsedSound.connectedMeshId) {
  45916. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  45917. if (connectedMesh) {
  45918. newSound.attachToMesh(connectedMesh);
  45919. }
  45920. }
  45921. return newSound;
  45922. };
  45923. return Sound;
  45924. }());
  45925. BABYLON.Sound = Sound;
  45926. })(BABYLON || (BABYLON = {}));
  45927. //# sourceMappingURL=babylon.sound.js.map
  45928. var BABYLON;
  45929. (function (BABYLON) {
  45930. var SoundTrack = (function () {
  45931. function SoundTrack(scene, options) {
  45932. this.id = -1;
  45933. this._isMainTrack = false;
  45934. this._isInitialized = false;
  45935. this._scene = scene;
  45936. this.soundCollection = new Array();
  45937. this._options = options;
  45938. if (!this._isMainTrack) {
  45939. this._scene.soundTracks.push(this);
  45940. this.id = this._scene.soundTracks.length - 1;
  45941. }
  45942. }
  45943. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  45944. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45945. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  45946. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  45947. if (this._options) {
  45948. if (this._options.volume) {
  45949. this._outputAudioNode.gain.value = this._options.volume;
  45950. }
  45951. if (this._options.mainTrack) {
  45952. this._isMainTrack = this._options.mainTrack;
  45953. }
  45954. }
  45955. this._isInitialized = true;
  45956. }
  45957. };
  45958. SoundTrack.prototype.dispose = function () {
  45959. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45960. if (this._connectedAnalyser) {
  45961. this._connectedAnalyser.stopDebugCanvas();
  45962. }
  45963. while (this.soundCollection.length) {
  45964. this.soundCollection[0].dispose();
  45965. }
  45966. if (this._outputAudioNode) {
  45967. this._outputAudioNode.disconnect();
  45968. }
  45969. this._outputAudioNode = null;
  45970. }
  45971. };
  45972. SoundTrack.prototype.AddSound = function (sound) {
  45973. if (!this._isInitialized) {
  45974. this._initializeSoundTrackAudioGraph();
  45975. }
  45976. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45977. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  45978. }
  45979. if (sound.soundTrackId) {
  45980. if (sound.soundTrackId === -1) {
  45981. this._scene.mainSoundTrack.RemoveSound(sound);
  45982. }
  45983. else {
  45984. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  45985. }
  45986. }
  45987. this.soundCollection.push(sound);
  45988. sound.soundTrackId = this.id;
  45989. };
  45990. SoundTrack.prototype.RemoveSound = function (sound) {
  45991. var index = this.soundCollection.indexOf(sound);
  45992. if (index !== -1) {
  45993. this.soundCollection.splice(index, 1);
  45994. }
  45995. };
  45996. SoundTrack.prototype.setVolume = function (newVolume) {
  45997. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45998. this._outputAudioNode.gain.value = newVolume;
  45999. }
  46000. };
  46001. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  46002. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46003. for (var i = 0; i < this.soundCollection.length; i++) {
  46004. this.soundCollection[i].switchPanningModelToHRTF();
  46005. }
  46006. }
  46007. };
  46008. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  46009. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46010. for (var i = 0; i < this.soundCollection.length; i++) {
  46011. this.soundCollection[i].switchPanningModelToEqualPower();
  46012. }
  46013. }
  46014. };
  46015. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  46016. if (this._connectedAnalyser) {
  46017. this._connectedAnalyser.stopDebugCanvas();
  46018. }
  46019. this._connectedAnalyser = analyser;
  46020. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46021. this._outputAudioNode.disconnect();
  46022. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  46023. }
  46024. };
  46025. return SoundTrack;
  46026. }());
  46027. BABYLON.SoundTrack = SoundTrack;
  46028. })(BABYLON || (BABYLON = {}));
  46029. //# sourceMappingURL=babylon.soundtrack.js.map
  46030. var BABYLON;
  46031. (function (BABYLON) {
  46032. var Analyser = (function () {
  46033. function Analyser(scene) {
  46034. this.SMOOTHING = 0.75;
  46035. this.FFT_SIZE = 512;
  46036. this.BARGRAPHAMPLITUDE = 256;
  46037. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  46038. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  46039. this._scene = scene;
  46040. this._audioEngine = BABYLON.Engine.audioEngine;
  46041. if (this._audioEngine.canUseWebAudio) {
  46042. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  46043. this._webAudioAnalyser.minDecibels = -140;
  46044. this._webAudioAnalyser.maxDecibels = 0;
  46045. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46046. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46047. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  46048. }
  46049. }
  46050. Analyser.prototype.getFrequencyBinCount = function () {
  46051. if (this._audioEngine.canUseWebAudio) {
  46052. return this._webAudioAnalyser.frequencyBinCount;
  46053. }
  46054. else {
  46055. return 0;
  46056. }
  46057. };
  46058. Analyser.prototype.getByteFrequencyData = function () {
  46059. if (this._audioEngine.canUseWebAudio) {
  46060. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46061. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46062. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  46063. }
  46064. return this._byteFreqs;
  46065. };
  46066. Analyser.prototype.getByteTimeDomainData = function () {
  46067. if (this._audioEngine.canUseWebAudio) {
  46068. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46069. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46070. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  46071. }
  46072. return this._byteTime;
  46073. };
  46074. Analyser.prototype.getFloatFrequencyData = function () {
  46075. if (this._audioEngine.canUseWebAudio) {
  46076. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46077. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46078. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  46079. }
  46080. return this._floatFreqs;
  46081. };
  46082. Analyser.prototype.drawDebugCanvas = function () {
  46083. var _this = this;
  46084. if (this._audioEngine.canUseWebAudio) {
  46085. if (!this._debugCanvas) {
  46086. this._debugCanvas = document.createElement("canvas");
  46087. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  46088. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  46089. this._debugCanvas.style.position = "absolute";
  46090. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  46091. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  46092. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  46093. document.body.appendChild(this._debugCanvas);
  46094. this._registerFunc = function () {
  46095. _this.drawDebugCanvas();
  46096. };
  46097. this._scene.registerBeforeRender(this._registerFunc);
  46098. }
  46099. if (this._registerFunc) {
  46100. var workingArray = this.getByteFrequencyData();
  46101. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  46102. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  46103. // Draw the frequency domain chart.
  46104. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  46105. var value = workingArray[i];
  46106. var percent = value / this.BARGRAPHAMPLITUDE;
  46107. var height = this.DEBUGCANVASSIZE.height * percent;
  46108. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  46109. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  46110. var hue = i / this.getFrequencyBinCount() * 360;
  46111. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  46112. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  46113. }
  46114. }
  46115. }
  46116. };
  46117. Analyser.prototype.stopDebugCanvas = function () {
  46118. if (this._debugCanvas) {
  46119. this._scene.unregisterBeforeRender(this._registerFunc);
  46120. this._registerFunc = null;
  46121. document.body.removeChild(this._debugCanvas);
  46122. this._debugCanvas = null;
  46123. this._debugCanvasContext = null;
  46124. }
  46125. };
  46126. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  46127. if (this._audioEngine.canUseWebAudio) {
  46128. inputAudioNode.connect(this._webAudioAnalyser);
  46129. this._webAudioAnalyser.connect(outputAudioNode);
  46130. }
  46131. };
  46132. Analyser.prototype.dispose = function () {
  46133. if (this._audioEngine.canUseWebAudio) {
  46134. this._webAudioAnalyser.disconnect();
  46135. }
  46136. };
  46137. return Analyser;
  46138. }());
  46139. BABYLON.Analyser = Analyser;
  46140. })(BABYLON || (BABYLON = {}));
  46141. //# sourceMappingURL=babylon.analyser.js.map
  46142. var BABYLON;
  46143. (function (BABYLON) {
  46144. var CubeTexture = (function (_super) {
  46145. __extends(CubeTexture, _super);
  46146. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  46147. if (onLoad === void 0) { onLoad = null; }
  46148. if (onError === void 0) { onError = null; }
  46149. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  46150. if (prefiltered === void 0) { prefiltered = false; }
  46151. if (forcedExtension === void 0) { forcedExtension = null; }
  46152. var _this = _super.call(this, scene) || this;
  46153. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  46154. _this.name = rootUrl;
  46155. _this.url = rootUrl;
  46156. _this._noMipmap = noMipmap;
  46157. _this.hasAlpha = false;
  46158. _this._format = format;
  46159. _this._prefiltered = prefiltered;
  46160. _this.isCube = true;
  46161. _this._textureMatrix = BABYLON.Matrix.Identity();
  46162. if (prefiltered) {
  46163. _this.gammaSpace = false;
  46164. }
  46165. if (!rootUrl && !files) {
  46166. return _this;
  46167. }
  46168. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  46169. if (!files) {
  46170. if (!extensions) {
  46171. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  46172. }
  46173. files = [];
  46174. for (var index = 0; index < extensions.length; index++) {
  46175. files.push(rootUrl + extensions[index]);
  46176. }
  46177. _this._extensions = extensions;
  46178. }
  46179. _this._files = files;
  46180. if (!_this._texture) {
  46181. if (!scene.useDelayedTextureLoading) {
  46182. if (prefiltered) {
  46183. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  46184. }
  46185. else {
  46186. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  46187. }
  46188. }
  46189. else {
  46190. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  46191. }
  46192. }
  46193. else if (onLoad) {
  46194. if (_this._texture.isReady) {
  46195. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  46196. }
  46197. else {
  46198. _this._texture.onLoadedObservable.add(onLoad);
  46199. }
  46200. }
  46201. return _this;
  46202. }
  46203. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  46204. return new CubeTexture("", scene, null, noMipmap, files);
  46205. };
  46206. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  46207. if (forcedExtension === void 0) { forcedExtension = null; }
  46208. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  46209. };
  46210. // Methods
  46211. CubeTexture.prototype.delayLoad = function () {
  46212. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  46213. return;
  46214. }
  46215. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  46216. this._texture = this._getFromCache(this.url, this._noMipmap);
  46217. if (!this._texture) {
  46218. if (this._prefiltered) {
  46219. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  46220. }
  46221. else {
  46222. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  46223. }
  46224. }
  46225. };
  46226. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  46227. return this._textureMatrix;
  46228. };
  46229. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  46230. this._textureMatrix = value;
  46231. };
  46232. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  46233. var texture = BABYLON.SerializationHelper.Parse(function () {
  46234. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  46235. }, parsedTexture, scene);
  46236. // Animations
  46237. if (parsedTexture.animations) {
  46238. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  46239. var parsedAnimation = parsedTexture.animations[animationIndex];
  46240. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46241. }
  46242. }
  46243. return texture;
  46244. };
  46245. CubeTexture.prototype.clone = function () {
  46246. var _this = this;
  46247. return BABYLON.SerializationHelper.Clone(function () {
  46248. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  46249. }, this);
  46250. };
  46251. return CubeTexture;
  46252. }(BABYLON.BaseTexture));
  46253. BABYLON.CubeTexture = CubeTexture;
  46254. })(BABYLON || (BABYLON = {}));
  46255. //# sourceMappingURL=babylon.cubeTexture.js.map
  46256. var BABYLON;
  46257. (function (BABYLON) {
  46258. var RenderTargetTexture = (function (_super) {
  46259. __extends(RenderTargetTexture, _super);
  46260. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  46261. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  46262. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46263. if (isCube === void 0) { isCube = false; }
  46264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46265. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46266. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  46267. if (isMulti === void 0) { isMulti = false; }
  46268. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  46269. _this.isCube = isCube;
  46270. /**
  46271. * Use this list to define the list of mesh you want to render.
  46272. */
  46273. _this.renderList = new Array();
  46274. _this.renderParticles = true;
  46275. _this.renderSprites = false;
  46276. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  46277. _this.ignoreCameraViewport = false;
  46278. // Events
  46279. /**
  46280. * An event triggered when the texture is unbind.
  46281. * @type {BABYLON.Observable}
  46282. */
  46283. _this.onBeforeBindObservable = new BABYLON.Observable();
  46284. /**
  46285. * An event triggered when the texture is unbind.
  46286. * @type {BABYLON.Observable}
  46287. */
  46288. _this.onAfterUnbindObservable = new BABYLON.Observable();
  46289. /**
  46290. * An event triggered before rendering the texture
  46291. * @type {BABYLON.Observable}
  46292. */
  46293. _this.onBeforeRenderObservable = new BABYLON.Observable();
  46294. /**
  46295. * An event triggered after rendering the texture
  46296. * @type {BABYLON.Observable}
  46297. */
  46298. _this.onAfterRenderObservable = new BABYLON.Observable();
  46299. /**
  46300. * An event triggered after the texture clear
  46301. * @type {BABYLON.Observable}
  46302. */
  46303. _this.onClearObservable = new BABYLON.Observable();
  46304. _this._currentRefreshId = -1;
  46305. _this._refreshRate = 1;
  46306. _this._samples = 1;
  46307. scene = _this.getScene();
  46308. _this.name = name;
  46309. _this.isRenderTarget = true;
  46310. _this._size = size;
  46311. _this._generateMipMaps = generateMipMaps;
  46312. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  46313. // Rendering groups
  46314. _this._renderingManager = new BABYLON.RenderingManager(scene);
  46315. if (isMulti) {
  46316. return _this;
  46317. }
  46318. _this._renderTargetOptions = {
  46319. generateMipMaps: generateMipMaps,
  46320. type: type,
  46321. samplingMode: samplingMode,
  46322. generateDepthBuffer: generateDepthBuffer,
  46323. generateStencilBuffer: generateStencilBuffer
  46324. };
  46325. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  46326. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46327. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46328. }
  46329. if (isCube) {
  46330. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  46331. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  46332. _this._textureMatrix = BABYLON.Matrix.Identity();
  46333. }
  46334. else {
  46335. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  46336. }
  46337. return _this;
  46338. }
  46339. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  46340. get: function () {
  46341. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  46342. },
  46343. enumerable: true,
  46344. configurable: true
  46345. });
  46346. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  46347. get: function () {
  46348. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  46349. },
  46350. enumerable: true,
  46351. configurable: true
  46352. });
  46353. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  46354. get: function () {
  46355. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  46356. },
  46357. enumerable: true,
  46358. configurable: true
  46359. });
  46360. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  46361. set: function (callback) {
  46362. if (this._onAfterUnbindObserver) {
  46363. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  46364. }
  46365. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  46366. },
  46367. enumerable: true,
  46368. configurable: true
  46369. });
  46370. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  46371. set: function (callback) {
  46372. if (this._onBeforeRenderObserver) {
  46373. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  46374. }
  46375. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  46376. },
  46377. enumerable: true,
  46378. configurable: true
  46379. });
  46380. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  46381. set: function (callback) {
  46382. if (this._onAfterRenderObserver) {
  46383. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  46384. }
  46385. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  46386. },
  46387. enumerable: true,
  46388. configurable: true
  46389. });
  46390. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  46391. set: function (callback) {
  46392. if (this._onClearObserver) {
  46393. this.onClearObservable.remove(this._onClearObserver);
  46394. }
  46395. this._onClearObserver = this.onClearObservable.add(callback);
  46396. },
  46397. enumerable: true,
  46398. configurable: true
  46399. });
  46400. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  46401. get: function () {
  46402. return this._renderTargetOptions;
  46403. },
  46404. enumerable: true,
  46405. configurable: true
  46406. });
  46407. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  46408. get: function () {
  46409. return this._samples;
  46410. },
  46411. set: function (value) {
  46412. if (this._samples === value) {
  46413. return;
  46414. }
  46415. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  46416. },
  46417. enumerable: true,
  46418. configurable: true
  46419. });
  46420. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  46421. this._currentRefreshId = -1;
  46422. };
  46423. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  46424. get: function () {
  46425. return this._refreshRate;
  46426. },
  46427. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  46428. set: function (value) {
  46429. this._refreshRate = value;
  46430. this.resetRefreshCounter();
  46431. },
  46432. enumerable: true,
  46433. configurable: true
  46434. });
  46435. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  46436. if (!this._postProcessManager) {
  46437. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  46438. this._postProcesses = new Array();
  46439. }
  46440. this._postProcesses.push(postProcess);
  46441. this._postProcesses[0].autoClear = false;
  46442. };
  46443. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  46444. if (!this._postProcesses) {
  46445. return;
  46446. }
  46447. if (dispose) {
  46448. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  46449. var postProcess = _a[_i];
  46450. postProcess.dispose();
  46451. postProcess = null;
  46452. }
  46453. }
  46454. this._postProcesses = [];
  46455. };
  46456. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  46457. if (!this._postProcesses) {
  46458. return;
  46459. }
  46460. var index = this._postProcesses.indexOf(postProcess);
  46461. if (index === -1) {
  46462. return;
  46463. }
  46464. this._postProcesses.splice(index, 1);
  46465. if (this._postProcesses.length > 0) {
  46466. this._postProcesses[0].autoClear = false;
  46467. }
  46468. };
  46469. RenderTargetTexture.prototype._shouldRender = function () {
  46470. if (this._currentRefreshId === -1) {
  46471. this._currentRefreshId = 1;
  46472. return true;
  46473. }
  46474. if (this.refreshRate === this._currentRefreshId) {
  46475. this._currentRefreshId = 1;
  46476. return true;
  46477. }
  46478. this._currentRefreshId++;
  46479. return false;
  46480. };
  46481. RenderTargetTexture.prototype.getRenderSize = function () {
  46482. return this._size;
  46483. };
  46484. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  46485. get: function () {
  46486. return true;
  46487. },
  46488. enumerable: true,
  46489. configurable: true
  46490. });
  46491. RenderTargetTexture.prototype.scale = function (ratio) {
  46492. var newSize = this._size * ratio;
  46493. this.resize(newSize);
  46494. };
  46495. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  46496. if (this.isCube) {
  46497. return this._textureMatrix;
  46498. }
  46499. return _super.prototype.getReflectionTextureMatrix.call(this);
  46500. };
  46501. RenderTargetTexture.prototype.resize = function (size) {
  46502. this.releaseInternalTexture();
  46503. if (this.isCube) {
  46504. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  46505. }
  46506. else {
  46507. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  46508. }
  46509. this._size = size;
  46510. };
  46511. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  46512. var scene = this.getScene();
  46513. var engine = scene.getEngine();
  46514. if (this.useCameraPostProcesses !== undefined) {
  46515. useCameraPostProcess = this.useCameraPostProcesses;
  46516. }
  46517. if (this._waitingRenderList) {
  46518. this.renderList = [];
  46519. for (var index = 0; index < this._waitingRenderList.length; index++) {
  46520. var id = this._waitingRenderList[index];
  46521. this.renderList.push(scene.getMeshByID(id));
  46522. }
  46523. delete this._waitingRenderList;
  46524. }
  46525. // Is predicate defined?
  46526. if (this.renderListPredicate) {
  46527. this.renderList.splice(0); // Clear previous renderList
  46528. var sceneMeshes = this.getScene().meshes;
  46529. for (var index = 0; index < sceneMeshes.length; index++) {
  46530. var mesh = sceneMeshes[index];
  46531. if (this.renderListPredicate(mesh)) {
  46532. this.renderList.push(mesh);
  46533. }
  46534. }
  46535. }
  46536. if (this.renderList && this.renderList.length === 0) {
  46537. return;
  46538. }
  46539. this.onBeforeBindObservable.notifyObservers(this);
  46540. // Set custom projection.
  46541. // Needs to be before binding to prevent changing the aspect ratio.
  46542. var camera;
  46543. if (this.activeCamera) {
  46544. camera = this.activeCamera;
  46545. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  46546. if (this.activeCamera !== scene.activeCamera) {
  46547. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  46548. }
  46549. }
  46550. else {
  46551. camera = scene.activeCamera;
  46552. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  46553. }
  46554. // Prepare renderingManager
  46555. this._renderingManager.reset();
  46556. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  46557. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  46558. var sceneRenderId = scene.getRenderId();
  46559. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  46560. var mesh = currentRenderList[meshIndex];
  46561. if (mesh) {
  46562. if (!mesh.isReady()) {
  46563. // Reset _currentRefreshId
  46564. this.resetRefreshCounter();
  46565. continue;
  46566. }
  46567. mesh._preActivateForIntermediateRendering(sceneRenderId);
  46568. var isMasked = void 0;
  46569. if (!this.renderList) {
  46570. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  46571. }
  46572. else {
  46573. isMasked = false;
  46574. }
  46575. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  46576. mesh._activate(sceneRenderId);
  46577. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  46578. var subMesh = mesh.subMeshes[subIndex];
  46579. scene._activeIndices.addCount(subMesh.indexCount, false);
  46580. this._renderingManager.dispatch(subMesh);
  46581. }
  46582. }
  46583. }
  46584. }
  46585. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  46586. var particleSystem = scene.particleSystems[particleIndex];
  46587. var emitter = particleSystem.emitter;
  46588. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  46589. continue;
  46590. }
  46591. if (currentRenderList.indexOf(emitter) >= 0) {
  46592. this._renderingManager.dispatchParticles(particleSystem);
  46593. }
  46594. }
  46595. if (this.isCube) {
  46596. for (var face = 0; face < 6; face++) {
  46597. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46598. scene.incrementRenderId();
  46599. scene.resetCachedMaterial();
  46600. }
  46601. }
  46602. else {
  46603. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46604. }
  46605. this.onAfterUnbindObservable.notifyObservers(this);
  46606. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  46607. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  46608. }
  46609. engine.setViewport(scene.activeCamera.viewport);
  46610. scene.resetCachedMaterial();
  46611. };
  46612. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  46613. var _this = this;
  46614. var scene = this.getScene();
  46615. var engine = scene.getEngine();
  46616. // Bind
  46617. if (this._postProcessManager) {
  46618. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  46619. }
  46620. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  46621. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  46622. }
  46623. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  46624. // Clear
  46625. if (this.onClearObservable.hasObservers()) {
  46626. this.onClearObservable.notifyObservers(engine);
  46627. }
  46628. else {
  46629. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  46630. }
  46631. if (!this._doNotChangeAspectRatio) {
  46632. scene.updateTransformMatrix(true);
  46633. }
  46634. // Render
  46635. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  46636. if (this._postProcessManager) {
  46637. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  46638. }
  46639. else if (useCameraPostProcess) {
  46640. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  46641. }
  46642. if (!this._doNotChangeAspectRatio) {
  46643. scene.updateTransformMatrix(true);
  46644. }
  46645. // Dump ?
  46646. if (dumpForDebug) {
  46647. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  46648. }
  46649. // Unbind
  46650. if (!this.isCube || faceIndex === 5) {
  46651. if (this.isCube) {
  46652. if (faceIndex === 5) {
  46653. engine.generateMipMapsForCubemap(this._texture);
  46654. }
  46655. }
  46656. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  46657. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  46658. });
  46659. }
  46660. else {
  46661. this.onAfterRenderObservable.notifyObservers(faceIndex);
  46662. }
  46663. };
  46664. /**
  46665. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  46666. * This allowed control for front to back rendering or reversly depending of the special needs.
  46667. *
  46668. * @param renderingGroupId The rendering group id corresponding to its index
  46669. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  46670. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  46671. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  46672. */
  46673. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  46674. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  46675. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  46676. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  46677. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  46678. };
  46679. /**
  46680. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  46681. *
  46682. * @param renderingGroupId The rendering group id corresponding to its index
  46683. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  46684. */
  46685. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  46686. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  46687. };
  46688. RenderTargetTexture.prototype.clone = function () {
  46689. var textureSize = this.getSize();
  46690. 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);
  46691. // Base texture
  46692. newTexture.hasAlpha = this.hasAlpha;
  46693. newTexture.level = this.level;
  46694. // RenderTarget Texture
  46695. newTexture.coordinatesMode = this.coordinatesMode;
  46696. newTexture.renderList = this.renderList.slice(0);
  46697. return newTexture;
  46698. };
  46699. RenderTargetTexture.prototype.serialize = function () {
  46700. if (!this.name) {
  46701. return null;
  46702. }
  46703. var serializationObject = _super.prototype.serialize.call(this);
  46704. serializationObject.renderTargetSize = this.getRenderSize();
  46705. serializationObject.renderList = [];
  46706. for (var index = 0; index < this.renderList.length; index++) {
  46707. serializationObject.renderList.push(this.renderList[index].id);
  46708. }
  46709. return serializationObject;
  46710. };
  46711. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  46712. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  46713. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  46714. };
  46715. RenderTargetTexture.prototype.dispose = function () {
  46716. if (this._postProcessManager) {
  46717. this._postProcessManager.dispose();
  46718. this._postProcessManager = null;
  46719. }
  46720. this.clearPostProcesses(true);
  46721. this.renderList = null;
  46722. // Remove from custom render targets
  46723. var scene = this.getScene();
  46724. var index = scene.customRenderTargets.indexOf(this);
  46725. if (index >= 0) {
  46726. scene.customRenderTargets.splice(index, 1);
  46727. }
  46728. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  46729. var camera = _a[_i];
  46730. index = camera.customRenderTargets.indexOf(this);
  46731. if (index >= 0) {
  46732. camera.customRenderTargets.splice(index, 1);
  46733. }
  46734. }
  46735. _super.prototype.dispose.call(this);
  46736. };
  46737. RenderTargetTexture.prototype._rebuild = function () {
  46738. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  46739. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  46740. }
  46741. if (this._postProcessManager) {
  46742. this._postProcessManager._rebuild();
  46743. }
  46744. };
  46745. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  46746. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  46747. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  46748. return RenderTargetTexture;
  46749. }(BABYLON.Texture));
  46750. BABYLON.RenderTargetTexture = RenderTargetTexture;
  46751. })(BABYLON || (BABYLON = {}));
  46752. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  46753. var BABYLON;
  46754. (function (BABYLON) {
  46755. ;
  46756. var MultiRenderTarget = (function (_super) {
  46757. __extends(MultiRenderTarget, _super);
  46758. function MultiRenderTarget(name, size, count, scene, options) {
  46759. var _this = this;
  46760. options = options || {};
  46761. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  46762. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  46763. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  46764. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  46765. if (!_this.isSupported) {
  46766. _this.dispose();
  46767. return;
  46768. }
  46769. var types = [];
  46770. var samplingModes = [];
  46771. for (var i = 0; i < count; i++) {
  46772. if (options.types && options.types[i]) {
  46773. types.push(options.types[i]);
  46774. }
  46775. else {
  46776. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  46777. }
  46778. if (options.samplingModes && options.samplingModes[i]) {
  46779. samplingModes.push(options.samplingModes[i]);
  46780. }
  46781. else {
  46782. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46783. }
  46784. }
  46785. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  46786. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  46787. _this._count = count;
  46788. _this._size = size;
  46789. _this._multiRenderTargetOptions = {
  46790. samplingModes: samplingModes,
  46791. generateMipMaps: generateMipMaps,
  46792. generateDepthBuffer: generateDepthBuffer,
  46793. generateStencilBuffer: generateStencilBuffer,
  46794. generateDepthTexture: generateDepthTexture,
  46795. types: types,
  46796. textureCount: count
  46797. };
  46798. _this._createInternalTextures();
  46799. _this._createTextures();
  46800. return _this;
  46801. }
  46802. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  46803. get: function () {
  46804. var engine = this.getScene().getEngine();
  46805. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  46806. },
  46807. enumerable: true,
  46808. configurable: true
  46809. });
  46810. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  46811. get: function () {
  46812. return this._textures;
  46813. },
  46814. enumerable: true,
  46815. configurable: true
  46816. });
  46817. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  46818. get: function () {
  46819. return this._textures[this._textures.length - 1];
  46820. },
  46821. enumerable: true,
  46822. configurable: true
  46823. });
  46824. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  46825. set: function (wrap) {
  46826. if (this._textures) {
  46827. for (var i = 0; i < this._textures.length; i++) {
  46828. this._textures[i].wrapU = wrap;
  46829. }
  46830. }
  46831. },
  46832. enumerable: true,
  46833. configurable: true
  46834. });
  46835. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  46836. set: function (wrap) {
  46837. if (this._textures) {
  46838. for (var i = 0; i < this._textures.length; i++) {
  46839. this._textures[i].wrapV = wrap;
  46840. }
  46841. }
  46842. },
  46843. enumerable: true,
  46844. configurable: true
  46845. });
  46846. MultiRenderTarget.prototype._rebuild = function () {
  46847. this.releaseInternalTextures();
  46848. this._createInternalTextures();
  46849. for (var i = 0; i < this._internalTextures.length; i++) {
  46850. var texture = this._textures[i];
  46851. texture._texture = this._internalTextures[i];
  46852. }
  46853. // Keeps references to frame buffer and stencil/depth buffer
  46854. this._texture = this._internalTextures[0];
  46855. };
  46856. MultiRenderTarget.prototype._createInternalTextures = function () {
  46857. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  46858. };
  46859. MultiRenderTarget.prototype._createTextures = function () {
  46860. this._textures = [];
  46861. for (var i = 0; i < this._internalTextures.length; i++) {
  46862. var texture = new BABYLON.Texture(null, this.getScene());
  46863. texture._texture = this._internalTextures[i];
  46864. this._textures.push(texture);
  46865. }
  46866. // Keeps references to frame buffer and stencil/depth buffer
  46867. this._texture = this._internalTextures[0];
  46868. };
  46869. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  46870. get: function () {
  46871. return this._samples;
  46872. },
  46873. set: function (value) {
  46874. if (this._samples === value) {
  46875. return;
  46876. }
  46877. for (var i = 0; i < this._internalTextures.length; i++) {
  46878. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  46879. }
  46880. },
  46881. enumerable: true,
  46882. configurable: true
  46883. });
  46884. MultiRenderTarget.prototype.resize = function (size) {
  46885. this.releaseInternalTextures();
  46886. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  46887. this._createInternalTextures();
  46888. };
  46889. MultiRenderTarget.prototype.dispose = function () {
  46890. this.releaseInternalTextures();
  46891. _super.prototype.dispose.call(this);
  46892. };
  46893. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  46894. if (!this._internalTextures) {
  46895. return;
  46896. }
  46897. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  46898. if (this._internalTextures[i] !== undefined) {
  46899. this._internalTextures[i].dispose();
  46900. this._internalTextures.splice(i, 1);
  46901. }
  46902. }
  46903. };
  46904. return MultiRenderTarget;
  46905. }(BABYLON.RenderTargetTexture));
  46906. BABYLON.MultiRenderTarget = MultiRenderTarget;
  46907. })(BABYLON || (BABYLON = {}));
  46908. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  46909. /// <reference path="babylon.renderTargetTexture.ts" />
  46910. var BABYLON;
  46911. (function (BABYLON) {
  46912. var MirrorTexture = (function (_super) {
  46913. __extends(MirrorTexture, _super);
  46914. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  46915. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46917. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46918. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  46919. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  46920. _this._transformMatrix = BABYLON.Matrix.Zero();
  46921. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  46922. _this._blurKernelX = 0;
  46923. _this._blurKernelY = 0;
  46924. _this._blurRatio = 1.0;
  46925. _this.ignoreCameraViewport = true;
  46926. _this.onBeforeRenderObservable.add(function () {
  46927. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  46928. _this._savedViewMatrix = scene.getViewMatrix();
  46929. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  46930. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  46931. scene.clipPlane = _this.mirrorPlane;
  46932. scene.getEngine().cullBackFaces = false;
  46933. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  46934. });
  46935. _this.onAfterRenderObservable.add(function () {
  46936. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  46937. scene.getEngine().cullBackFaces = true;
  46938. scene._mirroredCameraPosition = null;
  46939. delete scene.clipPlane;
  46940. });
  46941. return _this;
  46942. }
  46943. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  46944. get: function () {
  46945. return this._blurRatio;
  46946. },
  46947. set: function (value) {
  46948. if (this._blurRatio === value) {
  46949. return;
  46950. }
  46951. this._blurRatio = value;
  46952. this._preparePostProcesses();
  46953. },
  46954. enumerable: true,
  46955. configurable: true
  46956. });
  46957. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  46958. set: function (value) {
  46959. this.blurKernelX = value;
  46960. this.blurKernelY = value;
  46961. },
  46962. enumerable: true,
  46963. configurable: true
  46964. });
  46965. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  46966. get: function () {
  46967. return this._blurKernelX;
  46968. },
  46969. set: function (value) {
  46970. if (this._blurKernelX === value) {
  46971. return;
  46972. }
  46973. this._blurKernelX = value;
  46974. this._preparePostProcesses();
  46975. },
  46976. enumerable: true,
  46977. configurable: true
  46978. });
  46979. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  46980. get: function () {
  46981. return this._blurKernelY;
  46982. },
  46983. set: function (value) {
  46984. if (this._blurKernelY === value) {
  46985. return;
  46986. }
  46987. this._blurKernelY = value;
  46988. this._preparePostProcesses();
  46989. },
  46990. enumerable: true,
  46991. configurable: true
  46992. });
  46993. MirrorTexture.prototype._preparePostProcesses = function () {
  46994. this.clearPostProcesses(true);
  46995. if (this._blurKernelX && this._blurKernelY) {
  46996. var engine = this.getScene().getEngine();
  46997. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46998. 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);
  46999. this._blurX.autoClear = false;
  47000. if (this._blurRatio === 1 && this.samples < 2) {
  47001. this._blurX.outputTexture = this._texture;
  47002. }
  47003. else {
  47004. this._blurX.alwaysForcePOT = true;
  47005. }
  47006. 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);
  47007. this._blurY.autoClear = false;
  47008. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  47009. this.addPostProcess(this._blurX);
  47010. this.addPostProcess(this._blurY);
  47011. }
  47012. };
  47013. MirrorTexture.prototype.clone = function () {
  47014. var textureSize = this.getSize();
  47015. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  47016. // Base texture
  47017. newTexture.hasAlpha = this.hasAlpha;
  47018. newTexture.level = this.level;
  47019. // Mirror Texture
  47020. newTexture.mirrorPlane = this.mirrorPlane.clone();
  47021. newTexture.renderList = this.renderList.slice(0);
  47022. return newTexture;
  47023. };
  47024. MirrorTexture.prototype.serialize = function () {
  47025. if (!this.name) {
  47026. return null;
  47027. }
  47028. var serializationObject = _super.prototype.serialize.call(this);
  47029. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  47030. return serializationObject;
  47031. };
  47032. return MirrorTexture;
  47033. }(BABYLON.RenderTargetTexture));
  47034. BABYLON.MirrorTexture = MirrorTexture;
  47035. })(BABYLON || (BABYLON = {}));
  47036. //# sourceMappingURL=babylon.mirrorTexture.js.map
  47037. /// <reference path="babylon.renderTargetTexture.ts" />
  47038. var BABYLON;
  47039. (function (BABYLON) {
  47040. /**
  47041. * Creates a refraction texture used by refraction channel of the standard material.
  47042. * @param name the texture name
  47043. * @param size size of the underlying texture
  47044. * @param scene root scene
  47045. */
  47046. var RefractionTexture = (function (_super) {
  47047. __extends(RefractionTexture, _super);
  47048. function RefractionTexture(name, size, scene, generateMipMaps) {
  47049. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  47050. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  47051. _this.depth = 2.0;
  47052. _this.onBeforeRenderObservable.add(function () {
  47053. scene.clipPlane = _this.refractionPlane;
  47054. });
  47055. _this.onAfterRenderObservable.add(function () {
  47056. delete scene.clipPlane;
  47057. });
  47058. return _this;
  47059. }
  47060. RefractionTexture.prototype.clone = function () {
  47061. var textureSize = this.getSize();
  47062. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  47063. // Base texture
  47064. newTexture.hasAlpha = this.hasAlpha;
  47065. newTexture.level = this.level;
  47066. // Refraction Texture
  47067. newTexture.refractionPlane = this.refractionPlane.clone();
  47068. newTexture.renderList = this.renderList.slice(0);
  47069. newTexture.depth = this.depth;
  47070. return newTexture;
  47071. };
  47072. RefractionTexture.prototype.serialize = function () {
  47073. if (!this.name) {
  47074. return null;
  47075. }
  47076. var serializationObject = _super.prototype.serialize.call(this);
  47077. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  47078. serializationObject.depth = this.depth;
  47079. return serializationObject;
  47080. };
  47081. return RefractionTexture;
  47082. }(BABYLON.RenderTargetTexture));
  47083. BABYLON.RefractionTexture = RefractionTexture;
  47084. })(BABYLON || (BABYLON = {}));
  47085. //# sourceMappingURL=babylon.refractionTexture.js.map
  47086. /// <reference path="babylon.texture.ts" />
  47087. var BABYLON;
  47088. (function (BABYLON) {
  47089. var DynamicTexture = (function (_super) {
  47090. __extends(DynamicTexture, _super);
  47091. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  47092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47093. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  47094. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  47095. _this.name = name;
  47096. var engine = _this.getScene().getEngine();
  47097. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47098. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47099. _this._generateMipMaps = generateMipMaps;
  47100. if (options.getContext) {
  47101. _this._canvas = options;
  47102. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  47103. }
  47104. else {
  47105. _this._canvas = document.createElement("canvas");
  47106. if (options.width) {
  47107. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  47108. }
  47109. else {
  47110. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  47111. }
  47112. }
  47113. var textureSize = _this.getSize();
  47114. _this._canvas.width = textureSize.width;
  47115. _this._canvas.height = textureSize.height;
  47116. _this._context = _this._canvas.getContext("2d");
  47117. return _this;
  47118. }
  47119. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  47120. get: function () {
  47121. return true;
  47122. },
  47123. enumerable: true,
  47124. configurable: true
  47125. });
  47126. DynamicTexture.prototype._recreate = function (textureSize) {
  47127. this._canvas.width = textureSize.width;
  47128. this._canvas.height = textureSize.height;
  47129. this.releaseInternalTexture();
  47130. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  47131. };
  47132. DynamicTexture.prototype.scale = function (ratio) {
  47133. var textureSize = this.getSize();
  47134. textureSize.width *= ratio;
  47135. textureSize.height *= ratio;
  47136. this._recreate(textureSize);
  47137. };
  47138. DynamicTexture.prototype.scaleTo = function (width, height) {
  47139. var textureSize = this.getSize();
  47140. textureSize.width = width;
  47141. textureSize.height = height;
  47142. this._recreate(textureSize);
  47143. };
  47144. DynamicTexture.prototype.getContext = function () {
  47145. return this._context;
  47146. };
  47147. DynamicTexture.prototype.clear = function () {
  47148. var size = this.getSize();
  47149. this._context.fillRect(0, 0, size.width, size.height);
  47150. };
  47151. DynamicTexture.prototype.update = function (invertY) {
  47152. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  47153. };
  47154. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  47155. if (update === void 0) { update = true; }
  47156. var size = this.getSize();
  47157. if (clearColor) {
  47158. this._context.fillStyle = clearColor;
  47159. this._context.fillRect(0, 0, size.width, size.height);
  47160. }
  47161. this._context.font = font;
  47162. if (x === null || x === undefined) {
  47163. var textSize = this._context.measureText(text);
  47164. x = (size.width - textSize.width) / 2;
  47165. }
  47166. if (y === null || y === undefined) {
  47167. var fontSize = parseInt((font.replace(/\D/g, '')));
  47168. ;
  47169. y = (size.height / 2) + (fontSize / 3.65);
  47170. }
  47171. this._context.fillStyle = color;
  47172. this._context.fillText(text, x, y);
  47173. if (update) {
  47174. this.update(invertY);
  47175. }
  47176. };
  47177. DynamicTexture.prototype.clone = function () {
  47178. var textureSize = this.getSize();
  47179. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  47180. // Base texture
  47181. newTexture.hasAlpha = this.hasAlpha;
  47182. newTexture.level = this.level;
  47183. // Dynamic Texture
  47184. newTexture.wrapU = this.wrapU;
  47185. newTexture.wrapV = this.wrapV;
  47186. return newTexture;
  47187. };
  47188. DynamicTexture.prototype._rebuild = function () {
  47189. this.update();
  47190. };
  47191. return DynamicTexture;
  47192. }(BABYLON.Texture));
  47193. BABYLON.DynamicTexture = DynamicTexture;
  47194. })(BABYLON || (BABYLON = {}));
  47195. //# sourceMappingURL=babylon.dynamicTexture.js.map
  47196. var BABYLON;
  47197. (function (BABYLON) {
  47198. var VideoTexture = (function (_super) {
  47199. __extends(VideoTexture, _super);
  47200. /**
  47201. * Creates a video texture.
  47202. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  47203. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  47204. * @param {BABYLON.Scene} scene is obviously the current scene.
  47205. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  47206. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  47207. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  47208. */
  47209. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  47210. if (generateMipMaps === void 0) { generateMipMaps = false; }
  47211. if (invertY === void 0) { invertY = false; }
  47212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47213. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  47214. _this._autoLaunch = true;
  47215. var urls;
  47216. _this.name = name;
  47217. if (urlsOrVideo instanceof HTMLVideoElement) {
  47218. _this.video = urlsOrVideo;
  47219. }
  47220. else {
  47221. urls = urlsOrVideo;
  47222. _this.video = document.createElement("video");
  47223. _this.video.autoplay = false;
  47224. _this.video.loop = true;
  47225. }
  47226. _this._generateMipMaps = generateMipMaps;
  47227. _this._samplingMode = samplingMode;
  47228. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  47229. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47230. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47231. }
  47232. else {
  47233. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47234. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47235. _this._generateMipMaps = false;
  47236. }
  47237. if (urls) {
  47238. _this.video.addEventListener("canplay", function () {
  47239. _this._createTexture();
  47240. });
  47241. urls.forEach(function (url) {
  47242. var source = document.createElement("source");
  47243. source.src = url;
  47244. _this.video.appendChild(source);
  47245. });
  47246. }
  47247. else {
  47248. _this._createTexture();
  47249. }
  47250. _this._lastUpdate = BABYLON.Tools.Now;
  47251. return _this;
  47252. }
  47253. VideoTexture.prototype.__setTextureReady = function () {
  47254. this._texture.isReady = true;
  47255. };
  47256. VideoTexture.prototype._createTexture = function () {
  47257. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  47258. if (this._autoLaunch) {
  47259. this._autoLaunch = false;
  47260. this.video.play();
  47261. }
  47262. this._setTextureReady = this.__setTextureReady.bind(this);
  47263. this.video.addEventListener("playing", this._setTextureReady);
  47264. };
  47265. VideoTexture.prototype._rebuild = function () {
  47266. this.update();
  47267. };
  47268. VideoTexture.prototype.update = function () {
  47269. var now = BABYLON.Tools.Now;
  47270. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  47271. return false;
  47272. }
  47273. this._lastUpdate = now;
  47274. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  47275. return true;
  47276. };
  47277. VideoTexture.prototype.dispose = function () {
  47278. _super.prototype.dispose.call(this);
  47279. this.video.removeEventListener("playing", this._setTextureReady);
  47280. };
  47281. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  47282. var video = document.createElement("video");
  47283. var constraintsDeviceId;
  47284. if (constraints && constraints.deviceId) {
  47285. constraintsDeviceId = {
  47286. exact: constraints.deviceId
  47287. };
  47288. }
  47289. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  47290. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  47291. if (navigator.getUserMedia) {
  47292. navigator.getUserMedia({
  47293. video: {
  47294. deviceId: constraintsDeviceId,
  47295. width: {
  47296. min: (constraints && constraints.minWidth) || 256,
  47297. max: (constraints && constraints.maxWidth) || 640
  47298. },
  47299. height: {
  47300. min: (constraints && constraints.minHeight) || 256,
  47301. max: (constraints && constraints.maxHeight) || 480
  47302. }
  47303. }
  47304. }, function (stream) {
  47305. if (video.mozSrcObject !== undefined) {
  47306. video.mozSrcObject = stream;
  47307. }
  47308. else {
  47309. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  47310. }
  47311. video.play();
  47312. if (onReady) {
  47313. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  47314. }
  47315. }, function (e) {
  47316. BABYLON.Tools.Error(e.name);
  47317. });
  47318. }
  47319. };
  47320. return VideoTexture;
  47321. }(BABYLON.Texture));
  47322. BABYLON.VideoTexture = VideoTexture;
  47323. })(BABYLON || (BABYLON = {}));
  47324. //# sourceMappingURL=babylon.videoTexture.js.map
  47325. var BABYLON;
  47326. (function (BABYLON) {
  47327. var RawTexture = (function (_super) {
  47328. __extends(RawTexture, _super);
  47329. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  47330. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47331. if (invertY === void 0) { invertY = false; }
  47332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47333. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  47334. _this.format = format;
  47335. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  47336. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47337. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47338. return _this;
  47339. }
  47340. RawTexture.prototype.update = function (data) {
  47341. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  47342. };
  47343. // Statics
  47344. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47345. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47346. if (invertY === void 0) { invertY = false; }
  47347. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47348. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  47349. };
  47350. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47351. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47352. if (invertY === void 0) { invertY = false; }
  47353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47354. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47355. };
  47356. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47357. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47358. if (invertY === void 0) { invertY = false; }
  47359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47360. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  47361. };
  47362. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47363. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47364. if (invertY === void 0) { invertY = false; }
  47365. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47366. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  47367. };
  47368. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  47369. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47370. if (invertY === void 0) { invertY = false; }
  47371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47372. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  47373. };
  47374. return RawTexture;
  47375. }(BABYLON.Texture));
  47376. BABYLON.RawTexture = RawTexture;
  47377. })(BABYLON || (BABYLON = {}));
  47378. //# sourceMappingURL=babylon.rawTexture.js.map
  47379. var BABYLON;
  47380. (function (BABYLON) {
  47381. var PostProcess = (function () {
  47382. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  47383. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  47384. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47385. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  47386. if (blockCompilation === void 0) { blockCompilation = false; }
  47387. this.name = name;
  47388. this.width = -1;
  47389. this.height = -1;
  47390. this.autoClear = true;
  47391. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  47392. /*
  47393. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  47394. Can only be used on a single postprocess or on the last one of a chain.
  47395. */
  47396. this.enablePixelPerfectMode = false;
  47397. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  47398. this.alwaysForcePOT = false;
  47399. this.samples = 1;
  47400. this.adaptScaleToCurrentViewport = false;
  47401. this._reusable = false;
  47402. this._textures = new BABYLON.SmartArray(2);
  47403. this._currentRenderTextureInd = 0;
  47404. this._scaleRatio = new BABYLON.Vector2(1, 1);
  47405. this._texelSize = BABYLON.Vector2.Zero();
  47406. // Events
  47407. /**
  47408. * An event triggered when the postprocess is activated.
  47409. * @type {BABYLON.Observable}
  47410. */
  47411. this.onActivateObservable = new BABYLON.Observable();
  47412. /**
  47413. * An event triggered when the postprocess changes its size.
  47414. * @type {BABYLON.Observable}
  47415. */
  47416. this.onSizeChangedObservable = new BABYLON.Observable();
  47417. /**
  47418. * An event triggered when the postprocess applies its effect.
  47419. * @type {BABYLON.Observable}
  47420. */
  47421. this.onApplyObservable = new BABYLON.Observable();
  47422. /**
  47423. * An event triggered before rendering the postprocess
  47424. * @type {BABYLON.Observable}
  47425. */
  47426. this.onBeforeRenderObservable = new BABYLON.Observable();
  47427. /**
  47428. * An event triggered after rendering the postprocess
  47429. * @type {BABYLON.Observable}
  47430. */
  47431. this.onAfterRenderObservable = new BABYLON.Observable();
  47432. if (camera != null) {
  47433. this._camera = camera;
  47434. this._scene = camera.getScene();
  47435. camera.attachPostProcess(this);
  47436. this._engine = this._scene.getEngine();
  47437. this._scene.postProcesses.push(this);
  47438. }
  47439. else {
  47440. this._engine = engine;
  47441. this._engine.postProcesses.push(this);
  47442. }
  47443. this._options = options;
  47444. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  47445. this._reusable = reusable || false;
  47446. this._textureType = textureType;
  47447. this._samplers = samplers || [];
  47448. this._samplers.push("textureSampler");
  47449. this._fragmentUrl = fragmentUrl;
  47450. this._vertexUrl = vertexUrl;
  47451. this._parameters = parameters || [];
  47452. this._parameters.push("scale");
  47453. this._indexParameters = indexParameters;
  47454. if (!blockCompilation) {
  47455. this.updateEffect(defines);
  47456. }
  47457. }
  47458. Object.defineProperty(PostProcess.prototype, "onActivate", {
  47459. set: function (callback) {
  47460. if (this._onActivateObserver) {
  47461. this.onActivateObservable.remove(this._onActivateObserver);
  47462. }
  47463. this._onActivateObserver = this.onActivateObservable.add(callback);
  47464. },
  47465. enumerable: true,
  47466. configurable: true
  47467. });
  47468. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  47469. set: function (callback) {
  47470. if (this._onSizeChangedObserver) {
  47471. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  47472. }
  47473. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  47474. },
  47475. enumerable: true,
  47476. configurable: true
  47477. });
  47478. Object.defineProperty(PostProcess.prototype, "onApply", {
  47479. set: function (callback) {
  47480. if (this._onApplyObserver) {
  47481. this.onApplyObservable.remove(this._onApplyObserver);
  47482. }
  47483. this._onApplyObserver = this.onApplyObservable.add(callback);
  47484. },
  47485. enumerable: true,
  47486. configurable: true
  47487. });
  47488. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  47489. set: function (callback) {
  47490. if (this._onBeforeRenderObserver) {
  47491. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  47492. }
  47493. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  47494. },
  47495. enumerable: true,
  47496. configurable: true
  47497. });
  47498. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  47499. set: function (callback) {
  47500. if (this._onAfterRenderObserver) {
  47501. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  47502. }
  47503. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  47504. },
  47505. enumerable: true,
  47506. configurable: true
  47507. });
  47508. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  47509. get: function () {
  47510. return this._textures.data[this._currentRenderTextureInd];
  47511. },
  47512. set: function (value) {
  47513. this._forcedOutputTexture = value;
  47514. },
  47515. enumerable: true,
  47516. configurable: true
  47517. });
  47518. PostProcess.prototype.getCamera = function () {
  47519. return this._camera;
  47520. };
  47521. Object.defineProperty(PostProcess.prototype, "texelSize", {
  47522. get: function () {
  47523. if (this._shareOutputWithPostProcess) {
  47524. return this._shareOutputWithPostProcess.texelSize;
  47525. }
  47526. if (this._forcedOutputTexture) {
  47527. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  47528. }
  47529. return this._texelSize;
  47530. },
  47531. enumerable: true,
  47532. configurable: true
  47533. });
  47534. PostProcess.prototype.getEngine = function () {
  47535. return this._engine;
  47536. };
  47537. PostProcess.prototype.getEffect = function () {
  47538. return this._effect;
  47539. };
  47540. PostProcess.prototype.shareOutputWith = function (postProcess) {
  47541. this._disposeTextures();
  47542. this._shareOutputWithPostProcess = postProcess;
  47543. return this;
  47544. };
  47545. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  47546. 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);
  47547. };
  47548. PostProcess.prototype.isReusable = function () {
  47549. return this._reusable;
  47550. };
  47551. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  47552. PostProcess.prototype.markTextureDirty = function () {
  47553. this.width = -1;
  47554. };
  47555. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  47556. var _this = this;
  47557. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  47558. camera = camera || this._camera;
  47559. var scene = camera.getScene();
  47560. var engine = scene.getEngine();
  47561. var maxSize = engine.getCaps().maxTextureSize;
  47562. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  47563. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  47564. var desiredWidth = (this._options.width || requiredWidth);
  47565. var desiredHeight = this._options.height || requiredHeight;
  47566. if (this.adaptScaleToCurrentViewport) {
  47567. var currentViewport = engine.currentViewport;
  47568. if (currentViewport) {
  47569. desiredWidth *= currentViewport.width;
  47570. desiredHeight *= currentViewport.height;
  47571. }
  47572. }
  47573. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  47574. if (!this._options.width) {
  47575. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  47576. }
  47577. if (!this._options.height) {
  47578. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  47579. }
  47580. }
  47581. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  47582. if (this._textures.length > 0) {
  47583. for (var i = 0; i < this._textures.length; i++) {
  47584. this._engine._releaseTexture(this._textures.data[i]);
  47585. }
  47586. this._textures.reset();
  47587. }
  47588. this.width = desiredWidth;
  47589. this.height = desiredHeight;
  47590. var textureSize = { width: this.width, height: this.height };
  47591. var textureOptions = {
  47592. generateMipMaps: false,
  47593. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  47594. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  47595. samplingMode: this.renderTargetSamplingMode,
  47596. type: this._textureType
  47597. };
  47598. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47599. if (this._reusable) {
  47600. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47601. }
  47602. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  47603. this.onSizeChangedObservable.notifyObservers(this);
  47604. }
  47605. this._textures.forEach(function (texture) {
  47606. if (texture.samples !== _this.samples) {
  47607. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  47608. }
  47609. });
  47610. }
  47611. var target;
  47612. if (this._shareOutputWithPostProcess) {
  47613. target = this._shareOutputWithPostProcess.outputTexture;
  47614. }
  47615. else if (this._forcedOutputTexture) {
  47616. target = this._forcedOutputTexture;
  47617. this.width = this._forcedOutputTexture.width;
  47618. this.height = this._forcedOutputTexture.height;
  47619. }
  47620. else {
  47621. target = this.outputTexture;
  47622. }
  47623. if (this.enablePixelPerfectMode) {
  47624. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  47625. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  47626. }
  47627. else {
  47628. this._scaleRatio.copyFromFloats(1, 1);
  47629. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  47630. }
  47631. this.onActivateObservable.notifyObservers(camera);
  47632. // Clear
  47633. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  47634. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  47635. }
  47636. if (this._reusable) {
  47637. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  47638. }
  47639. };
  47640. Object.defineProperty(PostProcess.prototype, "isSupported", {
  47641. get: function () {
  47642. return this._effect.isSupported;
  47643. },
  47644. enumerable: true,
  47645. configurable: true
  47646. });
  47647. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  47648. get: function () {
  47649. if (this._shareOutputWithPostProcess) {
  47650. return this._shareOutputWithPostProcess.aspectRatio;
  47651. }
  47652. if (this._forcedOutputTexture) {
  47653. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  47654. }
  47655. return this.width / this.height;
  47656. },
  47657. enumerable: true,
  47658. configurable: true
  47659. });
  47660. PostProcess.prototype.apply = function () {
  47661. // Check
  47662. if (!this._effect || !this._effect.isReady())
  47663. return null;
  47664. // States
  47665. this._engine.enableEffect(this._effect);
  47666. this._engine.setState(false);
  47667. this._engine.setDepthBuffer(false);
  47668. this._engine.setDepthWrite(false);
  47669. // Alpha
  47670. this._engine.setAlphaMode(this.alphaMode);
  47671. if (this.alphaConstants) {
  47672. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  47673. }
  47674. // Texture
  47675. var source;
  47676. if (this._shareOutputWithPostProcess) {
  47677. source = this._shareOutputWithPostProcess.outputTexture;
  47678. }
  47679. else if (this._forcedOutputTexture) {
  47680. source = this._forcedOutputTexture;
  47681. }
  47682. else {
  47683. source = this.outputTexture;
  47684. }
  47685. this._effect._bindTexture("textureSampler", source);
  47686. // Parameters
  47687. this._effect.setVector2("scale", this._scaleRatio);
  47688. this.onApplyObservable.notifyObservers(this._effect);
  47689. return this._effect;
  47690. };
  47691. PostProcess.prototype._disposeTextures = function () {
  47692. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  47693. return;
  47694. }
  47695. if (this._textures.length > 0) {
  47696. for (var i = 0; i < this._textures.length; i++) {
  47697. this._engine._releaseTexture(this._textures.data[i]);
  47698. }
  47699. }
  47700. this._textures.dispose();
  47701. };
  47702. PostProcess.prototype.dispose = function (camera) {
  47703. camera = camera || this._camera;
  47704. this._disposeTextures();
  47705. if (this._scene) {
  47706. var index_1 = this._scene.postProcesses.indexOf(this);
  47707. if (index_1 !== -1) {
  47708. this._scene.postProcesses.splice(index_1, 1);
  47709. }
  47710. }
  47711. else {
  47712. var index_2 = this._engine.postProcesses.indexOf(this);
  47713. if (index_2 !== -1) {
  47714. this._engine.postProcesses.splice(index_2, 1);
  47715. }
  47716. }
  47717. if (!camera) {
  47718. return;
  47719. }
  47720. camera.detachPostProcess(this);
  47721. var index = camera._postProcesses.indexOf(this);
  47722. if (index === 0 && camera._postProcesses.length > 0) {
  47723. this._camera._postProcesses[0].markTextureDirty();
  47724. }
  47725. this.onActivateObservable.clear();
  47726. this.onAfterRenderObservable.clear();
  47727. this.onApplyObservable.clear();
  47728. this.onBeforeRenderObservable.clear();
  47729. this.onSizeChangedObservable.clear();
  47730. };
  47731. return PostProcess;
  47732. }());
  47733. BABYLON.PostProcess = PostProcess;
  47734. })(BABYLON || (BABYLON = {}));
  47735. //# sourceMappingURL=babylon.postProcess.js.map
  47736. var BABYLON;
  47737. (function (BABYLON) {
  47738. var PassPostProcess = (function (_super) {
  47739. __extends(PassPostProcess, _super);
  47740. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  47741. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47742. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  47743. }
  47744. return PassPostProcess;
  47745. }(BABYLON.PostProcess));
  47746. BABYLON.PassPostProcess = PassPostProcess;
  47747. })(BABYLON || (BABYLON = {}));
  47748. //# sourceMappingURL=babylon.passPostProcess.js.map
  47749. var BABYLON;
  47750. (function (BABYLON) {
  47751. var ShadowGenerator = (function () {
  47752. /**
  47753. * Creates a ShadowGenerator object.
  47754. * A ShadowGenerator is the required tool to use the shadows.
  47755. * Each light casting shadows needs to use its own ShadowGenerator.
  47756. * Required parameters :
  47757. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  47758. * - `light`: the light object generating the shadows.
  47759. * - `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.
  47760. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  47761. */
  47762. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  47763. // Members
  47764. this._bias = 0.00005;
  47765. this._blurBoxOffset = 1;
  47766. this._blurScale = 2;
  47767. this._blurKernel = 1;
  47768. this._useKernelBlur = false;
  47769. this._filter = ShadowGenerator.FILTER_NONE;
  47770. this._darkness = 0;
  47771. this._transparencyShadow = false;
  47772. /**
  47773. * Controls the extent to which the shadows fade out at the edge of the frustum
  47774. * Used only by directionals and spots
  47775. */
  47776. this.frustumEdgeFalloff = 0;
  47777. this.forceBackFacesOnly = false;
  47778. this._lightDirection = BABYLON.Vector3.Zero();
  47779. this._viewMatrix = BABYLON.Matrix.Zero();
  47780. this._projectionMatrix = BABYLON.Matrix.Zero();
  47781. this._transformMatrix = BABYLON.Matrix.Zero();
  47782. this._worldViewProjection = BABYLON.Matrix.Zero();
  47783. this._currentFaceIndex = 0;
  47784. this._currentFaceIndexCache = 0;
  47785. this._isCube = false;
  47786. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  47787. this._mapSize = mapSize;
  47788. this._light = light;
  47789. this._scene = light.getScene();
  47790. light._shadowGenerator = this;
  47791. // Texture type fallback from float to int if not supported.
  47792. var caps = this._scene.getEngine().getCaps();
  47793. if (!useFullFloatFirst) {
  47794. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47795. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47796. }
  47797. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47798. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47799. }
  47800. else {
  47801. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47802. }
  47803. }
  47804. else {
  47805. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47806. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47807. }
  47808. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47809. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47810. }
  47811. else {
  47812. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47813. }
  47814. }
  47815. this._initializeGenerator();
  47816. }
  47817. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  47818. // Static
  47819. get: function () {
  47820. return ShadowGenerator._FILTER_NONE;
  47821. },
  47822. enumerable: true,
  47823. configurable: true
  47824. });
  47825. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  47826. get: function () {
  47827. return ShadowGenerator._FILTER_POISSONSAMPLING;
  47828. },
  47829. enumerable: true,
  47830. configurable: true
  47831. });
  47832. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  47833. get: function () {
  47834. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  47835. },
  47836. enumerable: true,
  47837. configurable: true
  47838. });
  47839. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  47840. get: function () {
  47841. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  47842. },
  47843. enumerable: true,
  47844. configurable: true
  47845. });
  47846. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  47847. get: function () {
  47848. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47849. },
  47850. enumerable: true,
  47851. configurable: true
  47852. });
  47853. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  47854. get: function () {
  47855. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47856. },
  47857. enumerable: true,
  47858. configurable: true
  47859. });
  47860. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  47861. get: function () {
  47862. return this._bias;
  47863. },
  47864. set: function (bias) {
  47865. this._bias = bias;
  47866. },
  47867. enumerable: true,
  47868. configurable: true
  47869. });
  47870. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  47871. get: function () {
  47872. return this._blurBoxOffset;
  47873. },
  47874. set: function (value) {
  47875. if (this._blurBoxOffset === value) {
  47876. return;
  47877. }
  47878. this._blurBoxOffset = value;
  47879. this._disposeBlurPostProcesses();
  47880. },
  47881. enumerable: true,
  47882. configurable: true
  47883. });
  47884. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  47885. get: function () {
  47886. return this._blurScale;
  47887. },
  47888. set: function (value) {
  47889. if (this._blurScale === value) {
  47890. return;
  47891. }
  47892. this._blurScale = value;
  47893. this._disposeBlurPostProcesses();
  47894. },
  47895. enumerable: true,
  47896. configurable: true
  47897. });
  47898. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  47899. get: function () {
  47900. return this._blurKernel;
  47901. },
  47902. set: function (value) {
  47903. if (this._blurKernel === value) {
  47904. return;
  47905. }
  47906. this._blurKernel = value;
  47907. this._disposeBlurPostProcesses();
  47908. },
  47909. enumerable: true,
  47910. configurable: true
  47911. });
  47912. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  47913. get: function () {
  47914. return this._useKernelBlur;
  47915. },
  47916. set: function (value) {
  47917. if (this._useKernelBlur === value) {
  47918. return;
  47919. }
  47920. this._useKernelBlur = value;
  47921. this._disposeBlurPostProcesses();
  47922. },
  47923. enumerable: true,
  47924. configurable: true
  47925. });
  47926. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  47927. get: function () {
  47928. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  47929. },
  47930. set: function (value) {
  47931. this._depthScale = value;
  47932. },
  47933. enumerable: true,
  47934. configurable: true
  47935. });
  47936. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  47937. get: function () {
  47938. return this._filter;
  47939. },
  47940. set: function (value) {
  47941. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  47942. if (this._light.needCube()) {
  47943. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47944. this.useExponentialShadowMap = true;
  47945. return;
  47946. }
  47947. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47948. this.useCloseExponentialShadowMap = true;
  47949. return;
  47950. }
  47951. }
  47952. if (this._filter === value) {
  47953. return;
  47954. }
  47955. this._filter = value;
  47956. this._disposeBlurPostProcesses();
  47957. this._applyFilterValues();
  47958. this._light._markMeshesAsLightDirty();
  47959. },
  47960. enumerable: true,
  47961. configurable: true
  47962. });
  47963. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  47964. get: function () {
  47965. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  47966. },
  47967. set: function (value) {
  47968. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  47969. return;
  47970. }
  47971. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  47972. },
  47973. enumerable: true,
  47974. configurable: true
  47975. });
  47976. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  47977. get: function () {
  47978. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47979. return this.useExponentialShadowMap;
  47980. },
  47981. set: function (value) {
  47982. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47983. this.useExponentialShadowMap = value;
  47984. },
  47985. enumerable: true,
  47986. configurable: true
  47987. });
  47988. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  47989. get: function () {
  47990. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47991. return this.useBlurExponentialShadowMap;
  47992. },
  47993. set: function (value) {
  47994. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47995. this.useBlurExponentialShadowMap = value;
  47996. },
  47997. enumerable: true,
  47998. configurable: true
  47999. });
  48000. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  48001. get: function () {
  48002. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  48003. },
  48004. set: function (value) {
  48005. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  48006. return;
  48007. }
  48008. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  48009. },
  48010. enumerable: true,
  48011. configurable: true
  48012. });
  48013. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  48014. get: function () {
  48015. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  48016. },
  48017. set: function (value) {
  48018. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  48019. return;
  48020. }
  48021. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  48022. },
  48023. enumerable: true,
  48024. configurable: true
  48025. });
  48026. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  48027. get: function () {
  48028. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  48029. },
  48030. set: function (value) {
  48031. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  48032. return;
  48033. }
  48034. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  48035. },
  48036. enumerable: true,
  48037. configurable: true
  48038. });
  48039. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  48040. get: function () {
  48041. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  48042. },
  48043. set: function (value) {
  48044. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  48045. return;
  48046. }
  48047. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  48048. },
  48049. enumerable: true,
  48050. configurable: true
  48051. });
  48052. /**
  48053. * Returns the darkness value (float).
  48054. */
  48055. ShadowGenerator.prototype.getDarkness = function () {
  48056. return this._darkness;
  48057. };
  48058. /**
  48059. * Sets the ShadowGenerator darkness value (float <= 1.0).
  48060. * Returns the ShadowGenerator.
  48061. */
  48062. ShadowGenerator.prototype.setDarkness = function (darkness) {
  48063. if (darkness >= 1.0)
  48064. this._darkness = 1.0;
  48065. else if (darkness <= 0.0)
  48066. this._darkness = 0.0;
  48067. else
  48068. this._darkness = darkness;
  48069. return this;
  48070. };
  48071. /**
  48072. * Sets the ability to have transparent shadow (boolean).
  48073. * Returns the ShadowGenerator.
  48074. */
  48075. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  48076. this._transparencyShadow = hasShadow;
  48077. return this;
  48078. };
  48079. /**
  48080. * Returns a RenderTargetTexture object : the shadow map texture.
  48081. */
  48082. ShadowGenerator.prototype.getShadowMap = function () {
  48083. return this._shadowMap;
  48084. };
  48085. /**
  48086. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  48087. */
  48088. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  48089. if (this._shadowMap2) {
  48090. return this._shadowMap2;
  48091. }
  48092. return this._shadowMap;
  48093. };
  48094. /**
  48095. * Returns the associated light object.
  48096. */
  48097. ShadowGenerator.prototype.getLight = function () {
  48098. return this._light;
  48099. };
  48100. ShadowGenerator.prototype._initializeGenerator = function () {
  48101. this._light._markMeshesAsLightDirty();
  48102. this._initializeShadowMap();
  48103. };
  48104. ShadowGenerator.prototype._initializeShadowMap = function () {
  48105. var _this = this;
  48106. // Render target
  48107. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  48108. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48109. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48110. this._shadowMap.anisotropicFilteringLevel = 1;
  48111. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48112. this._shadowMap.renderParticles = false;
  48113. this._shadowMap.ignoreCameraViewport = true;
  48114. // Record Face Index before render.
  48115. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  48116. _this._currentFaceIndex = faceIndex;
  48117. });
  48118. // Custom render function.
  48119. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  48120. // Blur if required afer render.
  48121. this._shadowMap.onAfterUnbindObservable.add(function () {
  48122. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  48123. return;
  48124. }
  48125. if (!_this._blurPostProcesses) {
  48126. _this._initializeBlurRTTAndPostProcesses();
  48127. }
  48128. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture(), true);
  48129. });
  48130. // Clear according to the chosen filter.
  48131. this._shadowMap.onClearObservable.add(function (engine) {
  48132. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  48133. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  48134. }
  48135. else {
  48136. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  48137. }
  48138. });
  48139. };
  48140. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  48141. var _this = this;
  48142. var engine = this._scene.getEngine();
  48143. var targetSize = this._mapSize / this.blurScale;
  48144. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  48145. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  48146. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48147. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48148. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48149. }
  48150. if (this.useKernelBlur) {
  48151. 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);
  48152. this._kernelBlurXPostprocess.width = targetSize;
  48153. this._kernelBlurXPostprocess.height = targetSize;
  48154. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  48155. effect.setTexture("textureSampler", _this._shadowMap);
  48156. });
  48157. 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);
  48158. this._kernelBlurXPostprocess.autoClear = false;
  48159. this._kernelBlurYPostprocess.autoClear = false;
  48160. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48161. this._kernelBlurXPostprocess.packedFloat = true;
  48162. this._kernelBlurYPostprocess.packedFloat = true;
  48163. }
  48164. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  48165. }
  48166. else {
  48167. 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);
  48168. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  48169. effect.setFloat2("screenSize", targetSize, targetSize);
  48170. effect.setTexture("textureSampler", _this._shadowMap);
  48171. });
  48172. this._boxBlurPostprocess.autoClear = false;
  48173. this._blurPostProcesses = [this._boxBlurPostprocess];
  48174. }
  48175. };
  48176. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  48177. var index;
  48178. var engine = this._scene.getEngine();
  48179. if (depthOnlySubMeshes.length) {
  48180. engine.setColorWrite(false);
  48181. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  48182. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  48183. }
  48184. engine.setColorWrite(true);
  48185. }
  48186. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48187. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  48188. }
  48189. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48190. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  48191. }
  48192. if (this._transparencyShadow) {
  48193. for (index = 0; index < transparentSubMeshes.length; index++) {
  48194. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  48195. }
  48196. }
  48197. };
  48198. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  48199. var _this = this;
  48200. var mesh = subMesh.getRenderingMesh();
  48201. var scene = this._scene;
  48202. var engine = scene.getEngine();
  48203. // Culling
  48204. engine.setState(subMesh.getMaterial().backFaceCulling);
  48205. // Managing instances
  48206. var batch = mesh._getInstancesRenderList(subMesh._id);
  48207. if (batch.mustReturn) {
  48208. return;
  48209. }
  48210. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  48211. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  48212. engine.enableEffect(this._effect);
  48213. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  48214. var material = subMesh.getMaterial();
  48215. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  48216. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  48217. this._effect.setVector3("lightPosition", this.getLight().position);
  48218. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  48219. // Alpha test
  48220. if (material && material.needAlphaTesting()) {
  48221. var alphaTexture = material.getAlphaTestTexture();
  48222. if (alphaTexture) {
  48223. this._effect.setTexture("diffuseSampler", alphaTexture);
  48224. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  48225. }
  48226. }
  48227. // Bones
  48228. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48229. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48230. }
  48231. if (this.forceBackFacesOnly) {
  48232. engine.setState(true, 0, false, true);
  48233. }
  48234. // Draw
  48235. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  48236. if (this.forceBackFacesOnly) {
  48237. engine.setState(true, 0, false, false);
  48238. }
  48239. }
  48240. else {
  48241. // Need to reset refresh rate of the shadowMap
  48242. this._shadowMap.resetRefreshCounter();
  48243. }
  48244. };
  48245. ShadowGenerator.prototype._applyFilterValues = function () {
  48246. if (this.filter === ShadowGenerator.FILTER_NONE) {
  48247. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  48248. }
  48249. else {
  48250. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48251. }
  48252. };
  48253. /**
  48254. * Force shader compilation including textures ready check
  48255. */
  48256. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  48257. var _this = this;
  48258. var scene = this._scene;
  48259. var engine = scene.getEngine();
  48260. var subMeshes = new Array();
  48261. var currentIndex = 0;
  48262. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  48263. var mesh = _a[_i];
  48264. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  48265. }
  48266. var checkReady = function () {
  48267. if (!_this._scene || !_this._scene.getEngine()) {
  48268. return;
  48269. }
  48270. var subMesh = subMeshes[currentIndex];
  48271. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  48272. currentIndex++;
  48273. if (currentIndex >= subMeshes.length) {
  48274. if (onCompiled) {
  48275. onCompiled(_this);
  48276. }
  48277. return;
  48278. }
  48279. }
  48280. setTimeout(checkReady, 16);
  48281. };
  48282. if (subMeshes.length > 0) {
  48283. checkReady();
  48284. }
  48285. };
  48286. /**
  48287. * Boolean : true when the ShadowGenerator is finally computed.
  48288. */
  48289. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  48290. var defines = [];
  48291. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  48292. defines.push("#define FLOAT");
  48293. }
  48294. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  48295. defines.push("#define ESM");
  48296. }
  48297. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48298. var mesh = subMesh.getMesh();
  48299. var material = subMesh.getMaterial();
  48300. // Alpha test
  48301. if (material && material.needAlphaTesting()) {
  48302. var alphaTexture = material.getAlphaTestTexture();
  48303. if (alphaTexture) {
  48304. defines.push("#define ALPHATEST");
  48305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48306. attribs.push(BABYLON.VertexBuffer.UVKind);
  48307. defines.push("#define UV1");
  48308. }
  48309. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48310. if (alphaTexture.coordinatesIndex === 1) {
  48311. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48312. defines.push("#define UV2");
  48313. }
  48314. }
  48315. }
  48316. }
  48317. // Bones
  48318. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48319. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48320. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48321. if (mesh.numBoneInfluencers > 4) {
  48322. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48323. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48324. }
  48325. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48326. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48327. }
  48328. else {
  48329. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48330. }
  48331. // Instances
  48332. if (useInstances) {
  48333. defines.push("#define INSTANCES");
  48334. attribs.push("world0");
  48335. attribs.push("world1");
  48336. attribs.push("world2");
  48337. attribs.push("world3");
  48338. }
  48339. // Get correct effect
  48340. var join = defines.join("\n");
  48341. if (this._cachedDefines !== join) {
  48342. this._cachedDefines = join;
  48343. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  48344. }
  48345. return this._effect.isReady();
  48346. };
  48347. /**
  48348. * This creates the defines related to the standard BJS materials.
  48349. */
  48350. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  48351. var scene = this._scene;
  48352. var light = this._light;
  48353. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  48354. return;
  48355. }
  48356. defines["SHADOW" + lightIndex] = true;
  48357. if (this.usePoissonSampling) {
  48358. defines["SHADOWPCF" + lightIndex] = true;
  48359. }
  48360. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  48361. defines["SHADOWESM" + lightIndex] = true;
  48362. }
  48363. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  48364. defines["SHADOWCLOSEESM" + lightIndex] = true;
  48365. }
  48366. if (light.needCube()) {
  48367. defines["SHADOWCUBE" + lightIndex] = true;
  48368. }
  48369. };
  48370. /**
  48371. * This binds shadow lights related to the standard BJS materials.
  48372. * It implies the unifroms available on the materials are the standard BJS ones.
  48373. */
  48374. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  48375. var light = this._light;
  48376. var scene = this._scene;
  48377. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  48378. return;
  48379. }
  48380. if (!light.needCube()) {
  48381. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  48382. }
  48383. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  48384. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  48385. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  48386. };
  48387. // Methods
  48388. /**
  48389. * Returns a Matrix object : the updated transformation matrix.
  48390. */
  48391. ShadowGenerator.prototype.getTransformMatrix = function () {
  48392. var scene = this._scene;
  48393. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  48394. return this._transformMatrix;
  48395. }
  48396. this._currentRenderID = scene.getRenderId();
  48397. this._currentFaceIndexCache = this._currentFaceIndex;
  48398. var lightPosition = this._light.position;
  48399. if (this._light.computeTransformedInformation()) {
  48400. lightPosition = this._light.transformedPosition;
  48401. }
  48402. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  48403. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  48404. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  48405. }
  48406. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  48407. this._cachedPosition = lightPosition.clone();
  48408. this._cachedDirection = this._lightDirection.clone();
  48409. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  48410. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  48411. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  48412. }
  48413. return this._transformMatrix;
  48414. };
  48415. ShadowGenerator.prototype.recreateShadowMap = function () {
  48416. // Track render list.
  48417. var renderList = this._shadowMap.renderList;
  48418. // Clean up existing data.
  48419. this._disposeRTTandPostProcesses();
  48420. // Reinitializes.
  48421. this._initializeGenerator();
  48422. // Reaffect the filter to ensure a correct fallback if necessary.
  48423. this.filter = this.filter;
  48424. // Reaffect the filter.
  48425. this._applyFilterValues();
  48426. // Reaffect Render List.
  48427. this._shadowMap.renderList = renderList;
  48428. };
  48429. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  48430. if (this._shadowMap2) {
  48431. this._shadowMap2.dispose();
  48432. this._shadowMap2 = null;
  48433. }
  48434. if (this._downSamplePostprocess) {
  48435. this._downSamplePostprocess.dispose();
  48436. this._downSamplePostprocess = null;
  48437. }
  48438. if (this._boxBlurPostprocess) {
  48439. this._boxBlurPostprocess.dispose();
  48440. this._boxBlurPostprocess = null;
  48441. }
  48442. if (this._kernelBlurXPostprocess) {
  48443. this._kernelBlurXPostprocess.dispose();
  48444. this._kernelBlurXPostprocess = null;
  48445. }
  48446. if (this._kernelBlurYPostprocess) {
  48447. this._kernelBlurYPostprocess.dispose();
  48448. this._kernelBlurYPostprocess = null;
  48449. }
  48450. this._blurPostProcesses = null;
  48451. };
  48452. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  48453. if (this._shadowMap) {
  48454. this._shadowMap.dispose();
  48455. this._shadowMap = null;
  48456. }
  48457. this._disposeBlurPostProcesses();
  48458. };
  48459. /**
  48460. * Disposes the ShadowGenerator.
  48461. * Returns nothing.
  48462. */
  48463. ShadowGenerator.prototype.dispose = function () {
  48464. this._disposeRTTandPostProcesses();
  48465. this._light._shadowGenerator = null;
  48466. this._light._markMeshesAsLightDirty();
  48467. };
  48468. /**
  48469. * Serializes the ShadowGenerator and returns a serializationObject.
  48470. */
  48471. ShadowGenerator.prototype.serialize = function () {
  48472. var serializationObject = {};
  48473. var shadowMap = this.getShadowMap();
  48474. serializationObject.lightId = this._light.id;
  48475. serializationObject.mapSize = shadowMap.getRenderSize();
  48476. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  48477. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  48478. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48479. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48480. serializationObject.usePoissonSampling = this.usePoissonSampling;
  48481. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  48482. serializationObject.depthScale = this.depthScale;
  48483. serializationObject.darkness = this.getDarkness();
  48484. serializationObject.blurBoxOffset = this.blurBoxOffset;
  48485. serializationObject.blurKernel = this.blurKernel;
  48486. serializationObject.blurScale = this.blurScale;
  48487. serializationObject.useKernelBlur = this.useKernelBlur;
  48488. serializationObject.transparencyShadow = this._transparencyShadow;
  48489. serializationObject.renderList = [];
  48490. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  48491. var mesh = shadowMap.renderList[meshIndex];
  48492. serializationObject.renderList.push(mesh.id);
  48493. }
  48494. return serializationObject;
  48495. };
  48496. /**
  48497. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  48498. */
  48499. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  48500. //casting to point light, as light is missing the position attr and typescript complains.
  48501. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  48502. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  48503. var shadowMap = shadowGenerator.getShadowMap();
  48504. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  48505. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  48506. meshes.forEach(function (mesh) {
  48507. shadowMap.renderList.push(mesh);
  48508. });
  48509. }
  48510. if (parsedShadowGenerator.usePoissonSampling) {
  48511. shadowGenerator.usePoissonSampling = true;
  48512. }
  48513. else if (parsedShadowGenerator.useExponentialShadowMap) {
  48514. shadowGenerator.useExponentialShadowMap = true;
  48515. }
  48516. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48517. shadowGenerator.useBlurExponentialShadowMap = true;
  48518. }
  48519. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  48520. shadowGenerator.useCloseExponentialShadowMap = true;
  48521. }
  48522. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48523. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  48524. }
  48525. else if (parsedShadowGenerator.useVarianceShadowMap) {
  48526. shadowGenerator.useExponentialShadowMap = true;
  48527. }
  48528. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  48529. shadowGenerator.useBlurExponentialShadowMap = true;
  48530. }
  48531. if (parsedShadowGenerator.depthScale) {
  48532. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  48533. }
  48534. if (parsedShadowGenerator.blurScale) {
  48535. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  48536. }
  48537. if (parsedShadowGenerator.blurBoxOffset) {
  48538. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  48539. }
  48540. if (parsedShadowGenerator.useKernelBlur) {
  48541. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  48542. }
  48543. if (parsedShadowGenerator.blurKernel) {
  48544. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  48545. }
  48546. if (parsedShadowGenerator.bias !== undefined) {
  48547. shadowGenerator.bias = parsedShadowGenerator.bias;
  48548. }
  48549. if (parsedShadowGenerator.darkness) {
  48550. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  48551. }
  48552. if (parsedShadowGenerator.transparencyShadow) {
  48553. shadowGenerator.setTransparencyShadow(true);
  48554. }
  48555. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  48556. return shadowGenerator;
  48557. };
  48558. ShadowGenerator._FILTER_NONE = 0;
  48559. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  48560. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  48561. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  48562. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  48563. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  48564. return ShadowGenerator;
  48565. }());
  48566. BABYLON.ShadowGenerator = ShadowGenerator;
  48567. })(BABYLON || (BABYLON = {}));
  48568. //# sourceMappingURL=babylon.shadowGenerator.js.map
  48569. var BABYLON;
  48570. (function (BABYLON) {
  48571. var DefaultLoadingScreen = (function () {
  48572. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48573. if (_loadingText === void 0) { _loadingText = ""; }
  48574. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48575. var _this = this;
  48576. this._renderingCanvas = _renderingCanvas;
  48577. this._loadingText = _loadingText;
  48578. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48579. // Resize
  48580. this._resizeLoadingUI = function () {
  48581. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  48582. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  48583. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  48584. _this._loadingDiv.style.left = canvasRect.left + "px";
  48585. _this._loadingDiv.style.top = canvasRect.top + "px";
  48586. _this._loadingDiv.style.width = canvasRect.width + "px";
  48587. _this._loadingDiv.style.height = canvasRect.height + "px";
  48588. };
  48589. }
  48590. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  48591. if (this._loadingDiv) {
  48592. // Do not add a loading screen if there is already one
  48593. return;
  48594. }
  48595. this._loadingDiv = document.createElement("div");
  48596. this._loadingDiv.id = "babylonjsLoadingDiv";
  48597. this._loadingDiv.style.opacity = "0";
  48598. this._loadingDiv.style.transition = "opacity 1.5s ease";
  48599. this._loadingDiv.style.pointerEvents = "none";
  48600. // Loading text
  48601. this._loadingTextDiv = document.createElement("div");
  48602. this._loadingTextDiv.style.position = "absolute";
  48603. this._loadingTextDiv.style.left = "0";
  48604. this._loadingTextDiv.style.top = "50%";
  48605. this._loadingTextDiv.style.marginTop = "80px";
  48606. this._loadingTextDiv.style.width = "100%";
  48607. this._loadingTextDiv.style.height = "20px";
  48608. this._loadingTextDiv.style.fontFamily = "Arial";
  48609. this._loadingTextDiv.style.fontSize = "14px";
  48610. this._loadingTextDiv.style.color = "white";
  48611. this._loadingTextDiv.style.textAlign = "center";
  48612. this._loadingTextDiv.innerHTML = "Loading";
  48613. this._loadingDiv.appendChild(this._loadingTextDiv);
  48614. //set the predefined text
  48615. this._loadingTextDiv.innerHTML = this._loadingText;
  48616. // Generating keyframes
  48617. var style = document.createElement('style');
  48618. style.type = 'text/css';
  48619. 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 }";
  48620. style.innerHTML = keyFrames;
  48621. document.getElementsByTagName('head')[0].appendChild(style);
  48622. // Loading img
  48623. var imgBack = new Image();
  48624. 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";
  48625. imgBack.style.position = "absolute";
  48626. imgBack.style.left = "50%";
  48627. imgBack.style.top = "50%";
  48628. imgBack.style.marginLeft = "-60px";
  48629. imgBack.style.marginTop = "-60px";
  48630. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  48631. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  48632. imgBack.style.transformOrigin = "50% 50%";
  48633. imgBack.style.webkitTransformOrigin = "50% 50%";
  48634. this._loadingDiv.appendChild(imgBack);
  48635. this._resizeLoadingUI();
  48636. window.addEventListener("resize", this._resizeLoadingUI);
  48637. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48638. document.body.appendChild(this._loadingDiv);
  48639. this._loadingDiv.style.opacity = "1";
  48640. };
  48641. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  48642. var _this = this;
  48643. if (!this._loadingDiv) {
  48644. return;
  48645. }
  48646. var onTransitionEnd = function () {
  48647. if (!_this._loadingDiv) {
  48648. return;
  48649. }
  48650. document.body.removeChild(_this._loadingDiv);
  48651. window.removeEventListener("resize", _this._resizeLoadingUI);
  48652. _this._loadingDiv = null;
  48653. };
  48654. this._loadingDiv.style.opacity = "0";
  48655. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  48656. };
  48657. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  48658. set: function (text) {
  48659. this._loadingText = text;
  48660. if (this._loadingTextDiv) {
  48661. this._loadingTextDiv.innerHTML = this._loadingText;
  48662. }
  48663. },
  48664. enumerable: true,
  48665. configurable: true
  48666. });
  48667. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48668. get: function () {
  48669. return this._loadingDivBackgroundColor;
  48670. },
  48671. set: function (color) {
  48672. this._loadingDivBackgroundColor = color;
  48673. if (!this._loadingDiv) {
  48674. return;
  48675. }
  48676. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48677. },
  48678. enumerable: true,
  48679. configurable: true
  48680. });
  48681. return DefaultLoadingScreen;
  48682. }());
  48683. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48684. })(BABYLON || (BABYLON = {}));
  48685. //# sourceMappingURL=babylon.loadingScreen.js.map
  48686. var BABYLON;
  48687. (function (BABYLON) {
  48688. var SceneLoader = (function () {
  48689. function SceneLoader() {
  48690. }
  48691. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48692. get: function () {
  48693. return 0;
  48694. },
  48695. enumerable: true,
  48696. configurable: true
  48697. });
  48698. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48699. get: function () {
  48700. return 1;
  48701. },
  48702. enumerable: true,
  48703. configurable: true
  48704. });
  48705. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48706. get: function () {
  48707. return 2;
  48708. },
  48709. enumerable: true,
  48710. configurable: true
  48711. });
  48712. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48713. get: function () {
  48714. return 3;
  48715. },
  48716. enumerable: true,
  48717. configurable: true
  48718. });
  48719. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48720. get: function () {
  48721. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48722. },
  48723. set: function (value) {
  48724. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48725. },
  48726. enumerable: true,
  48727. configurable: true
  48728. });
  48729. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48730. get: function () {
  48731. return SceneLoader._ShowLoadingScreen;
  48732. },
  48733. set: function (value) {
  48734. SceneLoader._ShowLoadingScreen = value;
  48735. },
  48736. enumerable: true,
  48737. configurable: true
  48738. });
  48739. Object.defineProperty(SceneLoader, "loggingLevel", {
  48740. get: function () {
  48741. return SceneLoader._loggingLevel;
  48742. },
  48743. set: function (value) {
  48744. SceneLoader._loggingLevel = value;
  48745. },
  48746. enumerable: true,
  48747. configurable: true
  48748. });
  48749. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48750. get: function () {
  48751. return SceneLoader._CleanBoneMatrixWeights;
  48752. },
  48753. set: function (value) {
  48754. SceneLoader._CleanBoneMatrixWeights = value;
  48755. },
  48756. enumerable: true,
  48757. configurable: true
  48758. });
  48759. SceneLoader._getDefaultPlugin = function () {
  48760. return SceneLoader._registeredPlugins[".babylon"];
  48761. };
  48762. SceneLoader._getPluginForExtension = function (extension) {
  48763. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  48764. if (registeredPlugin) {
  48765. return registeredPlugin;
  48766. }
  48767. return SceneLoader._getDefaultPlugin();
  48768. };
  48769. SceneLoader._getPluginForDirectLoad = function (data) {
  48770. for (var extension in SceneLoader._registeredPlugins) {
  48771. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  48772. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  48773. return SceneLoader._registeredPlugins[extension];
  48774. }
  48775. }
  48776. return SceneLoader._getDefaultPlugin();
  48777. };
  48778. SceneLoader._getPluginForFilename = function (sceneFilename) {
  48779. if (sceneFilename.name) {
  48780. sceneFilename = sceneFilename.name;
  48781. }
  48782. var dotPosition = sceneFilename.lastIndexOf(".");
  48783. var queryStringPosition = sceneFilename.indexOf("?");
  48784. if (queryStringPosition === -1) {
  48785. queryStringPosition = sceneFilename.length;
  48786. }
  48787. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  48788. return SceneLoader._getPluginForExtension(extension);
  48789. };
  48790. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  48791. SceneLoader._getDirectLoad = function (sceneFilename) {
  48792. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  48793. return sceneFilename.substr(5);
  48794. }
  48795. return null;
  48796. };
  48797. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48798. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  48799. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  48800. var plugin = registeredPlugin.plugin;
  48801. var useArrayBuffer = registeredPlugin.isBinary;
  48802. var database;
  48803. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  48804. var dataCallback = function (data) {
  48805. if (scene.isDisposed) {
  48806. onError("Scene has been disposed");
  48807. return;
  48808. }
  48809. scene.database = database;
  48810. try {
  48811. onSuccess(plugin, data);
  48812. }
  48813. catch (e) {
  48814. onError(null, e);
  48815. }
  48816. };
  48817. var manifestChecked = function (success) {
  48818. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  48819. onError(request.status + " " + request.statusText);
  48820. });
  48821. };
  48822. if (directLoad) {
  48823. dataCallback(directLoad);
  48824. return;
  48825. }
  48826. if (rootUrl.indexOf("file:") === -1) {
  48827. if (scene.getEngine().enableOfflineSupport) {
  48828. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  48829. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  48830. }
  48831. else {
  48832. manifestChecked(true);
  48833. }
  48834. }
  48835. else {
  48836. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  48837. }
  48838. };
  48839. // Public functions
  48840. SceneLoader.GetPluginForExtension = function (extension) {
  48841. return SceneLoader._getPluginForExtension(extension).plugin;
  48842. };
  48843. SceneLoader.RegisterPlugin = function (plugin) {
  48844. if (typeof plugin.extensions === "string") {
  48845. var extension = plugin.extensions;
  48846. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48847. plugin: plugin,
  48848. isBinary: false
  48849. };
  48850. }
  48851. else {
  48852. var extensions = plugin.extensions;
  48853. Object.keys(extensions).forEach(function (extension) {
  48854. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48855. plugin: plugin,
  48856. isBinary: extensions[extension].isBinary
  48857. };
  48858. });
  48859. }
  48860. };
  48861. /**
  48862. * Import meshes into a scene
  48863. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  48864. * @param rootUrl a string that defines the root url for scene and resources
  48865. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48866. * @param scene the instance of BABYLON.Scene to append to
  48867. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  48868. * @param onProgress a callback with a progress event for each file being loaded
  48869. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48870. */
  48871. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48872. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48873. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48874. return;
  48875. }
  48876. var loadingToken = {};
  48877. scene._addPendingData(loadingToken);
  48878. var errorHandler = function (message, exception) {
  48879. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  48880. if (onError) {
  48881. onError(scene, errorMessage, exception);
  48882. }
  48883. else {
  48884. BABYLON.Tools.Error(errorMessage);
  48885. // should the exception be thrown?
  48886. }
  48887. scene._removePendingData(loadingToken);
  48888. };
  48889. var progressHandler = function (event) {
  48890. if (onProgress) {
  48891. onProgress(event);
  48892. }
  48893. };
  48894. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48895. if (plugin.importMesh) {
  48896. var syncedPlugin = plugin;
  48897. var meshes = [];
  48898. var particleSystems = [];
  48899. var skeletons = [];
  48900. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  48901. return;
  48902. }
  48903. if (onSuccess) {
  48904. // wrap onSuccess with try-catch to know if something went wrong.
  48905. try {
  48906. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48907. onSuccess(meshes, particleSystems, skeletons);
  48908. scene._removePendingData(loadingToken);
  48909. }
  48910. catch (e) {
  48911. var message = 'Error in onSuccess callback.';
  48912. errorHandler(message, e);
  48913. }
  48914. }
  48915. }
  48916. else {
  48917. var asyncedPlugin = plugin;
  48918. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  48919. if (onSuccess) {
  48920. try {
  48921. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48922. onSuccess(meshes, particleSystems, skeletons);
  48923. scene._removePendingData(loadingToken);
  48924. }
  48925. catch (e) {
  48926. var message = 'Error in onSuccess callback.';
  48927. errorHandler(message, e);
  48928. }
  48929. }
  48930. }, progressHandler, errorHandler);
  48931. }
  48932. }, progressHandler, errorHandler);
  48933. };
  48934. /**
  48935. * Load a scene
  48936. * @param rootUrl a string that defines the root url for scene and resources
  48937. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48938. * @param engine is the instance of BABYLON.Engine to use to create the scene
  48939. * @param onSuccess a callback with the scene when import succeeds
  48940. * @param onProgress a callback with a progress event for each file being loaded
  48941. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48942. */
  48943. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  48944. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  48945. };
  48946. /**
  48947. * Append a scene
  48948. * @param rootUrl a string that defines the root url for scene and resources
  48949. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48950. * @param scene is the instance of BABYLON.Scene to append to
  48951. * @param onSuccess a callback with the scene when import succeeds
  48952. * @param onProgress a callback with a progress event for each file being loaded
  48953. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48954. */
  48955. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48956. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48957. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48958. return;
  48959. }
  48960. if (SceneLoader.ShowLoadingScreen) {
  48961. scene.getEngine().displayLoadingUI();
  48962. }
  48963. var loadingToken = {};
  48964. scene._addPendingData(loadingToken);
  48965. var errorHandler = function (message, exception) {
  48966. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  48967. if (onError) {
  48968. onError(scene, errorMessage, exception);
  48969. }
  48970. else {
  48971. BABYLON.Tools.Error(errorMessage);
  48972. // should the exception be thrown?
  48973. }
  48974. scene._removePendingData(loadingToken);
  48975. scene.getEngine().hideLoadingUI();
  48976. };
  48977. var progressHandler = function (event) {
  48978. if (onProgress) {
  48979. onProgress(event);
  48980. }
  48981. };
  48982. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48983. if (plugin.load) {
  48984. var syncedPlugin = plugin;
  48985. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  48986. return;
  48987. }
  48988. if (onSuccess) {
  48989. try {
  48990. onSuccess(scene);
  48991. }
  48992. catch (e) {
  48993. errorHandler("Error in onSuccess callback", e);
  48994. }
  48995. }
  48996. scene.loadingPluginName = plugin.name;
  48997. scene._removePendingData(loadingToken);
  48998. }
  48999. else {
  49000. var asyncedPlugin = plugin;
  49001. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  49002. if (onSuccess) {
  49003. onSuccess(scene);
  49004. }
  49005. scene.loadingPluginName = plugin.name;
  49006. scene._removePendingData(loadingToken);
  49007. }, progressHandler, errorHandler);
  49008. }
  49009. if (SceneLoader.ShowLoadingScreen) {
  49010. scene.executeWhenReady(function () {
  49011. scene.getEngine().hideLoadingUI();
  49012. });
  49013. }
  49014. }, progressHandler, errorHandler);
  49015. };
  49016. // Flags
  49017. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  49018. SceneLoader._ShowLoadingScreen = true;
  49019. SceneLoader._CleanBoneMatrixWeights = false;
  49020. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  49021. // Members
  49022. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  49023. SceneLoader._registeredPlugins = {};
  49024. return SceneLoader;
  49025. }());
  49026. BABYLON.SceneLoader = SceneLoader;
  49027. ;
  49028. })(BABYLON || (BABYLON = {}));
  49029. //# sourceMappingURL=babylon.sceneLoader.js.map
  49030. var BABYLON;
  49031. (function (BABYLON) {
  49032. var Internals;
  49033. (function (Internals) {
  49034. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  49035. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49036. var parsedMaterial = parsedData.materials[index];
  49037. if (parsedMaterial.id === id) {
  49038. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49039. }
  49040. }
  49041. return null;
  49042. };
  49043. var isDescendantOf = function (mesh, names, hierarchyIds) {
  49044. for (var i in names) {
  49045. if (mesh.name === names[i]) {
  49046. hierarchyIds.push(mesh.id);
  49047. return true;
  49048. }
  49049. }
  49050. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  49051. hierarchyIds.push(mesh.id);
  49052. return true;
  49053. }
  49054. return false;
  49055. };
  49056. var logOperation = function (operation, producer) {
  49057. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  49058. };
  49059. BABYLON.SceneLoader.RegisterPlugin({
  49060. name: "babylon.js",
  49061. extensions: ".babylon",
  49062. canDirectLoad: function (data) {
  49063. if (data.indexOf("babylon") !== -1) {
  49064. return true;
  49065. }
  49066. return false;
  49067. },
  49068. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  49069. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49070. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49071. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49072. // and avoid problems with multiple concurrent .babylon loads.
  49073. var log = "importMesh has failed JSON parse";
  49074. try {
  49075. var parsedData = JSON.parse(data);
  49076. log = "";
  49077. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49078. if (!meshesNames) {
  49079. meshesNames = null;
  49080. }
  49081. else if (!Array.isArray(meshesNames)) {
  49082. meshesNames = [meshesNames];
  49083. }
  49084. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49085. var loadedSkeletonsIds = [];
  49086. var loadedMaterialsIds = [];
  49087. var hierarchyIds = [];
  49088. var index;
  49089. var cache;
  49090. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49091. var parsedMesh = parsedData.meshes[index];
  49092. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  49093. if (meshesNames !== null) {
  49094. // Remove found mesh name from list.
  49095. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  49096. }
  49097. //Geometry?
  49098. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  49099. //does the file contain geometries?
  49100. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  49101. //find the correct geometry and add it to the scene
  49102. var found = false;
  49103. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  49104. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  49105. return;
  49106. }
  49107. else {
  49108. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  49109. if (parsedGeometryData.id === parsedMesh.geometryId) {
  49110. switch (geometryType) {
  49111. case "boxes":
  49112. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  49113. break;
  49114. case "spheres":
  49115. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  49116. break;
  49117. case "cylinders":
  49118. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  49119. break;
  49120. case "toruses":
  49121. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  49122. break;
  49123. case "grounds":
  49124. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  49125. break;
  49126. case "planes":
  49127. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  49128. break;
  49129. case "torusKnots":
  49130. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  49131. break;
  49132. case "vertexData":
  49133. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  49134. break;
  49135. }
  49136. found = true;
  49137. }
  49138. });
  49139. }
  49140. });
  49141. if (found === false) {
  49142. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  49143. }
  49144. }
  49145. }
  49146. // Material ?
  49147. if (parsedMesh.materialId) {
  49148. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  49149. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49150. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  49151. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  49152. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  49153. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  49154. var subMatId = parsedMultiMaterial.materials[matIndex];
  49155. loadedMaterialsIds.push(subMatId);
  49156. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  49157. log += "\n\tMaterial " + mat.toString(fullDetails);
  49158. }
  49159. loadedMaterialsIds.push(parsedMultiMaterial.id);
  49160. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49161. materialFound = true;
  49162. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  49163. break;
  49164. }
  49165. }
  49166. }
  49167. if (materialFound === false) {
  49168. loadedMaterialsIds.push(parsedMesh.materialId);
  49169. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  49170. if (!mat) {
  49171. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  49172. }
  49173. else {
  49174. log += "\n\tMaterial " + mat.toString(fullDetails);
  49175. }
  49176. }
  49177. }
  49178. // Skeleton ?
  49179. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49180. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  49181. if (skeletonAlreadyLoaded === false) {
  49182. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  49183. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  49184. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  49185. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49186. skeletons.push(skeleton);
  49187. loadedSkeletonsIds.push(parsedSkeleton.id);
  49188. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  49189. }
  49190. }
  49191. }
  49192. }
  49193. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49194. meshes.push(mesh);
  49195. log += "\n\tMesh " + mesh.toString(fullDetails);
  49196. }
  49197. }
  49198. // Connecting parents
  49199. var currentMesh;
  49200. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49201. currentMesh = scene.meshes[index];
  49202. if (currentMesh._waitingParentId) {
  49203. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  49204. currentMesh._waitingParentId = undefined;
  49205. }
  49206. }
  49207. // freeze and compute world matrix application
  49208. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49209. currentMesh = scene.meshes[index];
  49210. if (currentMesh._waitingFreezeWorldMatrix) {
  49211. currentMesh.freezeWorldMatrix();
  49212. currentMesh._waitingFreezeWorldMatrix = undefined;
  49213. }
  49214. else {
  49215. currentMesh.computeWorldMatrix(true);
  49216. }
  49217. }
  49218. }
  49219. // Particles
  49220. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49221. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49222. var parsedParticleSystem = parsedData.particleSystems[index];
  49223. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  49224. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  49225. }
  49226. }
  49227. }
  49228. return true;
  49229. }
  49230. catch (err) {
  49231. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  49232. if (onError) {
  49233. onError(msg, err);
  49234. }
  49235. else {
  49236. BABYLON.Tools.Log(msg);
  49237. log = null;
  49238. throw err;
  49239. }
  49240. }
  49241. finally {
  49242. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49243. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49244. }
  49245. }
  49246. },
  49247. load: function (scene, data, rootUrl, onError) {
  49248. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  49249. // when SceneLoader.debugLogging = true (default), or exception encountered.
  49250. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  49251. // and avoid problems with multiple concurrent .babylon loads.
  49252. var log = "importScene has failed JSON parse";
  49253. try {
  49254. var parsedData = JSON.parse(data);
  49255. log = "";
  49256. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  49257. // Scene
  49258. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  49259. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  49260. }
  49261. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  49262. scene.autoClear = parsedData.autoClear;
  49263. }
  49264. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  49265. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  49266. }
  49267. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  49268. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  49269. }
  49270. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  49271. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  49272. }
  49273. // Fog
  49274. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  49275. scene.fogMode = parsedData.fogMode;
  49276. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  49277. scene.fogStart = parsedData.fogStart;
  49278. scene.fogEnd = parsedData.fogEnd;
  49279. scene.fogDensity = parsedData.fogDensity;
  49280. log += "\tFog mode for scene: ";
  49281. switch (scene.fogMode) {
  49282. // getters not compiling, so using hardcoded
  49283. case 1:
  49284. log += "exp\n";
  49285. break;
  49286. case 2:
  49287. log += "exp2\n";
  49288. break;
  49289. case 3:
  49290. log += "linear\n";
  49291. break;
  49292. }
  49293. }
  49294. //Physics
  49295. if (parsedData.physicsEnabled) {
  49296. var physicsPlugin;
  49297. if (parsedData.physicsEngine === "cannon") {
  49298. physicsPlugin = new BABYLON.CannonJSPlugin();
  49299. }
  49300. else if (parsedData.physicsEngine === "oimo") {
  49301. physicsPlugin = new BABYLON.OimoJSPlugin();
  49302. }
  49303. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  49304. //else - default engine, which is currently oimo
  49305. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  49306. scene.enablePhysics(physicsGravity, physicsPlugin);
  49307. }
  49308. // Metadata
  49309. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  49310. scene.metadata = parsedData.metadata;
  49311. }
  49312. //collisions, if defined. otherwise, default is true
  49313. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  49314. scene.collisionsEnabled = parsedData.collisionsEnabled;
  49315. }
  49316. scene.workerCollisions = !!parsedData.workerCollisions;
  49317. var index;
  49318. var cache;
  49319. // Lights
  49320. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  49321. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  49322. var parsedLight = parsedData.lights[index];
  49323. var light = BABYLON.Light.Parse(parsedLight, scene);
  49324. log += (index === 0 ? "\n\tLights:" : "");
  49325. log += "\n\t\t" + light.toString(fullDetails);
  49326. }
  49327. }
  49328. // Animations
  49329. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  49330. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  49331. var parsedAnimation = parsedData.animations[index];
  49332. var animation = BABYLON.Animation.Parse(parsedAnimation);
  49333. scene.animations.push(animation);
  49334. log += (index === 0 ? "\n\tAnimations:" : "");
  49335. log += "\n\t\t" + animation.toString(fullDetails);
  49336. }
  49337. }
  49338. if (parsedData.autoAnimate) {
  49339. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  49340. }
  49341. // Materials
  49342. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  49343. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  49344. var parsedMaterial = parsedData.materials[index];
  49345. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  49346. log += (index === 0 ? "\n\tMaterials:" : "");
  49347. log += "\n\t\t" + mat.toString(fullDetails);
  49348. }
  49349. }
  49350. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  49351. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  49352. var parsedMultiMaterial = parsedData.multiMaterials[index];
  49353. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  49354. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  49355. log += "\n\t\t" + mmat.toString(fullDetails);
  49356. }
  49357. }
  49358. // Morph targets
  49359. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  49360. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  49361. var managerData = _a[_i];
  49362. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  49363. }
  49364. }
  49365. // Skeletons
  49366. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  49367. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  49368. var parsedSkeleton = parsedData.skeletons[index];
  49369. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  49370. log += (index === 0 ? "\n\tSkeletons:" : "");
  49371. log += "\n\t\t" + skeleton.toString(fullDetails);
  49372. }
  49373. }
  49374. // Geometries
  49375. var geometries = parsedData.geometries;
  49376. if (geometries !== undefined && geometries !== null) {
  49377. // Boxes
  49378. var boxes = geometries.boxes;
  49379. if (boxes !== undefined && boxes !== null) {
  49380. for (index = 0, cache = boxes.length; index < cache; index++) {
  49381. var parsedBox = boxes[index];
  49382. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  49383. }
  49384. }
  49385. // Spheres
  49386. var spheres = geometries.spheres;
  49387. if (spheres !== undefined && spheres !== null) {
  49388. for (index = 0, cache = spheres.length; index < cache; index++) {
  49389. var parsedSphere = spheres[index];
  49390. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  49391. }
  49392. }
  49393. // Cylinders
  49394. var cylinders = geometries.cylinders;
  49395. if (cylinders !== undefined && cylinders !== null) {
  49396. for (index = 0, cache = cylinders.length; index < cache; index++) {
  49397. var parsedCylinder = cylinders[index];
  49398. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  49399. }
  49400. }
  49401. // Toruses
  49402. var toruses = geometries.toruses;
  49403. if (toruses !== undefined && toruses !== null) {
  49404. for (index = 0, cache = toruses.length; index < cache; index++) {
  49405. var parsedTorus = toruses[index];
  49406. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  49407. }
  49408. }
  49409. // Grounds
  49410. var grounds = geometries.grounds;
  49411. if (grounds !== undefined && grounds !== null) {
  49412. for (index = 0, cache = grounds.length; index < cache; index++) {
  49413. var parsedGround = grounds[index];
  49414. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  49415. }
  49416. }
  49417. // Planes
  49418. var planes = geometries.planes;
  49419. if (planes !== undefined && planes !== null) {
  49420. for (index = 0, cache = planes.length; index < cache; index++) {
  49421. var parsedPlane = planes[index];
  49422. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  49423. }
  49424. }
  49425. // TorusKnots
  49426. var torusKnots = geometries.torusKnots;
  49427. if (torusKnots !== undefined && torusKnots !== null) {
  49428. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  49429. var parsedTorusKnot = torusKnots[index];
  49430. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  49431. }
  49432. }
  49433. // VertexData
  49434. var vertexData = geometries.vertexData;
  49435. if (vertexData !== undefined && vertexData !== null) {
  49436. for (index = 0, cache = vertexData.length; index < cache; index++) {
  49437. var parsedVertexData = vertexData[index];
  49438. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  49439. }
  49440. }
  49441. }
  49442. // Meshes
  49443. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  49444. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  49445. var parsedMesh = parsedData.meshes[index];
  49446. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  49447. log += (index === 0 ? "\n\tMeshes:" : "");
  49448. log += "\n\t\t" + mesh.toString(fullDetails);
  49449. }
  49450. }
  49451. // Cameras
  49452. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  49453. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  49454. var parsedCamera = parsedData.cameras[index];
  49455. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  49456. log += (index === 0 ? "\n\tCameras:" : "");
  49457. log += "\n\t\t" + camera.toString(fullDetails);
  49458. }
  49459. }
  49460. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  49461. scene.setActiveCameraByID(parsedData.activeCameraID);
  49462. }
  49463. // Browsing all the graph to connect the dots
  49464. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  49465. var camera = scene.cameras[index];
  49466. if (camera._waitingParentId) {
  49467. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  49468. camera._waitingParentId = undefined;
  49469. }
  49470. }
  49471. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49472. var light = scene.lights[index];
  49473. if (light._waitingParentId) {
  49474. light.parent = scene.getLastEntryByID(light._waitingParentId);
  49475. light._waitingParentId = undefined;
  49476. }
  49477. }
  49478. // Sounds
  49479. var loadedSounds = [];
  49480. var loadedSound;
  49481. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  49482. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  49483. var parsedSound = parsedData.sounds[index];
  49484. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49485. if (!parsedSound.url)
  49486. parsedSound.url = parsedSound.name;
  49487. if (!loadedSounds[parsedSound.url]) {
  49488. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  49489. loadedSounds[parsedSound.url] = loadedSound;
  49490. }
  49491. else {
  49492. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  49493. }
  49494. }
  49495. else {
  49496. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  49497. }
  49498. }
  49499. }
  49500. loadedSounds = [];
  49501. // Connect parents & children and parse actions
  49502. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49503. var mesh = scene.meshes[index];
  49504. if (mesh._waitingParentId) {
  49505. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49506. mesh._waitingParentId = undefined;
  49507. }
  49508. if (mesh._waitingActions) {
  49509. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49510. mesh._waitingActions = undefined;
  49511. }
  49512. }
  49513. // freeze world matrix application
  49514. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49515. var currentMesh = scene.meshes[index];
  49516. if (currentMesh._waitingFreezeWorldMatrix) {
  49517. currentMesh.freezeWorldMatrix();
  49518. currentMesh._waitingFreezeWorldMatrix = undefined;
  49519. }
  49520. else {
  49521. currentMesh.computeWorldMatrix(true);
  49522. }
  49523. }
  49524. // Particles Systems
  49525. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49526. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49527. var parsedParticleSystem = parsedData.particleSystems[index];
  49528. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49529. }
  49530. }
  49531. // Lens flares
  49532. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49533. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49534. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49535. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49536. }
  49537. }
  49538. // Shadows
  49539. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49540. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49541. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49542. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49543. }
  49544. }
  49545. // Lights exclusions / inclusions
  49546. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49547. var light = scene.lights[index];
  49548. // Excluded check
  49549. if (light._excludedMeshesIds.length > 0) {
  49550. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49551. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49552. if (excludedMesh) {
  49553. light.excludedMeshes.push(excludedMesh);
  49554. }
  49555. }
  49556. light._excludedMeshesIds = [];
  49557. }
  49558. // Included check
  49559. if (light._includedOnlyMeshesIds.length > 0) {
  49560. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49561. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49562. if (includedOnlyMesh) {
  49563. light.includedOnlyMeshes.push(includedOnlyMesh);
  49564. }
  49565. }
  49566. light._includedOnlyMeshesIds = [];
  49567. }
  49568. }
  49569. // Actions (scene)
  49570. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49571. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49572. }
  49573. // Finish
  49574. return true;
  49575. }
  49576. catch (err) {
  49577. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  49578. if (onError) {
  49579. onError(msg, err);
  49580. }
  49581. else {
  49582. BABYLON.Tools.Log(msg);
  49583. log = null;
  49584. throw err;
  49585. }
  49586. }
  49587. finally {
  49588. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49589. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49590. }
  49591. }
  49592. }
  49593. });
  49594. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49595. })(BABYLON || (BABYLON = {}));
  49596. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49597. var BABYLON;
  49598. (function (BABYLON) {
  49599. var FilesInput = (function () {
  49600. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  49601. this.onProcessFileCallback = function () { return true; };
  49602. this._engine = engine;
  49603. this._currentScene = scene;
  49604. this._sceneLoadedCallback = sceneLoadedCallback;
  49605. this._progressCallback = progressCallback;
  49606. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49607. this._textureLoadingCallback = textureLoadingCallback;
  49608. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49609. this._onReloadCallback = onReloadCallback;
  49610. this._errorCallback = errorCallback;
  49611. }
  49612. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49613. var _this = this;
  49614. if (elementToMonitor) {
  49615. this._elementToMonitor = elementToMonitor;
  49616. this._dragEnterHandler = function (e) { _this.drag(e); };
  49617. this._dragOverHandler = function (e) { _this.drag(e); };
  49618. this._dropHandler = function (e) { _this.drop(e); };
  49619. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  49620. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  49621. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  49622. }
  49623. };
  49624. FilesInput.prototype.dispose = function () {
  49625. if (!this._elementToMonitor) {
  49626. return;
  49627. }
  49628. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  49629. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  49630. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  49631. };
  49632. FilesInput.prototype.renderFunction = function () {
  49633. if (this._additionalRenderLoopLogicCallback) {
  49634. this._additionalRenderLoopLogicCallback();
  49635. }
  49636. if (this._currentScene) {
  49637. if (this._textureLoadingCallback) {
  49638. var remaining = this._currentScene.getWaitingItemsCount();
  49639. if (remaining > 0) {
  49640. this._textureLoadingCallback(remaining);
  49641. }
  49642. }
  49643. this._currentScene.render();
  49644. }
  49645. };
  49646. FilesInput.prototype.drag = function (e) {
  49647. e.stopPropagation();
  49648. e.preventDefault();
  49649. };
  49650. FilesInput.prototype.drop = function (eventDrop) {
  49651. eventDrop.stopPropagation();
  49652. eventDrop.preventDefault();
  49653. this.loadFiles(eventDrop);
  49654. };
  49655. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  49656. var _this = this;
  49657. var reader = folder.createReader();
  49658. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  49659. reader.readEntries(function (entries) {
  49660. remaining.count += entries.length;
  49661. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  49662. var entry = entries_1[_i];
  49663. if (entry.isFile) {
  49664. entry.file(function (file) {
  49665. file.correctName = relativePath + file.name;
  49666. files.push(file);
  49667. if (--remaining.count === 0) {
  49668. callback();
  49669. }
  49670. });
  49671. }
  49672. else if (entry.isDirectory) {
  49673. _this._traverseFolder(entry, files, remaining, callback);
  49674. }
  49675. }
  49676. if (--remaining.count) {
  49677. callback();
  49678. }
  49679. });
  49680. };
  49681. FilesInput.prototype._processFiles = function (files) {
  49682. var skippedFiles = 0;
  49683. for (var i = 0; i < files.length; i++) {
  49684. var name = files[i].correctName.toLowerCase();
  49685. var extension = name.split('.').pop();
  49686. if (!this.onProcessFileCallback(files[i], name, extension)) {
  49687. skippedFiles++;
  49688. continue;
  49689. }
  49690. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  49691. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  49692. this._sceneFileToLoad = files[i];
  49693. }
  49694. else {
  49695. FilesInput.FilesToLoad[name] = files[i];
  49696. }
  49697. }
  49698. if (this._onReloadCallback) {
  49699. this._onReloadCallback(this._sceneFileToLoad);
  49700. }
  49701. else if (skippedFiles < files.length) {
  49702. this.reload();
  49703. }
  49704. };
  49705. FilesInput.prototype.loadFiles = function (event) {
  49706. var _this = this;
  49707. if (this._startingProcessingFilesCallback)
  49708. this._startingProcessingFilesCallback();
  49709. // Handling data transfer via drag'n'drop
  49710. if (event && event.dataTransfer && event.dataTransfer.files) {
  49711. this._filesToLoad = event.dataTransfer.files;
  49712. }
  49713. // Handling files from input files
  49714. if (event && event.target && event.target.files) {
  49715. this._filesToLoad = event.target.files;
  49716. }
  49717. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49718. var files_1 = [];
  49719. var folders = [];
  49720. var items = event.dataTransfer ? event.dataTransfer.items : null;
  49721. for (var i = 0; i < this._filesToLoad.length; i++) {
  49722. var fileToLoad = this._filesToLoad[i];
  49723. var name_1 = fileToLoad.name.toLowerCase();
  49724. var type = fileToLoad.type;
  49725. var entry = void 0;
  49726. fileToLoad.correctName = name_1;
  49727. if (items) {
  49728. var item = items[i];
  49729. if (item.getAsEntry) {
  49730. entry = item.getAsEntry();
  49731. }
  49732. else if (item.webkitGetAsEntry) {
  49733. entry = item.webkitGetAsEntry();
  49734. }
  49735. }
  49736. if (!entry) {
  49737. files_1.push(fileToLoad);
  49738. }
  49739. else {
  49740. if (entry.isDirectory) {
  49741. folders.push(entry);
  49742. }
  49743. else {
  49744. files_1.push(fileToLoad);
  49745. }
  49746. }
  49747. }
  49748. if (folders.length === 0) {
  49749. this._processFiles(files_1);
  49750. }
  49751. else {
  49752. var remaining = { count: folders.length };
  49753. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49754. var folder = folders_1[_i];
  49755. this._traverseFolder(folder, files_1, remaining, function () {
  49756. _this._processFiles(files_1);
  49757. });
  49758. }
  49759. }
  49760. }
  49761. };
  49762. FilesInput.prototype.reload = function () {
  49763. var _this = this;
  49764. // If a ".babylon" file has been provided
  49765. if (this._sceneFileToLoad) {
  49766. if (this._currentScene) {
  49767. if (BABYLON.Tools.errorsCount > 0) {
  49768. BABYLON.Tools.ClearLogCache();
  49769. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49770. }
  49771. this._engine.stopRenderLoop();
  49772. this._currentScene.dispose();
  49773. }
  49774. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49775. _this._currentScene = newScene;
  49776. if (_this._sceneLoadedCallback) {
  49777. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  49778. }
  49779. // Wait for textures and shaders to be ready
  49780. _this._currentScene.executeWhenReady(function () {
  49781. _this._engine.runRenderLoop(function () {
  49782. _this.renderFunction();
  49783. });
  49784. });
  49785. }, function (progress) {
  49786. if (_this._progressCallback) {
  49787. _this._progressCallback(progress);
  49788. }
  49789. }, function (scene, message) {
  49790. _this._currentScene = scene;
  49791. if (_this._errorCallback) {
  49792. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  49793. }
  49794. });
  49795. }
  49796. else {
  49797. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49798. }
  49799. };
  49800. FilesInput.FilesToLoad = new Array();
  49801. return FilesInput;
  49802. }());
  49803. BABYLON.FilesInput = FilesInput;
  49804. })(BABYLON || (BABYLON = {}));
  49805. //# sourceMappingURL=babylon.filesInput.js.map
  49806. var BABYLON;
  49807. (function (BABYLON) {
  49808. /**
  49809. * This class implement a typical dictionary using a string as key and the generic type T as value.
  49810. * The underlying implementation relies on an associative array to ensure the best performances.
  49811. * The value can be anything including 'null' but except 'undefined'
  49812. */
  49813. var StringDictionary = (function () {
  49814. function StringDictionary() {
  49815. this._count = 0;
  49816. this._data = {};
  49817. }
  49818. /**
  49819. * This will clear this dictionary and copy the content from the 'source' one.
  49820. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  49821. * @param source the dictionary to take the content from and copy to this dictionary
  49822. */
  49823. StringDictionary.prototype.copyFrom = function (source) {
  49824. var _this = this;
  49825. this.clear();
  49826. source.forEach(function (t, v) { return _this.add(t, v); });
  49827. };
  49828. /**
  49829. * Get a value based from its key
  49830. * @param key the given key to get the matching value from
  49831. * @return the value if found, otherwise undefined is returned
  49832. */
  49833. StringDictionary.prototype.get = function (key) {
  49834. var val = this._data[key];
  49835. if (val !== undefined) {
  49836. return val;
  49837. }
  49838. return undefined;
  49839. };
  49840. /**
  49841. * Get a value from its key or add it if it doesn't exist.
  49842. * This method will ensure you that a given key/data will be present in the dictionary.
  49843. * @param key the given key to get the matching value from
  49844. * @param factory the factory that will create the value if the key is not present in the dictionary.
  49845. * The factory will only be invoked if there's no data for the given key.
  49846. * @return the value corresponding to the key.
  49847. */
  49848. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  49849. var val = this.get(key);
  49850. if (val !== undefined) {
  49851. return val;
  49852. }
  49853. val = factory(key);
  49854. if (val) {
  49855. this.add(key, val);
  49856. }
  49857. return val;
  49858. };
  49859. /**
  49860. * Get a value from its key if present in the dictionary otherwise add it
  49861. * @param key the key to get the value from
  49862. * @param val if there's no such key/value pair in the dictionary add it with this value
  49863. * @return the value corresponding to the key
  49864. */
  49865. StringDictionary.prototype.getOrAdd = function (key, val) {
  49866. var curVal = this.get(key);
  49867. if (curVal !== undefined) {
  49868. return curVal;
  49869. }
  49870. this.add(key, val);
  49871. return val;
  49872. };
  49873. /**
  49874. * Check if there's a given key in the dictionary
  49875. * @param key the key to check for
  49876. * @return true if the key is present, false otherwise
  49877. */
  49878. StringDictionary.prototype.contains = function (key) {
  49879. return this._data[key] !== undefined;
  49880. };
  49881. /**
  49882. * Add a new key and its corresponding value
  49883. * @param key the key to add
  49884. * @param value the value corresponding to the key
  49885. * @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
  49886. */
  49887. StringDictionary.prototype.add = function (key, value) {
  49888. if (this._data[key] !== undefined) {
  49889. return false;
  49890. }
  49891. this._data[key] = value;
  49892. ++this._count;
  49893. return true;
  49894. };
  49895. StringDictionary.prototype.set = function (key, value) {
  49896. if (this._data[key] === undefined) {
  49897. return false;
  49898. }
  49899. this._data[key] = value;
  49900. return true;
  49901. };
  49902. /**
  49903. * Get the element of the given key and remove it from the dictionary
  49904. * @param key
  49905. */
  49906. StringDictionary.prototype.getAndRemove = function (key) {
  49907. var val = this.get(key);
  49908. if (val !== undefined) {
  49909. delete this._data[key];
  49910. --this._count;
  49911. return val;
  49912. }
  49913. return null;
  49914. };
  49915. /**
  49916. * Remove a key/value from the dictionary.
  49917. * @param key the key to remove
  49918. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  49919. */
  49920. StringDictionary.prototype.remove = function (key) {
  49921. if (this.contains(key)) {
  49922. delete this._data[key];
  49923. --this._count;
  49924. return true;
  49925. }
  49926. return false;
  49927. };
  49928. /**
  49929. * Clear the whole content of the dictionary
  49930. */
  49931. StringDictionary.prototype.clear = function () {
  49932. this._data = {};
  49933. this._count = 0;
  49934. };
  49935. Object.defineProperty(StringDictionary.prototype, "count", {
  49936. get: function () {
  49937. return this._count;
  49938. },
  49939. enumerable: true,
  49940. configurable: true
  49941. });
  49942. /**
  49943. * Execute a callback on each key/val of the dictionary.
  49944. * Note that you can remove any element in this dictionary in the callback implementation
  49945. * @param callback the callback to execute on a given key/value pair
  49946. */
  49947. StringDictionary.prototype.forEach = function (callback) {
  49948. for (var cur in this._data) {
  49949. var val = this._data[cur];
  49950. callback(cur, val);
  49951. }
  49952. };
  49953. /**
  49954. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  49955. * If the callback returns null or undefined the method will iterate to the next key/value pair
  49956. * Note that you can remove any element in this dictionary in the callback implementation
  49957. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  49958. */
  49959. StringDictionary.prototype.first = function (callback) {
  49960. for (var cur in this._data) {
  49961. var val = this._data[cur];
  49962. var res = callback(cur, val);
  49963. if (res) {
  49964. return res;
  49965. }
  49966. }
  49967. return null;
  49968. };
  49969. return StringDictionary;
  49970. }());
  49971. BABYLON.StringDictionary = StringDictionary;
  49972. })(BABYLON || (BABYLON = {}));
  49973. //# sourceMappingURL=babylon.stringDictionary.js.map
  49974. var BABYLON;
  49975. (function (BABYLON) {
  49976. var Tags = (function () {
  49977. function Tags() {
  49978. }
  49979. Tags.EnableFor = function (obj) {
  49980. obj._tags = obj._tags || {};
  49981. obj.hasTags = function () {
  49982. return Tags.HasTags(obj);
  49983. };
  49984. obj.addTags = function (tagsString) {
  49985. return Tags.AddTagsTo(obj, tagsString);
  49986. };
  49987. obj.removeTags = function (tagsString) {
  49988. return Tags.RemoveTagsFrom(obj, tagsString);
  49989. };
  49990. obj.matchesTagsQuery = function (tagsQuery) {
  49991. return Tags.MatchesQuery(obj, tagsQuery);
  49992. };
  49993. };
  49994. Tags.DisableFor = function (obj) {
  49995. delete obj._tags;
  49996. delete obj.hasTags;
  49997. delete obj.addTags;
  49998. delete obj.removeTags;
  49999. delete obj.matchesTagsQuery;
  50000. };
  50001. Tags.HasTags = function (obj) {
  50002. if (!obj._tags) {
  50003. return false;
  50004. }
  50005. return !BABYLON.Tools.IsEmpty(obj._tags);
  50006. };
  50007. Tags.GetTags = function (obj, asString) {
  50008. if (asString === void 0) { asString = true; }
  50009. if (!obj._tags) {
  50010. return null;
  50011. }
  50012. if (asString) {
  50013. var tagsArray = [];
  50014. for (var tag in obj._tags) {
  50015. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  50016. tagsArray.push(tag);
  50017. }
  50018. }
  50019. return tagsArray.join(" ");
  50020. }
  50021. else {
  50022. return obj._tags;
  50023. }
  50024. };
  50025. // the tags 'true' and 'false' are reserved and cannot be used as tags
  50026. // a tag cannot start with '||', '&&', and '!'
  50027. // it cannot contain whitespaces
  50028. Tags.AddTagsTo = function (obj, tagsString) {
  50029. if (!tagsString) {
  50030. return;
  50031. }
  50032. if (typeof tagsString !== "string") {
  50033. return;
  50034. }
  50035. var tags = tagsString.split(" ");
  50036. tags.forEach(function (tag, index, array) {
  50037. Tags._AddTagTo(obj, tag);
  50038. });
  50039. };
  50040. Tags._AddTagTo = function (obj, tag) {
  50041. tag = tag.trim();
  50042. if (tag === "" || tag === "true" || tag === "false") {
  50043. return;
  50044. }
  50045. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  50046. return;
  50047. }
  50048. Tags.EnableFor(obj);
  50049. obj._tags[tag] = true;
  50050. };
  50051. Tags.RemoveTagsFrom = function (obj, tagsString) {
  50052. if (!Tags.HasTags(obj)) {
  50053. return;
  50054. }
  50055. var tags = tagsString.split(" ");
  50056. for (var t in tags) {
  50057. Tags._RemoveTagFrom(obj, tags[t]);
  50058. }
  50059. };
  50060. Tags._RemoveTagFrom = function (obj, tag) {
  50061. delete obj._tags[tag];
  50062. };
  50063. Tags.MatchesQuery = function (obj, tagsQuery) {
  50064. if (tagsQuery === undefined) {
  50065. return true;
  50066. }
  50067. if (tagsQuery === "") {
  50068. return Tags.HasTags(obj);
  50069. }
  50070. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  50071. };
  50072. return Tags;
  50073. }());
  50074. BABYLON.Tags = Tags;
  50075. })(BABYLON || (BABYLON = {}));
  50076. //# sourceMappingURL=babylon.tags.js.map
  50077. var BABYLON;
  50078. (function (BABYLON) {
  50079. var Internals;
  50080. (function (Internals) {
  50081. var AndOrNotEvaluator = (function () {
  50082. function AndOrNotEvaluator() {
  50083. }
  50084. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  50085. if (!query.match(/\([^\(\)]*\)/g)) {
  50086. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  50087. }
  50088. else {
  50089. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  50090. // remove parenthesis
  50091. r = r.slice(1, r.length - 1);
  50092. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  50093. });
  50094. }
  50095. if (query === "true") {
  50096. return true;
  50097. }
  50098. if (query === "false") {
  50099. return false;
  50100. }
  50101. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  50102. };
  50103. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  50104. evaluateCallback = evaluateCallback || (function (r) {
  50105. return r === "true" ? true : false;
  50106. });
  50107. var result;
  50108. var or = parenthesisContent.split("||");
  50109. for (var i in or) {
  50110. if (or.hasOwnProperty(i)) {
  50111. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  50112. var and = ori.split("&&");
  50113. if (and.length > 1) {
  50114. for (var j = 0; j < and.length; ++j) {
  50115. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  50116. if (andj !== "true" && andj !== "false") {
  50117. if (andj[0] === "!") {
  50118. result = !evaluateCallback(andj.substring(1));
  50119. }
  50120. else {
  50121. result = evaluateCallback(andj);
  50122. }
  50123. }
  50124. else {
  50125. result = andj === "true" ? true : false;
  50126. }
  50127. if (!result) {
  50128. ori = "false";
  50129. break;
  50130. }
  50131. }
  50132. }
  50133. if (result || ori === "true") {
  50134. result = true;
  50135. break;
  50136. }
  50137. // result equals false (or undefined)
  50138. if (ori !== "true" && ori !== "false") {
  50139. if (ori[0] === "!") {
  50140. result = !evaluateCallback(ori.substring(1));
  50141. }
  50142. else {
  50143. result = evaluateCallback(ori);
  50144. }
  50145. }
  50146. else {
  50147. result = ori === "true" ? true : false;
  50148. }
  50149. }
  50150. }
  50151. // the whole parenthesis scope is replaced by 'true' or 'false'
  50152. return result ? "true" : "false";
  50153. };
  50154. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  50155. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  50156. // remove whitespaces
  50157. r = r.replace(/[\s]/g, function () { return ""; });
  50158. return r.length % 2 ? "!" : "";
  50159. });
  50160. booleanString = booleanString.trim();
  50161. if (booleanString === "!true") {
  50162. booleanString = "false";
  50163. }
  50164. else if (booleanString === "!false") {
  50165. booleanString = "true";
  50166. }
  50167. return booleanString;
  50168. };
  50169. return AndOrNotEvaluator;
  50170. }());
  50171. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  50172. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50173. })(BABYLON || (BABYLON = {}));
  50174. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  50175. var BABYLON;
  50176. (function (BABYLON) {
  50177. var Database = (function () {
  50178. function Database(urlToScene, callbackManifestChecked) {
  50179. // Handling various flavors of prefixed version of IndexedDB
  50180. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  50181. this.callbackManifestChecked = callbackManifestChecked;
  50182. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  50183. this.db = null;
  50184. this.enableSceneOffline = false;
  50185. this.enableTexturesOffline = false;
  50186. this.manifestVersionFound = 0;
  50187. this.mustUpdateRessources = false;
  50188. this.hasReachedQuota = false;
  50189. if (!Database.IDBStorageEnabled) {
  50190. this.callbackManifestChecked(true);
  50191. }
  50192. else {
  50193. this.checkManifestFile();
  50194. }
  50195. }
  50196. Database.prototype.checkManifestFile = function () {
  50197. var _this = this;
  50198. function noManifestFile() {
  50199. that.enableSceneOffline = false;
  50200. that.enableTexturesOffline = false;
  50201. that.callbackManifestChecked(false);
  50202. }
  50203. var that = this;
  50204. var timeStampUsed = false;
  50205. var manifestURL = this.currentSceneUrl + ".manifest";
  50206. var xhr = new XMLHttpRequest();
  50207. if (navigator.onLine) {
  50208. // Adding a timestamp to by-pass browsers' cache
  50209. timeStampUsed = true;
  50210. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  50211. }
  50212. xhr.open("GET", manifestURL, true);
  50213. xhr.addEventListener("load", function () {
  50214. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  50215. try {
  50216. var manifestFile = JSON.parse(xhr.response);
  50217. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  50218. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  50219. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  50220. _this.manifestVersionFound = manifestFile.version;
  50221. }
  50222. if (_this.callbackManifestChecked) {
  50223. _this.callbackManifestChecked(true);
  50224. }
  50225. }
  50226. catch (ex) {
  50227. noManifestFile();
  50228. }
  50229. }
  50230. else {
  50231. noManifestFile();
  50232. }
  50233. }, false);
  50234. xhr.addEventListener("error", function (event) {
  50235. if (timeStampUsed) {
  50236. timeStampUsed = false;
  50237. // Let's retry without the timeStamp
  50238. // It could fail when coupled with HTML5 Offline API
  50239. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  50240. xhr.open("GET", retryManifestURL, true);
  50241. xhr.send();
  50242. }
  50243. else {
  50244. noManifestFile();
  50245. }
  50246. }, false);
  50247. try {
  50248. xhr.send();
  50249. }
  50250. catch (ex) {
  50251. BABYLON.Tools.Error("Error on XHR send request.");
  50252. that.callbackManifestChecked(false);
  50253. }
  50254. };
  50255. Database.prototype.openAsync = function (successCallback, errorCallback) {
  50256. var _this = this;
  50257. function handleError() {
  50258. that.isSupported = false;
  50259. if (errorCallback)
  50260. errorCallback();
  50261. }
  50262. var that = this;
  50263. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  50264. // Your browser doesn't support IndexedDB
  50265. this.isSupported = false;
  50266. if (errorCallback)
  50267. errorCallback();
  50268. }
  50269. else {
  50270. // If the DB hasn't been opened or created yet
  50271. if (!this.db) {
  50272. this.hasReachedQuota = false;
  50273. this.isSupported = true;
  50274. var request = this.idbFactory.open("babylonjs", 1);
  50275. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  50276. request.onerror = function (event) {
  50277. handleError();
  50278. };
  50279. // executes when a version change transaction cannot complete due to other active transactions
  50280. request.onblocked = function (event) {
  50281. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  50282. handleError();
  50283. };
  50284. // DB has been opened successfully
  50285. request.onsuccess = function (event) {
  50286. _this.db = request.result;
  50287. successCallback();
  50288. };
  50289. // Initialization of the DB. Creating Scenes & Textures stores
  50290. request.onupgradeneeded = function (event) {
  50291. _this.db = (event.target).result;
  50292. try {
  50293. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  50294. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  50295. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  50296. }
  50297. catch (ex) {
  50298. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  50299. handleError();
  50300. }
  50301. };
  50302. }
  50303. else {
  50304. if (successCallback)
  50305. successCallback();
  50306. }
  50307. }
  50308. };
  50309. Database.prototype.loadImageFromDB = function (url, image) {
  50310. var _this = this;
  50311. var completeURL = Database.ReturnFullUrlLocation(url);
  50312. var saveAndLoadImage = function () {
  50313. if (!_this.hasReachedQuota && _this.db !== null) {
  50314. // the texture is not yet in the DB, let's try to save it
  50315. _this._saveImageIntoDBAsync(completeURL, image);
  50316. }
  50317. else {
  50318. image.src = url;
  50319. }
  50320. };
  50321. if (!this.mustUpdateRessources) {
  50322. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  50323. }
  50324. else {
  50325. saveAndLoadImage();
  50326. }
  50327. };
  50328. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  50329. if (this.isSupported && this.db !== null) {
  50330. var texture;
  50331. var transaction = this.db.transaction(["textures"]);
  50332. transaction.onabort = function (event) {
  50333. image.src = url;
  50334. };
  50335. transaction.oncomplete = function (event) {
  50336. var blobTextureURL;
  50337. if (texture) {
  50338. var URL = window.URL || window.webkitURL;
  50339. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  50340. image.onerror = function () {
  50341. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  50342. image.src = url;
  50343. };
  50344. image.src = blobTextureURL;
  50345. }
  50346. else {
  50347. notInDBCallback();
  50348. }
  50349. };
  50350. var getRequest = transaction.objectStore("textures").get(url);
  50351. getRequest.onsuccess = function (event) {
  50352. texture = (event.target).result;
  50353. };
  50354. getRequest.onerror = function (event) {
  50355. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  50356. image.src = url;
  50357. };
  50358. }
  50359. else {
  50360. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50361. image.src = url;
  50362. }
  50363. };
  50364. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  50365. var _this = this;
  50366. if (this.isSupported) {
  50367. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  50368. var generateBlobUrl = function () {
  50369. var blobTextureURL;
  50370. if (blob) {
  50371. var URL = window.URL || window.webkitURL;
  50372. try {
  50373. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  50374. }
  50375. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  50376. catch (ex) {
  50377. blobTextureURL = URL.createObjectURL(blob);
  50378. }
  50379. }
  50380. image.src = blobTextureURL;
  50381. };
  50382. if (Database.IsUASupportingBlobStorage) {
  50383. var xhr = new XMLHttpRequest(), blob;
  50384. xhr.open("GET", url, true);
  50385. xhr.responseType = "blob";
  50386. xhr.addEventListener("load", function () {
  50387. if (xhr.status === 200) {
  50388. // Blob as response (XHR2)
  50389. blob = xhr.response;
  50390. var transaction = _this.db.transaction(["textures"], "readwrite");
  50391. // the transaction could abort because of a QuotaExceededError error
  50392. transaction.onabort = function (event) {
  50393. try {
  50394. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50395. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50396. _this.hasReachedQuota = true;
  50397. }
  50398. }
  50399. catch (ex) { }
  50400. generateBlobUrl();
  50401. };
  50402. transaction.oncomplete = function (event) {
  50403. generateBlobUrl();
  50404. };
  50405. var newTexture = { textureUrl: url, data: blob };
  50406. try {
  50407. // Put the blob into the dabase
  50408. var addRequest = transaction.objectStore("textures").put(newTexture);
  50409. addRequest.onsuccess = function (event) {
  50410. };
  50411. addRequest.onerror = function (event) {
  50412. generateBlobUrl();
  50413. };
  50414. }
  50415. catch (ex) {
  50416. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  50417. if (ex.code === 25) {
  50418. Database.IsUASupportingBlobStorage = false;
  50419. }
  50420. image.src = url;
  50421. }
  50422. }
  50423. else {
  50424. image.src = url;
  50425. }
  50426. }, false);
  50427. xhr.addEventListener("error", function (event) {
  50428. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  50429. image.src = url;
  50430. }, false);
  50431. xhr.send();
  50432. }
  50433. else {
  50434. image.src = url;
  50435. }
  50436. }
  50437. else {
  50438. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50439. image.src = url;
  50440. }
  50441. };
  50442. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  50443. var _this = this;
  50444. var updateVersion = function (event) {
  50445. // the version is not yet in the DB or we need to update it
  50446. _this._saveVersionIntoDBAsync(url, versionLoaded);
  50447. };
  50448. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  50449. };
  50450. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  50451. var _this = this;
  50452. if (this.isSupported) {
  50453. var version;
  50454. try {
  50455. var transaction = this.db.transaction(["versions"]);
  50456. transaction.oncomplete = function (event) {
  50457. if (version) {
  50458. // If the version in the JSON file is > than the version in DB
  50459. if (_this.manifestVersionFound > version.data) {
  50460. _this.mustUpdateRessources = true;
  50461. updateInDBCallback();
  50462. }
  50463. else {
  50464. callback(version.data);
  50465. }
  50466. }
  50467. else {
  50468. _this.mustUpdateRessources = true;
  50469. updateInDBCallback();
  50470. }
  50471. };
  50472. transaction.onabort = function (event) {
  50473. callback(-1);
  50474. };
  50475. var getRequest = transaction.objectStore("versions").get(url);
  50476. getRequest.onsuccess = function (event) {
  50477. version = (event.target).result;
  50478. };
  50479. getRequest.onerror = function (event) {
  50480. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  50481. callback(-1);
  50482. };
  50483. }
  50484. catch (ex) {
  50485. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  50486. callback(-1);
  50487. }
  50488. }
  50489. else {
  50490. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50491. callback(-1);
  50492. }
  50493. };
  50494. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  50495. var _this = this;
  50496. if (this.isSupported && !this.hasReachedQuota) {
  50497. try {
  50498. // Open a transaction to the database
  50499. var transaction = this.db.transaction(["versions"], "readwrite");
  50500. // the transaction could abort because of a QuotaExceededError error
  50501. transaction.onabort = function (event) {
  50502. try {
  50503. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50504. _this.hasReachedQuota = true;
  50505. }
  50506. }
  50507. catch (ex) { }
  50508. callback(-1);
  50509. };
  50510. transaction.oncomplete = function (event) {
  50511. callback(_this.manifestVersionFound);
  50512. };
  50513. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  50514. // Put the scene into the database
  50515. var addRequest = transaction.objectStore("versions").put(newVersion);
  50516. addRequest.onsuccess = function (event) {
  50517. };
  50518. addRequest.onerror = function (event) {
  50519. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  50520. };
  50521. }
  50522. catch (ex) {
  50523. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  50524. callback(-1);
  50525. }
  50526. }
  50527. else {
  50528. callback(-1);
  50529. }
  50530. };
  50531. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  50532. var _this = this;
  50533. var completeUrl = Database.ReturnFullUrlLocation(url);
  50534. var saveAndLoadFile = function (event) {
  50535. // the scene is not yet in the DB, let's try to save it
  50536. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  50537. };
  50538. this._checkVersionFromDB(completeUrl, function (version) {
  50539. if (version !== -1) {
  50540. if (!_this.mustUpdateRessources) {
  50541. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  50542. }
  50543. else {
  50544. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  50545. }
  50546. }
  50547. else {
  50548. errorCallback();
  50549. }
  50550. });
  50551. };
  50552. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  50553. if (this.isSupported) {
  50554. var targetStore;
  50555. if (url.indexOf(".babylon") !== -1) {
  50556. targetStore = "scenes";
  50557. }
  50558. else {
  50559. targetStore = "textures";
  50560. }
  50561. var file;
  50562. var transaction = this.db.transaction([targetStore]);
  50563. transaction.oncomplete = function (event) {
  50564. if (file) {
  50565. callback(file.data);
  50566. }
  50567. else {
  50568. notInDBCallback();
  50569. }
  50570. };
  50571. transaction.onabort = function (event) {
  50572. notInDBCallback();
  50573. };
  50574. var getRequest = transaction.objectStore(targetStore).get(url);
  50575. getRequest.onsuccess = function (event) {
  50576. file = (event.target).result;
  50577. };
  50578. getRequest.onerror = function (event) {
  50579. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  50580. notInDBCallback();
  50581. };
  50582. }
  50583. else {
  50584. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50585. callback();
  50586. }
  50587. };
  50588. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  50589. var _this = this;
  50590. if (this.isSupported) {
  50591. var targetStore;
  50592. if (url.indexOf(".babylon") !== -1) {
  50593. targetStore = "scenes";
  50594. }
  50595. else {
  50596. targetStore = "textures";
  50597. }
  50598. // Create XHR
  50599. var xhr = new XMLHttpRequest(), fileData;
  50600. xhr.open("GET", url, true);
  50601. if (useArrayBuffer) {
  50602. xhr.responseType = "arraybuffer";
  50603. }
  50604. xhr.onprogress = progressCallback;
  50605. xhr.addEventListener("load", function () {
  50606. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  50607. // Blob as response (XHR2)
  50608. //fileData = xhr.responseText;
  50609. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  50610. if (!_this.hasReachedQuota) {
  50611. // Open a transaction to the database
  50612. var transaction = _this.db.transaction([targetStore], "readwrite");
  50613. // the transaction could abort because of a QuotaExceededError error
  50614. transaction.onabort = function (event) {
  50615. try {
  50616. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50617. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50618. _this.hasReachedQuota = true;
  50619. }
  50620. }
  50621. catch (ex) { }
  50622. callback(fileData);
  50623. };
  50624. transaction.oncomplete = function (event) {
  50625. callback(fileData);
  50626. };
  50627. var newFile;
  50628. if (targetStore === "scenes") {
  50629. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  50630. }
  50631. else {
  50632. newFile = { textureUrl: url, data: fileData };
  50633. }
  50634. try {
  50635. // Put the scene into the database
  50636. var addRequest = transaction.objectStore(targetStore).put(newFile);
  50637. addRequest.onsuccess = function (event) {
  50638. };
  50639. addRequest.onerror = function (event) {
  50640. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  50641. };
  50642. }
  50643. catch (ex) {
  50644. callback(fileData);
  50645. }
  50646. }
  50647. else {
  50648. callback(fileData);
  50649. }
  50650. }
  50651. else {
  50652. callback();
  50653. }
  50654. }, false);
  50655. xhr.addEventListener("error", function (event) {
  50656. BABYLON.Tools.Error("error on XHR request.");
  50657. callback();
  50658. }, false);
  50659. xhr.send();
  50660. }
  50661. else {
  50662. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50663. callback();
  50664. }
  50665. };
  50666. Database.IsUASupportingBlobStorage = true;
  50667. Database.IDBStorageEnabled = true;
  50668. Database.parseURL = function (url) {
  50669. var a = document.createElement('a');
  50670. a.href = url;
  50671. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  50672. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  50673. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  50674. return absLocation;
  50675. };
  50676. Database.ReturnFullUrlLocation = function (url) {
  50677. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  50678. return (Database.parseURL(window.location.href) + url);
  50679. }
  50680. else {
  50681. return url;
  50682. }
  50683. };
  50684. return Database;
  50685. }());
  50686. BABYLON.Database = Database;
  50687. })(BABYLON || (BABYLON = {}));
  50688. //# sourceMappingURL=babylon.database.js.map
  50689. var BABYLON;
  50690. (function (BABYLON) {
  50691. var FresnelParameters = (function () {
  50692. function FresnelParameters() {
  50693. this._isEnabled = true;
  50694. this.leftColor = BABYLON.Color3.White();
  50695. this.rightColor = BABYLON.Color3.Black();
  50696. this.bias = 0;
  50697. this.power = 1;
  50698. }
  50699. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  50700. get: function () {
  50701. return this._isEnabled;
  50702. },
  50703. set: function (value) {
  50704. if (this._isEnabled === value) {
  50705. return;
  50706. }
  50707. this._isEnabled = value;
  50708. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  50709. },
  50710. enumerable: true,
  50711. configurable: true
  50712. });
  50713. FresnelParameters.prototype.clone = function () {
  50714. var newFresnelParameters = new FresnelParameters();
  50715. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  50716. return newFresnelParameters;
  50717. };
  50718. FresnelParameters.prototype.serialize = function () {
  50719. var serializationObject = {};
  50720. serializationObject.isEnabled = this.isEnabled;
  50721. serializationObject.leftColor = this.leftColor;
  50722. serializationObject.rightColor = this.rightColor;
  50723. serializationObject.bias = this.bias;
  50724. serializationObject.power = this.power;
  50725. return serializationObject;
  50726. };
  50727. FresnelParameters.Parse = function (parsedFresnelParameters) {
  50728. var fresnelParameters = new FresnelParameters();
  50729. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  50730. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  50731. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  50732. fresnelParameters.bias = parsedFresnelParameters.bias;
  50733. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  50734. return fresnelParameters;
  50735. };
  50736. return FresnelParameters;
  50737. }());
  50738. BABYLON.FresnelParameters = FresnelParameters;
  50739. })(BABYLON || (BABYLON = {}));
  50740. //# sourceMappingURL=babylon.fresnelParameters.js.map
  50741. var BABYLON;
  50742. (function (BABYLON) {
  50743. var MultiMaterial = (function (_super) {
  50744. __extends(MultiMaterial, _super);
  50745. function MultiMaterial(name, scene) {
  50746. var _this = _super.call(this, name, scene, true) || this;
  50747. scene.multiMaterials.push(_this);
  50748. _this.subMaterials = new Array();
  50749. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  50750. return _this;
  50751. }
  50752. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  50753. get: function () {
  50754. return this._subMaterials;
  50755. },
  50756. set: function (value) {
  50757. this._subMaterials = value;
  50758. this._hookArray(value);
  50759. },
  50760. enumerable: true,
  50761. configurable: true
  50762. });
  50763. MultiMaterial.prototype._hookArray = function (array) {
  50764. var _this = this;
  50765. var oldPush = array.push;
  50766. array.push = function () {
  50767. var items = [];
  50768. for (var _i = 0; _i < arguments.length; _i++) {
  50769. items[_i] = arguments[_i];
  50770. }
  50771. var result = oldPush.apply(array, items);
  50772. _this._markAllSubMeshesAsTexturesDirty();
  50773. return result;
  50774. };
  50775. var oldSplice = array.splice;
  50776. array.splice = function (index, deleteCount) {
  50777. var deleted = oldSplice.apply(array, [index, deleteCount]);
  50778. _this._markAllSubMeshesAsTexturesDirty();
  50779. return deleted;
  50780. };
  50781. };
  50782. // Properties
  50783. MultiMaterial.prototype.getSubMaterial = function (index) {
  50784. if (index < 0 || index >= this.subMaterials.length) {
  50785. return this.getScene().defaultMaterial;
  50786. }
  50787. return this.subMaterials[index];
  50788. };
  50789. MultiMaterial.prototype.getActiveTextures = function () {
  50790. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  50791. var _a;
  50792. };
  50793. // Methods
  50794. MultiMaterial.prototype.getClassName = function () {
  50795. return "MultiMaterial";
  50796. };
  50797. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  50798. for (var index = 0; index < this.subMaterials.length; index++) {
  50799. var subMaterial = this.subMaterials[index];
  50800. if (subMaterial) {
  50801. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  50802. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  50803. return false;
  50804. }
  50805. continue;
  50806. }
  50807. if (!this.subMaterials[index].isReady(mesh)) {
  50808. return false;
  50809. }
  50810. }
  50811. }
  50812. return true;
  50813. };
  50814. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  50815. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  50816. for (var index = 0; index < this.subMaterials.length; index++) {
  50817. var subMaterial = null;
  50818. if (cloneChildren) {
  50819. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  50820. }
  50821. else {
  50822. subMaterial = this.subMaterials[index];
  50823. }
  50824. newMultiMaterial.subMaterials.push(subMaterial);
  50825. }
  50826. return newMultiMaterial;
  50827. };
  50828. MultiMaterial.prototype.serialize = function () {
  50829. var serializationObject = {};
  50830. serializationObject.name = this.name;
  50831. serializationObject.id = this.id;
  50832. serializationObject.tags = BABYLON.Tags.GetTags(this);
  50833. serializationObject.materials = [];
  50834. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  50835. var subMat = this.subMaterials[matIndex];
  50836. if (subMat) {
  50837. serializationObject.materials.push(subMat.id);
  50838. }
  50839. else {
  50840. serializationObject.materials.push(null);
  50841. }
  50842. }
  50843. return serializationObject;
  50844. };
  50845. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50846. var scene = this.getScene();
  50847. if (!scene) {
  50848. return;
  50849. }
  50850. var index = scene.multiMaterials.indexOf(this);
  50851. if (index >= 0) {
  50852. scene.multiMaterials.splice(index, 1);
  50853. }
  50854. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50855. };
  50856. return MultiMaterial;
  50857. }(BABYLON.Material));
  50858. BABYLON.MultiMaterial = MultiMaterial;
  50859. })(BABYLON || (BABYLON = {}));
  50860. //# sourceMappingURL=babylon.multiMaterial.js.map
  50861. var BABYLON;
  50862. (function (BABYLON) {
  50863. var FreeCameraTouchInput = (function () {
  50864. function FreeCameraTouchInput() {
  50865. this._offsetX = null;
  50866. this._offsetY = null;
  50867. this._pointerCount = 0;
  50868. this._pointerPressed = [];
  50869. this.touchAngularSensibility = 200000.0;
  50870. this.touchMoveSensibility = 250.0;
  50871. }
  50872. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  50873. var _this = this;
  50874. var previousPosition;
  50875. if (this._pointerInput === undefined) {
  50876. this._onLostFocus = function (evt) {
  50877. _this._offsetX = null;
  50878. _this._offsetY = null;
  50879. };
  50880. this._pointerInput = function (p, s) {
  50881. var evt = p.event;
  50882. if (evt.pointerType === "mouse") {
  50883. return;
  50884. }
  50885. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50886. if (!noPreventDefault) {
  50887. evt.preventDefault();
  50888. }
  50889. _this._pointerPressed.push(evt.pointerId);
  50890. if (_this._pointerPressed.length !== 1) {
  50891. return;
  50892. }
  50893. previousPosition = {
  50894. x: evt.clientX,
  50895. y: evt.clientY
  50896. };
  50897. }
  50898. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  50899. if (!noPreventDefault) {
  50900. evt.preventDefault();
  50901. }
  50902. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50903. if (index === -1) {
  50904. return;
  50905. }
  50906. _this._pointerPressed.splice(index, 1);
  50907. if (index != 0) {
  50908. return;
  50909. }
  50910. previousPosition = null;
  50911. _this._offsetX = null;
  50912. _this._offsetY = null;
  50913. }
  50914. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50915. if (!noPreventDefault) {
  50916. evt.preventDefault();
  50917. }
  50918. if (!previousPosition) {
  50919. return;
  50920. }
  50921. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50922. if (index != 0) {
  50923. return;
  50924. }
  50925. _this._offsetX = evt.clientX - previousPosition.x;
  50926. _this._offsetY = -(evt.clientY - previousPosition.y);
  50927. }
  50928. };
  50929. }
  50930. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  50931. element.addEventListener("blur", this._onLostFocus);
  50932. };
  50933. FreeCameraTouchInput.prototype.detachControl = function (element) {
  50934. if (this._pointerInput && element) {
  50935. this.camera.getScene().onPointerObservable.remove(this._observer);
  50936. this._observer = null;
  50937. element.removeEventListener("blur", this._onLostFocus);
  50938. this._onLostFocus = null;
  50939. this._pointerPressed = [];
  50940. this._offsetX = null;
  50941. this._offsetY = null;
  50942. this._pointerCount = 0;
  50943. }
  50944. };
  50945. FreeCameraTouchInput.prototype.checkInputs = function () {
  50946. if (this._offsetX) {
  50947. var camera = this.camera;
  50948. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  50949. if (this._pointerPressed.length > 1) {
  50950. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  50951. }
  50952. else {
  50953. var speed = camera._computeLocalCameraSpeed();
  50954. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  50955. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  50956. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  50957. }
  50958. }
  50959. };
  50960. FreeCameraTouchInput.prototype.getClassName = function () {
  50961. return "FreeCameraTouchInput";
  50962. };
  50963. FreeCameraTouchInput.prototype.getSimpleName = function () {
  50964. return "touch";
  50965. };
  50966. __decorate([
  50967. BABYLON.serialize()
  50968. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  50969. __decorate([
  50970. BABYLON.serialize()
  50971. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  50972. return FreeCameraTouchInput;
  50973. }());
  50974. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  50975. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  50976. })(BABYLON || (BABYLON = {}));
  50977. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  50978. /// <reference path="babylon.freeCamera.ts" />
  50979. var BABYLON;
  50980. (function (BABYLON) {
  50981. // We're mainly based on the logic defined into the FreeCamera code
  50982. var TouchCamera = (function (_super) {
  50983. __extends(TouchCamera, _super);
  50984. //-- end properties for backward compatibility for inputs
  50985. function TouchCamera(name, position, scene) {
  50986. var _this = _super.call(this, name, position, scene) || this;
  50987. _this.inputs.addTouch();
  50988. _this._setupInputs();
  50989. return _this;
  50990. }
  50991. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  50992. //-- Begin properties for backward compatibility for inputs
  50993. get: function () {
  50994. var touch = this.inputs.attached["touch"];
  50995. if (touch)
  50996. return touch.touchAngularSensibility;
  50997. },
  50998. set: function (value) {
  50999. var touch = this.inputs.attached["touch"];
  51000. if (touch)
  51001. touch.touchAngularSensibility = value;
  51002. },
  51003. enumerable: true,
  51004. configurable: true
  51005. });
  51006. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  51007. get: function () {
  51008. var touch = this.inputs.attached["touch"];
  51009. if (touch)
  51010. return touch.touchMoveSensibility;
  51011. },
  51012. set: function (value) {
  51013. var touch = this.inputs.attached["touch"];
  51014. if (touch)
  51015. touch.touchMoveSensibility = value;
  51016. },
  51017. enumerable: true,
  51018. configurable: true
  51019. });
  51020. TouchCamera.prototype.getClassName = function () {
  51021. return "TouchCamera";
  51022. };
  51023. TouchCamera.prototype._setupInputs = function () {
  51024. var mouse = this.inputs.attached["mouse"];
  51025. if (mouse) {
  51026. mouse.touchEnabled = false;
  51027. }
  51028. };
  51029. return TouchCamera;
  51030. }(BABYLON.FreeCamera));
  51031. BABYLON.TouchCamera = TouchCamera;
  51032. })(BABYLON || (BABYLON = {}));
  51033. //# sourceMappingURL=babylon.touchCamera.js.map
  51034. var BABYLON;
  51035. (function (BABYLON) {
  51036. var ProceduralTexture = (function (_super) {
  51037. __extends(ProceduralTexture, _super);
  51038. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  51039. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51040. if (isCube === void 0) { isCube = false; }
  51041. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51042. _this.isCube = isCube;
  51043. _this.isEnabled = true;
  51044. _this._currentRefreshId = -1;
  51045. _this._refreshRate = 1;
  51046. _this._vertexBuffers = {};
  51047. _this._uniforms = new Array();
  51048. _this._samplers = new Array();
  51049. _this._textures = new Array();
  51050. _this._floats = new Array();
  51051. _this._floatsArrays = {};
  51052. _this._colors3 = new Array();
  51053. _this._colors4 = new Array();
  51054. _this._vectors2 = new Array();
  51055. _this._vectors3 = new Array();
  51056. _this._matrices = new Array();
  51057. _this._fallbackTextureUsed = false;
  51058. scene._proceduralTextures.push(_this);
  51059. _this.name = name;
  51060. _this.isRenderTarget = true;
  51061. _this._size = size;
  51062. _this._generateMipMaps = generateMipMaps;
  51063. _this.setFragment(fragment);
  51064. _this._fallbackTexture = fallbackTexture;
  51065. var engine = scene.getEngine();
  51066. if (isCube) {
  51067. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  51068. _this.setFloat("face", 0);
  51069. }
  51070. else {
  51071. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  51072. }
  51073. // VBO
  51074. var vertices = [];
  51075. vertices.push(1, 1);
  51076. vertices.push(-1, 1);
  51077. vertices.push(-1, -1);
  51078. vertices.push(1, -1);
  51079. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  51080. _this._createIndexBuffer();
  51081. return _this;
  51082. }
  51083. ProceduralTexture.prototype._createIndexBuffer = function () {
  51084. var engine = this.getScene().getEngine();
  51085. // Indices
  51086. var indices = [];
  51087. indices.push(0);
  51088. indices.push(1);
  51089. indices.push(2);
  51090. indices.push(0);
  51091. indices.push(2);
  51092. indices.push(3);
  51093. this._indexBuffer = engine.createIndexBuffer(indices);
  51094. };
  51095. ProceduralTexture.prototype._rebuild = function () {
  51096. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  51097. this._createIndexBuffer();
  51098. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  51099. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  51100. }
  51101. };
  51102. ProceduralTexture.prototype.reset = function () {
  51103. if (this._effect === undefined) {
  51104. return;
  51105. }
  51106. var engine = this.getScene().getEngine();
  51107. engine._releaseEffect(this._effect);
  51108. };
  51109. ProceduralTexture.prototype.isReady = function () {
  51110. var _this = this;
  51111. var engine = this.getScene().getEngine();
  51112. var shaders;
  51113. if (!this._fragment) {
  51114. return false;
  51115. }
  51116. if (this._fallbackTextureUsed) {
  51117. return true;
  51118. }
  51119. if (this._fragment.fragmentElement !== undefined) {
  51120. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  51121. }
  51122. else {
  51123. shaders = { vertex: "procedural", fragment: this._fragment };
  51124. }
  51125. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  51126. _this.releaseInternalTexture();
  51127. if (_this._fallbackTexture) {
  51128. _this._texture = _this._fallbackTexture._texture;
  51129. _this._texture.incrementReferences();
  51130. }
  51131. _this._fallbackTextureUsed = true;
  51132. });
  51133. return this._effect.isReady();
  51134. };
  51135. ProceduralTexture.prototype.resetRefreshCounter = function () {
  51136. this._currentRefreshId = -1;
  51137. };
  51138. ProceduralTexture.prototype.setFragment = function (fragment) {
  51139. this._fragment = fragment;
  51140. };
  51141. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  51142. get: function () {
  51143. return this._refreshRate;
  51144. },
  51145. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51146. set: function (value) {
  51147. this._refreshRate = value;
  51148. this.resetRefreshCounter();
  51149. },
  51150. enumerable: true,
  51151. configurable: true
  51152. });
  51153. ProceduralTexture.prototype._shouldRender = function () {
  51154. if (!this.isEnabled || !this.isReady() || !this._texture) {
  51155. return false;
  51156. }
  51157. if (this._fallbackTextureUsed) {
  51158. return false;
  51159. }
  51160. if (this._currentRefreshId === -1) {
  51161. this._currentRefreshId = 1;
  51162. return true;
  51163. }
  51164. if (this.refreshRate === this._currentRefreshId) {
  51165. this._currentRefreshId = 1;
  51166. return true;
  51167. }
  51168. this._currentRefreshId++;
  51169. return false;
  51170. };
  51171. ProceduralTexture.prototype.getRenderSize = function () {
  51172. return this._size;
  51173. };
  51174. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  51175. if (this._fallbackTextureUsed) {
  51176. return;
  51177. }
  51178. this.releaseInternalTexture();
  51179. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  51180. };
  51181. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  51182. if (this._uniforms.indexOf(uniformName) === -1) {
  51183. this._uniforms.push(uniformName);
  51184. }
  51185. };
  51186. ProceduralTexture.prototype.setTexture = function (name, texture) {
  51187. if (this._samplers.indexOf(name) === -1) {
  51188. this._samplers.push(name);
  51189. }
  51190. this._textures[name] = texture;
  51191. return this;
  51192. };
  51193. ProceduralTexture.prototype.setFloat = function (name, value) {
  51194. this._checkUniform(name);
  51195. this._floats[name] = value;
  51196. return this;
  51197. };
  51198. ProceduralTexture.prototype.setFloats = function (name, value) {
  51199. this._checkUniform(name);
  51200. this._floatsArrays[name] = value;
  51201. return this;
  51202. };
  51203. ProceduralTexture.prototype.setColor3 = function (name, value) {
  51204. this._checkUniform(name);
  51205. this._colors3[name] = value;
  51206. return this;
  51207. };
  51208. ProceduralTexture.prototype.setColor4 = function (name, value) {
  51209. this._checkUniform(name);
  51210. this._colors4[name] = value;
  51211. return this;
  51212. };
  51213. ProceduralTexture.prototype.setVector2 = function (name, value) {
  51214. this._checkUniform(name);
  51215. this._vectors2[name] = value;
  51216. return this;
  51217. };
  51218. ProceduralTexture.prototype.setVector3 = function (name, value) {
  51219. this._checkUniform(name);
  51220. this._vectors3[name] = value;
  51221. return this;
  51222. };
  51223. ProceduralTexture.prototype.setMatrix = function (name, value) {
  51224. this._checkUniform(name);
  51225. this._matrices[name] = value;
  51226. return this;
  51227. };
  51228. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  51229. var scene = this.getScene();
  51230. var engine = scene.getEngine();
  51231. // Render
  51232. engine.enableEffect(this._effect);
  51233. engine.setState(false);
  51234. // Texture
  51235. for (var name in this._textures) {
  51236. this._effect.setTexture(name, this._textures[name]);
  51237. }
  51238. // Float
  51239. for (name in this._floats) {
  51240. this._effect.setFloat(name, this._floats[name]);
  51241. }
  51242. // Floats
  51243. for (name in this._floatsArrays) {
  51244. this._effect.setArray(name, this._floatsArrays[name]);
  51245. }
  51246. // Color3
  51247. for (name in this._colors3) {
  51248. this._effect.setColor3(name, this._colors3[name]);
  51249. }
  51250. // Color4
  51251. for (name in this._colors4) {
  51252. var color = this._colors4[name];
  51253. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  51254. }
  51255. // Vector2
  51256. for (name in this._vectors2) {
  51257. this._effect.setVector2(name, this._vectors2[name]);
  51258. }
  51259. // Vector3
  51260. for (name in this._vectors3) {
  51261. this._effect.setVector3(name, this._vectors3[name]);
  51262. }
  51263. // Matrix
  51264. for (name in this._matrices) {
  51265. this._effect.setMatrix(name, this._matrices[name]);
  51266. }
  51267. if (this.isCube) {
  51268. for (var face = 0; face < 6; face++) {
  51269. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  51270. // VBOs
  51271. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  51272. this._effect.setFloat("face", face);
  51273. // Clear
  51274. engine.clear(scene.clearColor, true, true, true);
  51275. // Draw order
  51276. engine.draw(true, 0, 6);
  51277. // Mipmaps
  51278. if (face === 5) {
  51279. engine.generateMipMapsForCubemap(this._texture);
  51280. }
  51281. }
  51282. }
  51283. else {
  51284. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  51285. // VBOs
  51286. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  51287. // Clear
  51288. engine.clear(scene.clearColor, true, true, true);
  51289. // Draw order
  51290. engine.draw(true, 0, 6);
  51291. }
  51292. // Unbind
  51293. engine.unBindFramebuffer(this._texture, this.isCube);
  51294. if (this.onGenerated) {
  51295. this.onGenerated();
  51296. }
  51297. };
  51298. ProceduralTexture.prototype.clone = function () {
  51299. var textureSize = this.getSize();
  51300. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  51301. // Base texture
  51302. newTexture.hasAlpha = this.hasAlpha;
  51303. newTexture.level = this.level;
  51304. // RenderTarget Texture
  51305. newTexture.coordinatesMode = this.coordinatesMode;
  51306. return newTexture;
  51307. };
  51308. ProceduralTexture.prototype.dispose = function () {
  51309. var index = this.getScene()._proceduralTextures.indexOf(this);
  51310. if (index >= 0) {
  51311. this.getScene()._proceduralTextures.splice(index, 1);
  51312. }
  51313. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  51314. if (vertexBuffer) {
  51315. vertexBuffer.dispose();
  51316. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  51317. }
  51318. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  51319. this._indexBuffer = null;
  51320. }
  51321. _super.prototype.dispose.call(this);
  51322. };
  51323. return ProceduralTexture;
  51324. }(BABYLON.Texture));
  51325. BABYLON.ProceduralTexture = ProceduralTexture;
  51326. })(BABYLON || (BABYLON = {}));
  51327. //# sourceMappingURL=babylon.proceduralTexture.js.map
  51328. /// <reference path="babylon.proceduralTexture.ts" />
  51329. var BABYLON;
  51330. (function (BABYLON) {
  51331. var CustomProceduralTexture = (function (_super) {
  51332. __extends(CustomProceduralTexture, _super);
  51333. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  51334. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  51335. _this._animate = true;
  51336. _this._time = 0;
  51337. _this._texturePath = texturePath;
  51338. //Try to load json
  51339. _this.loadJson(texturePath);
  51340. _this.refreshRate = 1;
  51341. return _this;
  51342. }
  51343. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  51344. var _this = this;
  51345. var that = this;
  51346. function noConfigFile() {
  51347. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  51348. try {
  51349. that.setFragment(that._texturePath);
  51350. }
  51351. catch (ex) {
  51352. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  51353. }
  51354. }
  51355. var configFileUrl = jsonUrl + "/config.json";
  51356. var xhr = new XMLHttpRequest();
  51357. xhr.open("GET", configFileUrl, true);
  51358. xhr.addEventListener("load", function () {
  51359. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  51360. try {
  51361. _this._config = JSON.parse(xhr.response);
  51362. _this.updateShaderUniforms();
  51363. _this.updateTextures();
  51364. _this.setFragment(_this._texturePath + "/custom");
  51365. _this._animate = _this._config.animate;
  51366. _this.refreshRate = _this._config.refreshrate;
  51367. }
  51368. catch (ex) {
  51369. noConfigFile();
  51370. }
  51371. }
  51372. else {
  51373. noConfigFile();
  51374. }
  51375. }, false);
  51376. xhr.addEventListener("error", function () {
  51377. noConfigFile();
  51378. }, false);
  51379. try {
  51380. xhr.send();
  51381. }
  51382. catch (ex) {
  51383. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  51384. }
  51385. };
  51386. CustomProceduralTexture.prototype.isReady = function () {
  51387. if (!_super.prototype.isReady.call(this)) {
  51388. return false;
  51389. }
  51390. for (var name in this._textures) {
  51391. var texture = this._textures[name];
  51392. if (!texture.isReady()) {
  51393. return false;
  51394. }
  51395. }
  51396. return true;
  51397. };
  51398. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  51399. if (this._animate) {
  51400. this._time += this.getScene().getAnimationRatio() * 0.03;
  51401. this.updateShaderUniforms();
  51402. }
  51403. _super.prototype.render.call(this, useCameraPostProcess);
  51404. };
  51405. CustomProceduralTexture.prototype.updateTextures = function () {
  51406. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  51407. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  51408. }
  51409. };
  51410. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  51411. if (this._config) {
  51412. for (var j = 0; j < this._config.uniforms.length; j++) {
  51413. var uniform = this._config.uniforms[j];
  51414. switch (uniform.type) {
  51415. case "float":
  51416. this.setFloat(uniform.name, uniform.value);
  51417. break;
  51418. case "color3":
  51419. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  51420. break;
  51421. case "color4":
  51422. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  51423. break;
  51424. case "vector2":
  51425. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  51426. break;
  51427. case "vector3":
  51428. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  51429. break;
  51430. }
  51431. }
  51432. }
  51433. this.setFloat("time", this._time);
  51434. };
  51435. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  51436. get: function () {
  51437. return this._animate;
  51438. },
  51439. set: function (value) {
  51440. this._animate = value;
  51441. },
  51442. enumerable: true,
  51443. configurable: true
  51444. });
  51445. return CustomProceduralTexture;
  51446. }(BABYLON.ProceduralTexture));
  51447. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  51448. })(BABYLON || (BABYLON = {}));
  51449. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  51450. var BABYLON;
  51451. (function (BABYLON) {
  51452. var FreeCameraGamepadInput = (function () {
  51453. function FreeCameraGamepadInput() {
  51454. this.gamepadAngularSensibility = 200;
  51455. this.gamepadMoveSensibility = 40;
  51456. // private members
  51457. this._cameraTransform = BABYLON.Matrix.Identity();
  51458. this._deltaTransform = BABYLON.Vector3.Zero();
  51459. this._vector3 = BABYLON.Vector3.Zero();
  51460. this._vector2 = BABYLON.Vector2.Zero();
  51461. }
  51462. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  51463. var _this = this;
  51464. var manager = this.camera.getScene().gamepadManager;
  51465. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  51466. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  51467. // prioritize XBOX gamepads.
  51468. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  51469. _this.gamepad = gamepad;
  51470. }
  51471. }
  51472. });
  51473. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  51474. if (_this.gamepad === gamepad) {
  51475. _this.gamepad = null;
  51476. }
  51477. });
  51478. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  51479. };
  51480. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  51481. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  51482. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  51483. this.gamepad = null;
  51484. };
  51485. FreeCameraGamepadInput.prototype.checkInputs = function () {
  51486. if (this.gamepad && this.gamepad.leftStick) {
  51487. var camera = this.camera;
  51488. var LSValues = this.gamepad.leftStick;
  51489. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  51490. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51491. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  51492. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  51493. var RSValues = this.gamepad.rightStick;
  51494. if (RSValues) {
  51495. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  51496. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  51497. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  51498. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  51499. }
  51500. else {
  51501. RSValues = { x: 0, y: 0 };
  51502. }
  51503. if (!camera.rotationQuaternion) {
  51504. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  51505. }
  51506. else {
  51507. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  51508. }
  51509. var speed = camera._computeLocalCameraSpeed() * 50.0;
  51510. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  51511. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  51512. camera.cameraDirection.addInPlace(this._deltaTransform);
  51513. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  51514. camera.cameraRotation.addInPlace(this._vector2);
  51515. }
  51516. };
  51517. FreeCameraGamepadInput.prototype.getClassName = function () {
  51518. return "FreeCameraGamepadInput";
  51519. };
  51520. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  51521. return "gamepad";
  51522. };
  51523. __decorate([
  51524. BABYLON.serialize()
  51525. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  51526. __decorate([
  51527. BABYLON.serialize()
  51528. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51529. return FreeCameraGamepadInput;
  51530. }());
  51531. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  51532. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  51533. })(BABYLON || (BABYLON = {}));
  51534. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  51535. var BABYLON;
  51536. (function (BABYLON) {
  51537. var ArcRotateCameraGamepadInput = (function () {
  51538. function ArcRotateCameraGamepadInput() {
  51539. this.gamepadRotationSensibility = 80;
  51540. this.gamepadMoveSensibility = 40;
  51541. }
  51542. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  51543. var _this = this;
  51544. var manager = this.camera.getScene().gamepadManager;
  51545. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  51546. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  51547. // prioritize XBOX gamepads.
  51548. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  51549. _this.gamepad = gamepad;
  51550. }
  51551. }
  51552. });
  51553. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  51554. if (_this.gamepad === gamepad) {
  51555. _this.gamepad = null;
  51556. }
  51557. });
  51558. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  51559. };
  51560. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  51561. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  51562. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  51563. this.gamepad = null;
  51564. };
  51565. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  51566. if (this.gamepad) {
  51567. var camera = this.camera;
  51568. var RSValues = this.gamepad.rightStick;
  51569. if (RSValues) {
  51570. if (RSValues.x != 0) {
  51571. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  51572. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  51573. camera.inertialAlphaOffset += normalizedRX;
  51574. }
  51575. }
  51576. if (RSValues.y != 0) {
  51577. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  51578. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  51579. camera.inertialBetaOffset += normalizedRY;
  51580. }
  51581. }
  51582. }
  51583. var LSValues = this.gamepad.leftStick;
  51584. if (LSValues && LSValues.y != 0) {
  51585. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51586. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  51587. this.camera.inertialRadiusOffset -= normalizedLY;
  51588. }
  51589. }
  51590. }
  51591. };
  51592. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  51593. return "ArcRotateCameraGamepadInput";
  51594. };
  51595. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  51596. return "gamepad";
  51597. };
  51598. __decorate([
  51599. BABYLON.serialize()
  51600. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  51601. __decorate([
  51602. BABYLON.serialize()
  51603. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51604. return ArcRotateCameraGamepadInput;
  51605. }());
  51606. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  51607. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  51608. })(BABYLON || (BABYLON = {}));
  51609. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  51610. var BABYLON;
  51611. (function (BABYLON) {
  51612. var GamepadManager = (function () {
  51613. function GamepadManager() {
  51614. var _this = this;
  51615. this._babylonGamepads = [];
  51616. this._oneGamepadConnected = false;
  51617. this._isMonitoring = false;
  51618. this._gamepadEventSupported = 'GamepadEvent' in window;
  51619. this._gamepadSupport = (navigator.getGamepads ||
  51620. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  51621. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  51622. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  51623. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  51624. for (var i in _this._babylonGamepads) {
  51625. var gamepad = _this._babylonGamepads[i];
  51626. if (gamepad && gamepad._isConnected) {
  51627. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  51628. }
  51629. }
  51630. });
  51631. this._onGamepadConnectedEvent = function (evt) {
  51632. var gamepad = evt.gamepad;
  51633. if (gamepad.index in _this._babylonGamepads) {
  51634. if (_this._babylonGamepads[gamepad.index].isConnected) {
  51635. return;
  51636. }
  51637. }
  51638. var newGamepad;
  51639. if (_this._babylonGamepads[gamepad.index]) {
  51640. newGamepad = _this._babylonGamepads[gamepad.index];
  51641. newGamepad.browserGamepad = gamepad;
  51642. newGamepad._isConnected = true;
  51643. }
  51644. else {
  51645. newGamepad = _this._addNewGamepad(gamepad);
  51646. }
  51647. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51648. _this._startMonitoringGamepads();
  51649. };
  51650. this._onGamepadDisconnectedEvent = function (evt) {
  51651. var gamepad = evt.gamepad;
  51652. // Remove the gamepad from the list of gamepads to monitor.
  51653. for (var i in _this._babylonGamepads) {
  51654. if (_this._babylonGamepads[i].index === gamepad.index) {
  51655. var disconnectedGamepad = _this._babylonGamepads[i];
  51656. disconnectedGamepad._isConnected = false;
  51657. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  51658. break;
  51659. }
  51660. }
  51661. };
  51662. if (this._gamepadSupport) {
  51663. //first add already-connected gamepads
  51664. this._updateGamepadObjects();
  51665. if (this._babylonGamepads.length) {
  51666. this._startMonitoringGamepads();
  51667. }
  51668. // Checking if the gamepad connected event is supported (like in Firefox)
  51669. if (this._gamepadEventSupported) {
  51670. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51671. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  51672. }
  51673. else {
  51674. this._startMonitoringGamepads();
  51675. }
  51676. }
  51677. }
  51678. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  51679. get: function () {
  51680. return this._babylonGamepads;
  51681. },
  51682. enumerable: true,
  51683. configurable: true
  51684. });
  51685. GamepadManager.prototype.getGamepadByType = function (type) {
  51686. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  51687. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  51688. var gamepad = _a[_i];
  51689. if (gamepad && gamepad.type === type) {
  51690. return gamepad;
  51691. }
  51692. }
  51693. return null;
  51694. };
  51695. GamepadManager.prototype.dispose = function () {
  51696. if (this._gamepadEventSupported) {
  51697. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  51698. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  51699. this._onGamepadConnectedEvent = null;
  51700. this._onGamepadDisconnectedEvent = null;
  51701. }
  51702. this._babylonGamepads.forEach(function (gamepad) {
  51703. gamepad.dispose();
  51704. });
  51705. this.onGamepadConnectedObservable.clear();
  51706. this.onGamepadDisconnectedObservable.clear();
  51707. this._oneGamepadConnected = false;
  51708. this._stopMonitoringGamepads();
  51709. this._babylonGamepads = [];
  51710. };
  51711. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  51712. if (!this._oneGamepadConnected) {
  51713. this._oneGamepadConnected = true;
  51714. }
  51715. var newGamepad;
  51716. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  51717. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  51718. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  51719. }
  51720. else if (gamepad.pose) {
  51721. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  51722. }
  51723. else {
  51724. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  51725. }
  51726. this._babylonGamepads[newGamepad.index] = newGamepad;
  51727. return newGamepad;
  51728. };
  51729. GamepadManager.prototype._startMonitoringGamepads = function () {
  51730. if (!this._isMonitoring) {
  51731. this._isMonitoring = true;
  51732. this._checkGamepadsStatus();
  51733. }
  51734. };
  51735. GamepadManager.prototype._stopMonitoringGamepads = function () {
  51736. this._isMonitoring = false;
  51737. };
  51738. GamepadManager.prototype._checkGamepadsStatus = function () {
  51739. var _this = this;
  51740. // Hack to be compatible Chrome
  51741. this._updateGamepadObjects();
  51742. for (var i in this._babylonGamepads) {
  51743. var gamepad = this._babylonGamepads[i];
  51744. if (!gamepad || !gamepad.isConnected) {
  51745. continue;
  51746. }
  51747. gamepad.update();
  51748. }
  51749. if (this._isMonitoring) {
  51750. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  51751. }
  51752. };
  51753. // This function is called only on Chrome, which does not properly support
  51754. // connection/disconnection events and forces you to recopy again the gamepad object
  51755. GamepadManager.prototype._updateGamepadObjects = function () {
  51756. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51757. for (var i = 0; i < gamepads.length; i++) {
  51758. if (gamepads[i]) {
  51759. if (!this._babylonGamepads[gamepads[i].index]) {
  51760. var newGamepad = this._addNewGamepad(gamepads[i]);
  51761. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51762. }
  51763. else {
  51764. // Forced to copy again this object for Chrome for unknown reason
  51765. this._babylonGamepads[i].browserGamepad = gamepads[i];
  51766. if (!this._babylonGamepads[i].isConnected) {
  51767. this._babylonGamepads[i]._isConnected = true;
  51768. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  51769. }
  51770. }
  51771. }
  51772. }
  51773. };
  51774. return GamepadManager;
  51775. }());
  51776. BABYLON.GamepadManager = GamepadManager;
  51777. })(BABYLON || (BABYLON = {}));
  51778. //# sourceMappingURL=babylon.gamepadManager.js.map
  51779. var BABYLON;
  51780. (function (BABYLON) {
  51781. var StickValues = (function () {
  51782. function StickValues(x, y) {
  51783. this.x = x;
  51784. this.y = y;
  51785. }
  51786. return StickValues;
  51787. }());
  51788. BABYLON.StickValues = StickValues;
  51789. var Gamepad = (function () {
  51790. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51791. if (leftStickX === void 0) { leftStickX = 0; }
  51792. if (leftStickY === void 0) { leftStickY = 1; }
  51793. if (rightStickX === void 0) { rightStickX = 2; }
  51794. if (rightStickY === void 0) { rightStickY = 3; }
  51795. this.id = id;
  51796. this.index = index;
  51797. this.browserGamepad = browserGamepad;
  51798. this._isConnected = true;
  51799. this.type = Gamepad.GAMEPAD;
  51800. this._leftStickAxisX = leftStickX;
  51801. this._leftStickAxisY = leftStickY;
  51802. this._rightStickAxisX = rightStickX;
  51803. this._rightStickAxisY = rightStickY;
  51804. if (this.browserGamepad.axes.length >= 2) {
  51805. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51806. }
  51807. if (this.browserGamepad.axes.length >= 4) {
  51808. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51809. }
  51810. }
  51811. Object.defineProperty(Gamepad.prototype, "isConnected", {
  51812. get: function () {
  51813. return this._isConnected;
  51814. },
  51815. enumerable: true,
  51816. configurable: true
  51817. });
  51818. Gamepad.prototype.onleftstickchanged = function (callback) {
  51819. this._onleftstickchanged = callback;
  51820. };
  51821. Gamepad.prototype.onrightstickchanged = function (callback) {
  51822. this._onrightstickchanged = callback;
  51823. };
  51824. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51825. get: function () {
  51826. return this._leftStick;
  51827. },
  51828. set: function (newValues) {
  51829. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51830. this._onleftstickchanged(newValues);
  51831. }
  51832. this._leftStick = newValues;
  51833. },
  51834. enumerable: true,
  51835. configurable: true
  51836. });
  51837. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51838. get: function () {
  51839. return this._rightStick;
  51840. },
  51841. set: function (newValues) {
  51842. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51843. this._onrightstickchanged(newValues);
  51844. }
  51845. this._rightStick = newValues;
  51846. },
  51847. enumerable: true,
  51848. configurable: true
  51849. });
  51850. Gamepad.prototype.update = function () {
  51851. if (this._leftStick) {
  51852. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51853. }
  51854. if (this._rightStick) {
  51855. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51856. }
  51857. };
  51858. Gamepad.prototype.dispose = function () {
  51859. };
  51860. Gamepad.GAMEPAD = 0;
  51861. Gamepad.GENERIC = 1;
  51862. Gamepad.XBOX = 2;
  51863. Gamepad.POSE_ENABLED = 3;
  51864. return Gamepad;
  51865. }());
  51866. BABYLON.Gamepad = Gamepad;
  51867. var GenericPad = (function (_super) {
  51868. __extends(GenericPad, _super);
  51869. function GenericPad(id, index, browserGamepad) {
  51870. var _this = _super.call(this, id, index, browserGamepad) || this;
  51871. _this.onButtonDownObservable = new BABYLON.Observable();
  51872. _this.onButtonUpObservable = new BABYLON.Observable();
  51873. _this.type = Gamepad.GENERIC;
  51874. _this._buttons = new Array(browserGamepad.buttons.length);
  51875. return _this;
  51876. }
  51877. GenericPad.prototype.onbuttondown = function (callback) {
  51878. this._onbuttondown = callback;
  51879. };
  51880. GenericPad.prototype.onbuttonup = function (callback) {
  51881. this._onbuttonup = callback;
  51882. };
  51883. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51884. if (newValue !== currentValue) {
  51885. if (newValue === 1) {
  51886. if (this._onbuttondown) {
  51887. this._onbuttondown(buttonIndex);
  51888. }
  51889. this.onButtonDownObservable.notifyObservers(buttonIndex);
  51890. }
  51891. if (newValue === 0) {
  51892. if (this._onbuttonup) {
  51893. this._onbuttonup(buttonIndex);
  51894. }
  51895. this.onButtonUpObservable.notifyObservers(buttonIndex);
  51896. }
  51897. }
  51898. return newValue;
  51899. };
  51900. GenericPad.prototype.update = function () {
  51901. _super.prototype.update.call(this);
  51902. for (var index = 0; index < this._buttons.length; index++) {
  51903. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  51904. }
  51905. };
  51906. return GenericPad;
  51907. }(Gamepad));
  51908. BABYLON.GenericPad = GenericPad;
  51909. })(BABYLON || (BABYLON = {}));
  51910. //# sourceMappingURL=babylon.gamepad.js.map
  51911. var BABYLON;
  51912. (function (BABYLON) {
  51913. var Xbox360Button;
  51914. (function (Xbox360Button) {
  51915. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51916. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51917. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51918. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51919. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51920. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51921. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51922. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51923. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51924. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51925. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51926. var Xbox360Dpad;
  51927. (function (Xbox360Dpad) {
  51928. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51929. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51930. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51931. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51932. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51933. var Xbox360Pad = (function (_super) {
  51934. __extends(Xbox360Pad, _super);
  51935. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51936. if (xboxOne === void 0) { xboxOne = false; }
  51937. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  51938. _this._leftTrigger = 0;
  51939. _this._rightTrigger = 0;
  51940. _this.onButtonDownObservable = new BABYLON.Observable();
  51941. _this.onButtonUpObservable = new BABYLON.Observable();
  51942. _this.onPadDownObservable = new BABYLON.Observable();
  51943. _this.onPadUpObservable = new BABYLON.Observable();
  51944. _this._buttonA = 0;
  51945. _this._buttonB = 0;
  51946. _this._buttonX = 0;
  51947. _this._buttonY = 0;
  51948. _this._buttonBack = 0;
  51949. _this._buttonStart = 0;
  51950. _this._buttonLB = 0;
  51951. _this._buttonRB = 0;
  51952. _this._buttonLeftStick = 0;
  51953. _this._buttonRightStick = 0;
  51954. _this._dPadUp = 0;
  51955. _this._dPadDown = 0;
  51956. _this._dPadLeft = 0;
  51957. _this._dPadRight = 0;
  51958. _this._isXboxOnePad = false;
  51959. _this.type = BABYLON.Gamepad.XBOX;
  51960. _this._isXboxOnePad = xboxOne;
  51961. return _this;
  51962. }
  51963. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51964. this._onlefttriggerchanged = callback;
  51965. };
  51966. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51967. this._onrighttriggerchanged = callback;
  51968. };
  51969. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51970. get: function () {
  51971. return this._leftTrigger;
  51972. },
  51973. set: function (newValue) {
  51974. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51975. this._onlefttriggerchanged(newValue);
  51976. }
  51977. this._leftTrigger = newValue;
  51978. },
  51979. enumerable: true,
  51980. configurable: true
  51981. });
  51982. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51983. get: function () {
  51984. return this._rightTrigger;
  51985. },
  51986. set: function (newValue) {
  51987. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51988. this._onrighttriggerchanged(newValue);
  51989. }
  51990. this._rightTrigger = newValue;
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51996. this._onbuttondown = callback;
  51997. };
  51998. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51999. this._onbuttonup = callback;
  52000. };
  52001. Xbox360Pad.prototype.ondpaddown = function (callback) {
  52002. this._ondpaddown = callback;
  52003. };
  52004. Xbox360Pad.prototype.ondpadup = function (callback) {
  52005. this._ondpadup = callback;
  52006. };
  52007. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  52008. if (newValue !== currentValue) {
  52009. if (newValue === 1) {
  52010. if (this._onbuttondown) {
  52011. this._onbuttondown(buttonType);
  52012. }
  52013. this.onButtonDownObservable.notifyObservers(buttonType);
  52014. }
  52015. if (newValue === 0) {
  52016. if (this._onbuttonup) {
  52017. this._onbuttonup(buttonType);
  52018. }
  52019. this.onButtonUpObservable.notifyObservers(buttonType);
  52020. }
  52021. }
  52022. return newValue;
  52023. };
  52024. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  52025. if (newValue !== currentValue) {
  52026. if (newValue === 1) {
  52027. if (this._ondpaddown) {
  52028. this._ondpaddown(buttonType);
  52029. }
  52030. this.onPadDownObservable.notifyObservers(buttonType);
  52031. }
  52032. if (newValue === 0) {
  52033. if (this._ondpadup) {
  52034. this._ondpadup(buttonType);
  52035. }
  52036. this.onPadUpObservable.notifyObservers(buttonType);
  52037. }
  52038. }
  52039. return newValue;
  52040. };
  52041. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  52042. get: function () {
  52043. return this._buttonA;
  52044. },
  52045. set: function (value) {
  52046. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  52047. },
  52048. enumerable: true,
  52049. configurable: true
  52050. });
  52051. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  52052. get: function () {
  52053. return this._buttonB;
  52054. },
  52055. set: function (value) {
  52056. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  52057. },
  52058. enumerable: true,
  52059. configurable: true
  52060. });
  52061. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  52062. get: function () {
  52063. return this._buttonX;
  52064. },
  52065. set: function (value) {
  52066. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  52067. },
  52068. enumerable: true,
  52069. configurable: true
  52070. });
  52071. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  52072. get: function () {
  52073. return this._buttonY;
  52074. },
  52075. set: function (value) {
  52076. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  52077. },
  52078. enumerable: true,
  52079. configurable: true
  52080. });
  52081. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  52082. get: function () {
  52083. return this._buttonStart;
  52084. },
  52085. set: function (value) {
  52086. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  52087. },
  52088. enumerable: true,
  52089. configurable: true
  52090. });
  52091. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  52092. get: function () {
  52093. return this._buttonBack;
  52094. },
  52095. set: function (value) {
  52096. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  52097. },
  52098. enumerable: true,
  52099. configurable: true
  52100. });
  52101. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  52102. get: function () {
  52103. return this._buttonLB;
  52104. },
  52105. set: function (value) {
  52106. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  52107. },
  52108. enumerable: true,
  52109. configurable: true
  52110. });
  52111. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  52112. get: function () {
  52113. return this._buttonRB;
  52114. },
  52115. set: function (value) {
  52116. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  52117. },
  52118. enumerable: true,
  52119. configurable: true
  52120. });
  52121. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  52122. get: function () {
  52123. return this._buttonLeftStick;
  52124. },
  52125. set: function (value) {
  52126. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  52127. },
  52128. enumerable: true,
  52129. configurable: true
  52130. });
  52131. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  52132. get: function () {
  52133. return this._buttonRightStick;
  52134. },
  52135. set: function (value) {
  52136. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  52137. },
  52138. enumerable: true,
  52139. configurable: true
  52140. });
  52141. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  52142. get: function () {
  52143. return this._dPadUp;
  52144. },
  52145. set: function (value) {
  52146. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  52147. },
  52148. enumerable: true,
  52149. configurable: true
  52150. });
  52151. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  52152. get: function () {
  52153. return this._dPadDown;
  52154. },
  52155. set: function (value) {
  52156. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  52157. },
  52158. enumerable: true,
  52159. configurable: true
  52160. });
  52161. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  52162. get: function () {
  52163. return this._dPadLeft;
  52164. },
  52165. set: function (value) {
  52166. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  52167. },
  52168. enumerable: true,
  52169. configurable: true
  52170. });
  52171. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  52172. get: function () {
  52173. return this._dPadRight;
  52174. },
  52175. set: function (value) {
  52176. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  52177. },
  52178. enumerable: true,
  52179. configurable: true
  52180. });
  52181. Xbox360Pad.prototype.update = function () {
  52182. _super.prototype.update.call(this);
  52183. if (this._isXboxOnePad) {
  52184. this.buttonA = this.browserGamepad.buttons[0].value;
  52185. this.buttonB = this.browserGamepad.buttons[1].value;
  52186. this.buttonX = this.browserGamepad.buttons[2].value;
  52187. this.buttonY = this.browserGamepad.buttons[3].value;
  52188. this.buttonLB = this.browserGamepad.buttons[4].value;
  52189. this.buttonRB = this.browserGamepad.buttons[5].value;
  52190. this.leftTrigger = this.browserGamepad.axes[2];
  52191. this.rightTrigger = this.browserGamepad.axes[5];
  52192. this.buttonBack = this.browserGamepad.buttons[9].value;
  52193. this.buttonStart = this.browserGamepad.buttons[8].value;
  52194. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  52195. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  52196. this.dPadUp = this.browserGamepad.buttons[11].value;
  52197. this.dPadDown = this.browserGamepad.buttons[12].value;
  52198. this.dPadLeft = this.browserGamepad.buttons[13].value;
  52199. this.dPadRight = this.browserGamepad.buttons[14].value;
  52200. }
  52201. else {
  52202. this.buttonA = this.browserGamepad.buttons[0].value;
  52203. this.buttonB = this.browserGamepad.buttons[1].value;
  52204. this.buttonX = this.browserGamepad.buttons[2].value;
  52205. this.buttonY = this.browserGamepad.buttons[3].value;
  52206. this.buttonLB = this.browserGamepad.buttons[4].value;
  52207. this.buttonRB = this.browserGamepad.buttons[5].value;
  52208. this.leftTrigger = this.browserGamepad.buttons[6].value;
  52209. this.rightTrigger = this.browserGamepad.buttons[7].value;
  52210. this.buttonBack = this.browserGamepad.buttons[8].value;
  52211. this.buttonStart = this.browserGamepad.buttons[9].value;
  52212. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  52213. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  52214. this.dPadUp = this.browserGamepad.buttons[12].value;
  52215. this.dPadDown = this.browserGamepad.buttons[13].value;
  52216. this.dPadLeft = this.browserGamepad.buttons[14].value;
  52217. this.dPadRight = this.browserGamepad.buttons[15].value;
  52218. }
  52219. };
  52220. return Xbox360Pad;
  52221. }(BABYLON.Gamepad));
  52222. BABYLON.Xbox360Pad = Xbox360Pad;
  52223. })(BABYLON || (BABYLON = {}));
  52224. //# sourceMappingURL=babylon.xboxGamepad.js.map
  52225. var BABYLON;
  52226. (function (BABYLON) {
  52227. var PoseEnabledControllerType;
  52228. (function (PoseEnabledControllerType) {
  52229. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  52230. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  52231. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  52232. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  52233. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  52234. var PoseEnabledControllerHelper = (function () {
  52235. function PoseEnabledControllerHelper() {
  52236. }
  52237. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  52238. // Oculus Touch
  52239. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  52240. return new BABYLON.OculusTouchController(vrGamepad);
  52241. }
  52242. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  52243. return new BABYLON.WindowsMotionController(vrGamepad);
  52244. }
  52245. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  52246. return new BABYLON.ViveController(vrGamepad);
  52247. }
  52248. else {
  52249. return new BABYLON.GenericController(vrGamepad);
  52250. }
  52251. };
  52252. return PoseEnabledControllerHelper;
  52253. }());
  52254. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  52255. var PoseEnabledController = (function (_super) {
  52256. __extends(PoseEnabledController, _super);
  52257. function PoseEnabledController(browserGamepad) {
  52258. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  52259. _this.deviceScaleFactor = 1;
  52260. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  52261. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  52262. _this.controllerType = PoseEnabledControllerType.GENERIC;
  52263. _this.position = BABYLON.Vector3.Zero();
  52264. _this.rotationQuaternion = new BABYLON.Quaternion();
  52265. _this.devicePosition = BABYLON.Vector3.Zero();
  52266. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  52267. _this._calculatedPosition = BABYLON.Vector3.Zero();
  52268. _this._calculatedRotation = new BABYLON.Quaternion();
  52269. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  52270. return _this;
  52271. }
  52272. PoseEnabledController.prototype.update = function () {
  52273. _super.prototype.update.call(this);
  52274. var pose = this.browserGamepad.pose;
  52275. this.updateFromDevice(pose);
  52276. if (this._mesh) {
  52277. this._mesh.position.copyFrom(this._calculatedPosition);
  52278. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  52279. }
  52280. };
  52281. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  52282. if (poseData) {
  52283. this.rawPose = poseData;
  52284. if (poseData.position) {
  52285. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  52286. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  52287. this.devicePosition.z *= -1;
  52288. }
  52289. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  52290. this._calculatedPosition.addInPlace(this.position);
  52291. }
  52292. if (poseData.orientation) {
  52293. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  52294. if (this._mesh) {
  52295. if (this._mesh.getScene().useRightHandedSystem) {
  52296. this.deviceRotationQuaternion.z *= -1;
  52297. this.deviceRotationQuaternion.w *= -1;
  52298. }
  52299. else {
  52300. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  52301. }
  52302. }
  52303. // if the camera is set, rotate to the camera's rotation
  52304. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  52305. }
  52306. }
  52307. };
  52308. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  52309. if (this._mesh) {
  52310. this._mesh.parent = undefined;
  52311. }
  52312. this._mesh = mesh;
  52313. if (this._poseControlledCamera) {
  52314. this._mesh.parent = this._poseControlledCamera;
  52315. }
  52316. if (!this._mesh.rotationQuaternion) {
  52317. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  52318. }
  52319. };
  52320. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  52321. this._poseControlledCamera = camera;
  52322. if (this._mesh) {
  52323. this._mesh.parent = this._poseControlledCamera;
  52324. }
  52325. };
  52326. PoseEnabledController.prototype.dispose = function () {
  52327. if (this._mesh) {
  52328. this._mesh.dispose();
  52329. }
  52330. this._mesh = undefined;
  52331. _super.prototype.dispose.call(this);
  52332. };
  52333. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  52334. get: function () {
  52335. return this._mesh;
  52336. },
  52337. enumerable: true,
  52338. configurable: true
  52339. });
  52340. PoseEnabledController.prototype.getForwardRay = function (length) {
  52341. if (length === void 0) { length = 100; }
  52342. if (!this.mesh) {
  52343. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  52344. }
  52345. var m = this.mesh.getWorldMatrix();
  52346. var origin = m.getTranslation();
  52347. var forward = new BABYLON.Vector3(0, 0, -1);
  52348. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  52349. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  52350. return new BABYLON.Ray(origin, direction, length);
  52351. };
  52352. return PoseEnabledController;
  52353. }(BABYLON.Gamepad));
  52354. BABYLON.PoseEnabledController = PoseEnabledController;
  52355. })(BABYLON || (BABYLON = {}));
  52356. //# sourceMappingURL=babylon.poseEnabledController.js.map
  52357. var BABYLON;
  52358. (function (BABYLON) {
  52359. var WebVRController = (function (_super) {
  52360. __extends(WebVRController, _super);
  52361. function WebVRController(vrGamepad) {
  52362. var _this = _super.call(this, vrGamepad) || this;
  52363. // Observables
  52364. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  52365. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  52366. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  52367. _this.onPadStateChangedObservable = new BABYLON.Observable();
  52368. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  52369. _this.pad = { x: 0, y: 0 };
  52370. // avoid GC, store state in a tmp object
  52371. _this._changes = {
  52372. pressChanged: false,
  52373. touchChanged: false,
  52374. valueChanged: false,
  52375. changed: false
  52376. };
  52377. _this._buttons = new Array(vrGamepad.buttons.length);
  52378. _this.hand = vrGamepad.hand;
  52379. return _this;
  52380. }
  52381. WebVRController.prototype.onButtonStateChange = function (callback) {
  52382. this._onButtonStateChange = callback;
  52383. };
  52384. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  52385. get: function () {
  52386. return this._defaultModel;
  52387. },
  52388. enumerable: true,
  52389. configurable: true
  52390. });
  52391. WebVRController.prototype.update = function () {
  52392. _super.prototype.update.call(this);
  52393. for (var index = 0; index < this._buttons.length; index++) {
  52394. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  52395. }
  52396. ;
  52397. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  52398. this.pad.x = this.leftStick.x;
  52399. this.pad.y = this.leftStick.y;
  52400. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  52401. }
  52402. };
  52403. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  52404. if (!newState) {
  52405. newState = {
  52406. pressed: false,
  52407. touched: false,
  52408. value: 0
  52409. };
  52410. }
  52411. if (!currentState) {
  52412. this._buttons[buttonIndex] = {
  52413. pressed: newState.pressed,
  52414. touched: newState.touched,
  52415. value: newState.value
  52416. };
  52417. return;
  52418. }
  52419. this._checkChanges(newState, currentState);
  52420. if (this._changes.changed) {
  52421. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  52422. this.handleButtonChange(buttonIndex, newState, this._changes);
  52423. }
  52424. this._buttons[buttonIndex].pressed = newState.pressed;
  52425. this._buttons[buttonIndex].touched = newState.touched;
  52426. // oculus triggers are never 0, thou not touched.
  52427. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  52428. };
  52429. WebVRController.prototype._checkChanges = function (newState, currentState) {
  52430. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  52431. this._changes.touchChanged = newState.touched !== currentState.touched;
  52432. this._changes.valueChanged = newState.value !== currentState.value;
  52433. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  52434. return this._changes;
  52435. };
  52436. WebVRController.prototype.dispose = function () {
  52437. _super.prototype.dispose.call(this);
  52438. this.onTriggerStateChangedObservable.clear();
  52439. this.onMainButtonStateChangedObservable.clear();
  52440. this.onSecondaryButtonStateChangedObservable.clear();
  52441. this.onPadStateChangedObservable.clear();
  52442. this.onPadValuesChangedObservable.clear();
  52443. };
  52444. return WebVRController;
  52445. }(BABYLON.PoseEnabledController));
  52446. BABYLON.WebVRController = WebVRController;
  52447. })(BABYLON || (BABYLON = {}));
  52448. //# sourceMappingURL=babylon.webVRController.js.map
  52449. var BABYLON;
  52450. (function (BABYLON) {
  52451. var OculusTouchController = (function (_super) {
  52452. __extends(OculusTouchController, _super);
  52453. function OculusTouchController(vrGamepad) {
  52454. var _this = _super.call(this, vrGamepad) || this;
  52455. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  52456. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  52457. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  52458. return _this;
  52459. }
  52460. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52461. var _this = this;
  52462. var meshName;
  52463. // Hand
  52464. if (this.hand === 'left') {
  52465. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  52466. }
  52467. else {
  52468. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  52469. }
  52470. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  52471. /*
  52472. Parent Mesh name: oculus_touch_left
  52473. - body
  52474. - trigger
  52475. - thumbstick
  52476. - grip
  52477. - button_y
  52478. - button_x
  52479. - button_enter
  52480. */
  52481. _this._defaultModel = newMeshes[1];
  52482. if (meshLoaded) {
  52483. meshLoaded(_this._defaultModel);
  52484. }
  52485. _this.attachToMesh(_this._defaultModel);
  52486. });
  52487. };
  52488. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  52489. // helper getters for left and right hand.
  52490. get: function () {
  52491. if (this.hand === 'right') {
  52492. return this.onMainButtonStateChangedObservable;
  52493. }
  52494. else {
  52495. throw new Error('No A button on left hand');
  52496. }
  52497. },
  52498. enumerable: true,
  52499. configurable: true
  52500. });
  52501. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  52502. get: function () {
  52503. if (this.hand === 'right') {
  52504. return this.onSecondaryButtonStateChangedObservable;
  52505. }
  52506. else {
  52507. throw new Error('No B button on left hand');
  52508. }
  52509. },
  52510. enumerable: true,
  52511. configurable: true
  52512. });
  52513. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  52514. get: function () {
  52515. if (this.hand === 'left') {
  52516. return this.onMainButtonStateChangedObservable;
  52517. }
  52518. else {
  52519. throw new Error('No X button on right hand');
  52520. }
  52521. },
  52522. enumerable: true,
  52523. configurable: true
  52524. });
  52525. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  52526. get: function () {
  52527. if (this.hand === 'left') {
  52528. return this.onSecondaryButtonStateChangedObservable;
  52529. }
  52530. else {
  52531. throw new Error('No Y button on right hand');
  52532. }
  52533. },
  52534. enumerable: true,
  52535. configurable: true
  52536. });
  52537. /*
  52538. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  52539. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  52540. 2) secondary trigger (same)
  52541. 3) A (right) X (left), touch, pressed = value
  52542. 4) B / Y
  52543. 5) thumb rest
  52544. */
  52545. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52546. var notifyObject = state; //{ state: state, changes: changes };
  52547. var triggerDirection = this.hand === 'right' ? -1 : 1;
  52548. switch (buttonIdx) {
  52549. case 0:
  52550. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52551. return;
  52552. case 1:// index trigger
  52553. if (this._defaultModel) {
  52554. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  52555. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  52556. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  52557. }
  52558. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52559. return;
  52560. case 2:// secondary trigger
  52561. if (this._defaultModel) {
  52562. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  52563. }
  52564. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  52565. return;
  52566. case 3:
  52567. if (this._defaultModel) {
  52568. if (notifyObject.pressed) {
  52569. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  52570. }
  52571. else {
  52572. (this._defaultModel.getChildren()[1]).position.y = 0;
  52573. }
  52574. }
  52575. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52576. return;
  52577. case 4:
  52578. if (this._defaultModel) {
  52579. if (notifyObject.pressed) {
  52580. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52581. }
  52582. else {
  52583. (this._defaultModel.getChildren()[2]).position.y = 0;
  52584. }
  52585. }
  52586. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52587. return;
  52588. case 5:
  52589. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  52590. return;
  52591. }
  52592. };
  52593. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  52594. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  52595. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  52596. return OculusTouchController;
  52597. }(BABYLON.WebVRController));
  52598. BABYLON.OculusTouchController = OculusTouchController;
  52599. })(BABYLON || (BABYLON = {}));
  52600. //# sourceMappingURL=babylon.oculusTouchController.js.map
  52601. var BABYLON;
  52602. (function (BABYLON) {
  52603. var ViveController = (function (_super) {
  52604. __extends(ViveController, _super);
  52605. function ViveController(vrGamepad) {
  52606. var _this = _super.call(this, vrGamepad) || this;
  52607. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  52608. return _this;
  52609. }
  52610. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52611. var _this = this;
  52612. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  52613. /*
  52614. Parent Mesh name: ViveWand
  52615. - body
  52616. - r_gripper
  52617. - l_gripper
  52618. - menu_button
  52619. - system_button
  52620. - trackpad
  52621. - trigger
  52622. - LED
  52623. */
  52624. _this._defaultModel = newMeshes[1];
  52625. if (meshLoaded) {
  52626. meshLoaded(_this._defaultModel);
  52627. }
  52628. _this.attachToMesh(_this._defaultModel);
  52629. });
  52630. };
  52631. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  52632. get: function () {
  52633. return this.onMainButtonStateChangedObservable;
  52634. },
  52635. enumerable: true,
  52636. configurable: true
  52637. });
  52638. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  52639. get: function () {
  52640. return this.onMainButtonStateChangedObservable;
  52641. },
  52642. enumerable: true,
  52643. configurable: true
  52644. });
  52645. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  52646. get: function () {
  52647. return this.onSecondaryButtonStateChangedObservable;
  52648. },
  52649. enumerable: true,
  52650. configurable: true
  52651. });
  52652. /**
  52653. * Vive mapping:
  52654. * 0: touchpad
  52655. * 1: trigger
  52656. * 2: left AND right buttons
  52657. * 3: menu button
  52658. */
  52659. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52660. var notifyObject = state; //{ state: state, changes: changes };
  52661. switch (buttonIdx) {
  52662. case 0:
  52663. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52664. return;
  52665. case 1:// index trigger
  52666. if (this._defaultModel) {
  52667. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  52668. }
  52669. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52670. return;
  52671. case 2:// left AND right button
  52672. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52673. return;
  52674. case 3:
  52675. if (this._defaultModel) {
  52676. if (notifyObject.pressed) {
  52677. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52678. }
  52679. else {
  52680. (this._defaultModel.getChildren()[2]).position.y = 0;
  52681. }
  52682. }
  52683. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52684. return;
  52685. }
  52686. };
  52687. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  52688. ViveController.MODEL_FILENAME = 'wand.babylon';
  52689. return ViveController;
  52690. }(BABYLON.WebVRController));
  52691. BABYLON.ViveController = ViveController;
  52692. })(BABYLON || (BABYLON = {}));
  52693. //# sourceMappingURL=babylon.viveController.js.map
  52694. var BABYLON;
  52695. (function (BABYLON) {
  52696. var GenericController = (function (_super) {
  52697. __extends(GenericController, _super);
  52698. function GenericController(vrGamepad) {
  52699. return _super.call(this, vrGamepad) || this;
  52700. }
  52701. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52702. var _this = this;
  52703. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  52704. _this._defaultModel = newMeshes[1];
  52705. if (meshLoaded) {
  52706. meshLoaded(_this._defaultModel);
  52707. }
  52708. _this.attachToMesh(_this._defaultModel);
  52709. });
  52710. };
  52711. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52712. console.log("Button id: " + buttonIdx + "state: ");
  52713. console.dir(state);
  52714. };
  52715. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  52716. GenericController.MODEL_FILENAME = 'generic.babylon';
  52717. return GenericController;
  52718. }(BABYLON.WebVRController));
  52719. BABYLON.GenericController = GenericController;
  52720. })(BABYLON || (BABYLON = {}));
  52721. //# sourceMappingURL=babylon.genericController.js.map
  52722. var BABYLON;
  52723. (function (BABYLON) {
  52724. var LoadedMeshInfo = (function () {
  52725. function LoadedMeshInfo() {
  52726. this.buttonMeshes = {};
  52727. this.axisMeshes = {};
  52728. }
  52729. return LoadedMeshInfo;
  52730. }());
  52731. var WindowsMotionController = (function (_super) {
  52732. __extends(WindowsMotionController, _super);
  52733. function WindowsMotionController(vrGamepad) {
  52734. var _this = _super.call(this, vrGamepad) || this;
  52735. _this._mapping = {
  52736. // Semantic button names
  52737. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  52738. // A mapping of the button name to glTF model node name
  52739. // that should be transformed by button value.
  52740. buttonMeshNames: {
  52741. 'trigger': 'SELECT',
  52742. 'menu': 'MENU',
  52743. 'grip': 'GRASP',
  52744. 'thumbstick': 'THUMBSTICK_PRESS',
  52745. 'trackpad': 'TOUCHPAD_PRESS'
  52746. },
  52747. // This mapping is used to translate from the Motion Controller to Babylon semantics
  52748. buttonObservableNames: {
  52749. 'trigger': 'onTriggerStateChangedObservable',
  52750. 'menu': 'onSecondaryButtonStateChangedObservable',
  52751. 'grip': 'onMainButtonStateChangedObservable',
  52752. 'thumbstick': 'onPadStateChangedObservable',
  52753. 'trackpad': 'onTrackpadChangedObservable'
  52754. },
  52755. // A mapping of the axis name to glTF model node name
  52756. // that should be transformed by axis value.
  52757. // This array mirrors the browserGamepad.axes array, such that
  52758. // the mesh corresponding to axis 0 is in this array index 0.
  52759. axisMeshNames: [
  52760. 'THUMBSTICK_X',
  52761. 'THUMBSTICK_Y',
  52762. 'TOUCHPAD_TOUCH_X',
  52763. 'TOUCHPAD_TOUCH_Y'
  52764. ],
  52765. pointingPoseMeshName: 'POINTING_POSE'
  52766. };
  52767. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  52768. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  52769. _this._loadedMeshInfo = null;
  52770. return _this;
  52771. }
  52772. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  52773. get: function () {
  52774. return this.onTriggerStateChangedObservable;
  52775. },
  52776. enumerable: true,
  52777. configurable: true
  52778. });
  52779. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  52780. get: function () {
  52781. return this.onSecondaryButtonStateChangedObservable;
  52782. },
  52783. enumerable: true,
  52784. configurable: true
  52785. });
  52786. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  52787. get: function () {
  52788. return this.onMainButtonStateChangedObservable;
  52789. },
  52790. enumerable: true,
  52791. configurable: true
  52792. });
  52793. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  52794. get: function () {
  52795. return this.onPadStateChangedObservable;
  52796. },
  52797. enumerable: true,
  52798. configurable: true
  52799. });
  52800. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  52801. get: function () {
  52802. return this.onTrackpadChangedObservable;
  52803. },
  52804. enumerable: true,
  52805. configurable: true
  52806. });
  52807. /**
  52808. * Called once per frame by the engine.
  52809. */
  52810. WindowsMotionController.prototype.update = function () {
  52811. _super.prototype.update.call(this);
  52812. // Only need to animate axes if there is a loaded mesh
  52813. if (this._loadedMeshInfo) {
  52814. if (this.browserGamepad.axes) {
  52815. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  52816. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  52817. }
  52818. }
  52819. }
  52820. };
  52821. /**
  52822. * Called once for each button that changed state since the last frame
  52823. * @param buttonIdx Which button index changed
  52824. * @param state New state of the button
  52825. * @param changes Which properties on the state changed since last frame
  52826. */
  52827. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52828. var buttonName = this._mapping.buttons[buttonIdx];
  52829. if (!buttonName) {
  52830. return;
  52831. }
  52832. // Only emit events for buttons that we know how to map from index to name
  52833. var observable = this[this._mapping.buttonObservableNames[buttonName]];
  52834. if (observable) {
  52835. observable.notifyObservers(state);
  52836. }
  52837. this.lerpButtonTransform(buttonName, state.value);
  52838. };
  52839. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  52840. // If there is no loaded mesh, there is nothing to transform.
  52841. if (!this._loadedMeshInfo) {
  52842. return;
  52843. }
  52844. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  52845. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  52846. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  52847. };
  52848. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  52849. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  52850. if (!meshInfo) {
  52851. return;
  52852. }
  52853. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  52854. var lerpValue = axisValue * 0.5 + 0.5;
  52855. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  52856. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  52857. };
  52858. /**
  52859. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  52860. * @param scene scene in which to add meshes
  52861. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  52862. */
  52863. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  52864. var _this = this;
  52865. if (forceDefault === void 0) { forceDefault = false; }
  52866. var path;
  52867. var filename;
  52868. // Checking if GLB loader is present
  52869. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  52870. // Determine the device specific folder based on the ID suffix
  52871. var device = 'default';
  52872. if (this.id && !forceDefault) {
  52873. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  52874. device = ((match && match[0]) || device);
  52875. }
  52876. // Hand
  52877. if (this.hand === 'left') {
  52878. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  52879. }
  52880. else {
  52881. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  52882. }
  52883. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  52884. }
  52885. else {
  52886. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  52887. path = BABYLON.GenericController.MODEL_BASE_URL;
  52888. filename = BABYLON.GenericController.MODEL_FILENAME;
  52889. }
  52890. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  52891. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  52892. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  52893. if (!_this._loadedMeshInfo) {
  52894. return;
  52895. }
  52896. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  52897. _this.attachToMesh(_this._defaultModel);
  52898. if (meshLoaded) {
  52899. meshLoaded(_this._defaultModel);
  52900. }
  52901. }, null, function (scene, message) {
  52902. BABYLON.Tools.Log(message);
  52903. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  52904. if (!forceDefault) {
  52905. _this.initControllerMesh(scene, meshLoaded, true);
  52906. }
  52907. });
  52908. };
  52909. /**
  52910. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  52911. * can be transformed by button presses and axes values, based on this._mapping.
  52912. *
  52913. * @param scene scene in which the meshes exist
  52914. * @param meshes list of meshes that make up the controller model to process
  52915. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  52916. */
  52917. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  52918. var loadedMeshInfo = null;
  52919. // Create a new mesh to contain the glTF hierarchy
  52920. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  52921. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  52922. var childMesh = null;
  52923. for (var i = 0; i < meshes.length; i++) {
  52924. var mesh = meshes[i];
  52925. if (!mesh.parent) {
  52926. // Exclude controller meshes from picking results
  52927. mesh.isPickable = false;
  52928. // Handle root node, attach to the new parentMesh
  52929. childMesh = mesh;
  52930. break;
  52931. }
  52932. }
  52933. if (childMesh) {
  52934. childMesh.setParent(parentMesh);
  52935. // Create our mesh info. Note that this method will always return non-null.
  52936. loadedMeshInfo = this.createMeshInfo(parentMesh);
  52937. }
  52938. else {
  52939. BABYLON.Tools.Warn('Could not find root node in model file.');
  52940. }
  52941. return loadedMeshInfo;
  52942. };
  52943. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  52944. var loadedMeshInfo = new LoadedMeshInfo();
  52945. var i;
  52946. loadedMeshInfo.rootNode = rootNode;
  52947. // Reset the caches
  52948. loadedMeshInfo.buttonMeshes = {};
  52949. loadedMeshInfo.axisMeshes = {};
  52950. // Button Meshes
  52951. for (i = 0; i < this._mapping.buttons.length; i++) {
  52952. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  52953. if (!buttonMeshName) {
  52954. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  52955. continue;
  52956. }
  52957. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  52958. if (!buttonMesh) {
  52959. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  52960. continue;
  52961. }
  52962. var buttonMeshInfo = {
  52963. index: i,
  52964. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  52965. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  52966. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  52967. };
  52968. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  52969. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  52970. }
  52971. else {
  52972. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  52973. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  52974. '(VALUE: ' + !!buttonMeshInfo.value +
  52975. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  52976. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  52977. ')');
  52978. }
  52979. }
  52980. // Axis Meshes
  52981. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  52982. var axisMeshName = this._mapping.axisMeshNames[i];
  52983. if (!axisMeshName) {
  52984. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  52985. continue;
  52986. }
  52987. var axisMesh = getChildByName(rootNode, axisMeshName);
  52988. if (!axisMesh) {
  52989. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  52990. continue;
  52991. }
  52992. var axisMeshInfo = {
  52993. index: i,
  52994. value: getImmediateChildByName(axisMesh, 'VALUE'),
  52995. min: getImmediateChildByName(axisMesh, 'MIN'),
  52996. max: getImmediateChildByName(axisMesh, 'MAX')
  52997. };
  52998. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  52999. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  53000. }
  53001. else {
  53002. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  53003. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  53004. '(VALUE: ' + !!axisMeshInfo.value +
  53005. ', MIN: ' + !!axisMeshInfo.min +
  53006. ', MAX:' + !!axisMeshInfo.max +
  53007. ')');
  53008. }
  53009. }
  53010. // Pointing Ray
  53011. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  53012. if (!loadedMeshInfo.pointingPoseNode) {
  53013. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  53014. }
  53015. return loadedMeshInfo;
  53016. // Look through all children recursively. This will return null if no mesh exists with the given name.
  53017. function getChildByName(node, name) {
  53018. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  53019. }
  53020. // Look through only immediate children. This will return null if no mesh exists with the given name.
  53021. function getImmediateChildByName(node, name) {
  53022. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  53023. }
  53024. };
  53025. WindowsMotionController.prototype.getForwardRay = function (length) {
  53026. if (length === void 0) { length = 100; }
  53027. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  53028. return _super.prototype.getForwardRay.call(this, length);
  53029. }
  53030. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  53031. var origin = m.getTranslation();
  53032. var forward = new BABYLON.Vector3(0, 0, -1);
  53033. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  53034. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  53035. return new BABYLON.Ray(origin, direction, length);
  53036. };
  53037. WindowsMotionController.prototype.dispose = function () {
  53038. _super.prototype.dispose.call(this);
  53039. this.onTrackpadChangedObservable.clear();
  53040. };
  53041. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  53042. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  53043. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  53044. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  53045. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  53046. return WindowsMotionController;
  53047. }(BABYLON.WebVRController));
  53048. BABYLON.WindowsMotionController = WindowsMotionController;
  53049. })(BABYLON || (BABYLON = {}));
  53050. //# sourceMappingURL=babylon.windowsMotionController.js.map
  53051. /// <reference path="babylon.targetCamera.ts" />
  53052. var BABYLON;
  53053. (function (BABYLON) {
  53054. var FollowCamera = (function (_super) {
  53055. __extends(FollowCamera, _super);
  53056. function FollowCamera(name, position, scene, lockedTarget) {
  53057. var _this = _super.call(this, name, position, scene) || this;
  53058. _this.radius = 12;
  53059. _this.rotationOffset = 0;
  53060. _this.heightOffset = 4;
  53061. _this.cameraAcceleration = 0.05;
  53062. _this.maxCameraSpeed = 20;
  53063. _this.lockedTarget = lockedTarget;
  53064. return _this;
  53065. }
  53066. FollowCamera.prototype.getRadians = function (degrees) {
  53067. return degrees * Math.PI / 180;
  53068. };
  53069. FollowCamera.prototype.follow = function (cameraTarget) {
  53070. if (!cameraTarget)
  53071. return;
  53072. var yRotation;
  53073. if (cameraTarget.rotationQuaternion) {
  53074. var rotMatrix = new BABYLON.Matrix();
  53075. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  53076. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  53077. }
  53078. else {
  53079. yRotation = cameraTarget.rotation.y;
  53080. }
  53081. var radians = this.getRadians(this.rotationOffset) + yRotation;
  53082. var targetPosition = cameraTarget.getAbsolutePosition();
  53083. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  53084. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  53085. var dx = targetX - this.position.x;
  53086. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  53087. var dz = (targetZ) - this.position.z;
  53088. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  53089. var vy = dy * this.cameraAcceleration;
  53090. var vz = dz * this.cameraAcceleration * 2;
  53091. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  53092. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  53093. }
  53094. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  53095. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  53096. }
  53097. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  53098. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  53099. }
  53100. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  53101. this.setTarget(targetPosition);
  53102. };
  53103. FollowCamera.prototype._checkInputs = function () {
  53104. _super.prototype._checkInputs.call(this);
  53105. this.follow(this.lockedTarget);
  53106. };
  53107. FollowCamera.prototype.getClassName = function () {
  53108. return "FollowCamera";
  53109. };
  53110. __decorate([
  53111. BABYLON.serialize()
  53112. ], FollowCamera.prototype, "radius", void 0);
  53113. __decorate([
  53114. BABYLON.serialize()
  53115. ], FollowCamera.prototype, "rotationOffset", void 0);
  53116. __decorate([
  53117. BABYLON.serialize()
  53118. ], FollowCamera.prototype, "heightOffset", void 0);
  53119. __decorate([
  53120. BABYLON.serialize()
  53121. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  53122. __decorate([
  53123. BABYLON.serialize()
  53124. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  53125. __decorate([
  53126. BABYLON.serializeAsMeshReference("lockedTargetId")
  53127. ], FollowCamera.prototype, "lockedTarget", void 0);
  53128. return FollowCamera;
  53129. }(BABYLON.TargetCamera));
  53130. BABYLON.FollowCamera = FollowCamera;
  53131. var ArcFollowCamera = (function (_super) {
  53132. __extends(ArcFollowCamera, _super);
  53133. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  53134. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  53135. _this.alpha = alpha;
  53136. _this.beta = beta;
  53137. _this.radius = radius;
  53138. _this.target = target;
  53139. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  53140. _this.follow();
  53141. return _this;
  53142. }
  53143. ArcFollowCamera.prototype.follow = function () {
  53144. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  53145. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  53146. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  53147. var targetPosition = this.target.getAbsolutePosition();
  53148. this.position = targetPosition.add(this._cartesianCoordinates);
  53149. this.setTarget(targetPosition);
  53150. };
  53151. ArcFollowCamera.prototype._checkInputs = function () {
  53152. _super.prototype._checkInputs.call(this);
  53153. this.follow();
  53154. };
  53155. ArcFollowCamera.prototype.getClassName = function () {
  53156. return "ArcFollowCamera";
  53157. };
  53158. return ArcFollowCamera;
  53159. }(BABYLON.TargetCamera));
  53160. BABYLON.ArcFollowCamera = ArcFollowCamera;
  53161. })(BABYLON || (BABYLON = {}));
  53162. //# sourceMappingURL=babylon.followCamera.js.map
  53163. /// <reference path="babylon.touchCamera.ts" />
  53164. var BABYLON;
  53165. (function (BABYLON) {
  53166. // We're mainly based on the logic defined into the FreeCamera code
  53167. var UniversalCamera = (function (_super) {
  53168. __extends(UniversalCamera, _super);
  53169. //-- end properties for backward compatibility for inputs
  53170. function UniversalCamera(name, position, scene) {
  53171. var _this = _super.call(this, name, position, scene) || this;
  53172. _this.inputs.addGamepad();
  53173. return _this;
  53174. }
  53175. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  53176. //-- Begin properties for backward compatibility for inputs
  53177. get: function () {
  53178. var gamepad = this.inputs.attached["gamepad"];
  53179. if (gamepad)
  53180. return gamepad.gamepadAngularSensibility;
  53181. },
  53182. set: function (value) {
  53183. var gamepad = this.inputs.attached["gamepad"];
  53184. if (gamepad)
  53185. gamepad.gamepadAngularSensibility = value;
  53186. },
  53187. enumerable: true,
  53188. configurable: true
  53189. });
  53190. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  53191. get: function () {
  53192. var gamepad = this.inputs.attached["gamepad"];
  53193. if (gamepad)
  53194. return gamepad.gamepadMoveSensibility;
  53195. },
  53196. set: function (value) {
  53197. var gamepad = this.inputs.attached["gamepad"];
  53198. if (gamepad)
  53199. gamepad.gamepadMoveSensibility = value;
  53200. },
  53201. enumerable: true,
  53202. configurable: true
  53203. });
  53204. UniversalCamera.prototype.getClassName = function () {
  53205. return "UniversalCamera";
  53206. };
  53207. return UniversalCamera;
  53208. }(BABYLON.TouchCamera));
  53209. BABYLON.UniversalCamera = UniversalCamera;
  53210. })(BABYLON || (BABYLON = {}));
  53211. //# sourceMappingURL=babylon.universalCamera.js.map
  53212. /// <reference path="babylon.universalCamera.ts" />
  53213. var BABYLON;
  53214. (function (BABYLON) {
  53215. // We're mainly based on the logic defined into the FreeCamera code
  53216. var GamepadCamera = (function (_super) {
  53217. __extends(GamepadCamera, _super);
  53218. //-- end properties for backward compatibility for inputs
  53219. function GamepadCamera(name, position, scene) {
  53220. return _super.call(this, name, position, scene) || this;
  53221. }
  53222. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  53223. //-- Begin properties for backward compatibility for inputs
  53224. get: function () {
  53225. var gamepad = this.inputs.attached["gamepad"];
  53226. if (gamepad)
  53227. return gamepad.gamepadAngularSensibility;
  53228. },
  53229. set: function (value) {
  53230. var gamepad = this.inputs.attached["gamepad"];
  53231. if (gamepad)
  53232. gamepad.gamepadAngularSensibility = value;
  53233. },
  53234. enumerable: true,
  53235. configurable: true
  53236. });
  53237. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  53238. get: function () {
  53239. var gamepad = this.inputs.attached["gamepad"];
  53240. if (gamepad)
  53241. return gamepad.gamepadMoveSensibility;
  53242. },
  53243. set: function (value) {
  53244. var gamepad = this.inputs.attached["gamepad"];
  53245. if (gamepad)
  53246. gamepad.gamepadMoveSensibility = value;
  53247. },
  53248. enumerable: true,
  53249. configurable: true
  53250. });
  53251. GamepadCamera.prototype.getClassName = function () {
  53252. return "GamepadCamera";
  53253. };
  53254. return GamepadCamera;
  53255. }(BABYLON.UniversalCamera));
  53256. BABYLON.GamepadCamera = GamepadCamera;
  53257. })(BABYLON || (BABYLON = {}));
  53258. //# sourceMappingURL=babylon.gamepadCamera.js.map
  53259. var BABYLON;
  53260. (function (BABYLON) {
  53261. var PostProcessRenderPipelineManager = (function () {
  53262. function PostProcessRenderPipelineManager() {
  53263. this._renderPipelines = {};
  53264. }
  53265. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  53266. this._renderPipelines[renderPipeline._name] = renderPipeline;
  53267. };
  53268. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  53269. var renderPipeline = this._renderPipelines[renderPipelineName];
  53270. if (!renderPipeline) {
  53271. return;
  53272. }
  53273. renderPipeline._attachCameras(cameras, unique);
  53274. };
  53275. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  53276. var renderPipeline = this._renderPipelines[renderPipelineName];
  53277. if (!renderPipeline) {
  53278. return;
  53279. }
  53280. renderPipeline._detachCameras(cameras);
  53281. };
  53282. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  53283. var renderPipeline = this._renderPipelines[renderPipelineName];
  53284. if (!renderPipeline) {
  53285. return;
  53286. }
  53287. renderPipeline._enableEffect(renderEffectName, cameras);
  53288. };
  53289. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  53290. var renderPipeline = this._renderPipelines[renderPipelineName];
  53291. if (!renderPipeline) {
  53292. return;
  53293. }
  53294. renderPipeline._disableEffect(renderEffectName, cameras);
  53295. };
  53296. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  53297. var renderPipeline = this._renderPipelines[renderPipelineName];
  53298. if (!renderPipeline) {
  53299. return;
  53300. }
  53301. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  53302. };
  53303. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  53304. var renderPipeline = this._renderPipelines[renderPipelineName];
  53305. if (!renderPipeline) {
  53306. return;
  53307. }
  53308. renderPipeline._disableDisplayOnlyPass(cameras);
  53309. };
  53310. PostProcessRenderPipelineManager.prototype.update = function () {
  53311. for (var renderPipelineName in this._renderPipelines) {
  53312. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  53313. var pipeline = this._renderPipelines[renderPipelineName];
  53314. if (!pipeline.isSupported) {
  53315. pipeline.dispose();
  53316. delete this._renderPipelines[renderPipelineName];
  53317. }
  53318. else {
  53319. pipeline._update();
  53320. }
  53321. }
  53322. }
  53323. };
  53324. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  53325. for (var renderPipelineName in this._renderPipelines) {
  53326. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  53327. var pipeline = this._renderPipelines[renderPipelineName];
  53328. pipeline._rebuild();
  53329. }
  53330. }
  53331. };
  53332. PostProcessRenderPipelineManager.prototype.dispose = function () {
  53333. for (var renderPipelineName in this._renderPipelines) {
  53334. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  53335. var pipeline = this._renderPipelines[renderPipelineName];
  53336. pipeline.dispose();
  53337. }
  53338. }
  53339. };
  53340. return PostProcessRenderPipelineManager;
  53341. }());
  53342. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  53343. })(BABYLON || (BABYLON = {}));
  53344. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  53345. var BABYLON;
  53346. (function (BABYLON) {
  53347. var PostProcessRenderPass = (function () {
  53348. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  53349. this._enabled = true;
  53350. this._refCount = 0;
  53351. this._name = name;
  53352. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  53353. this.setRenderList(renderList);
  53354. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  53355. this._renderTexture.onAfterRenderObservable.add(afterRender);
  53356. this._scene = scene;
  53357. this._renderList = renderList;
  53358. }
  53359. // private
  53360. PostProcessRenderPass.prototype._incRefCount = function () {
  53361. if (this._refCount === 0) {
  53362. this._scene.customRenderTargets.push(this._renderTexture);
  53363. }
  53364. return ++this._refCount;
  53365. };
  53366. PostProcessRenderPass.prototype._decRefCount = function () {
  53367. this._refCount--;
  53368. if (this._refCount <= 0) {
  53369. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  53370. }
  53371. return this._refCount;
  53372. };
  53373. PostProcessRenderPass.prototype._update = function () {
  53374. this.setRenderList(this._renderList);
  53375. };
  53376. // public
  53377. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  53378. this._renderTexture.renderList = renderList;
  53379. };
  53380. PostProcessRenderPass.prototype.getRenderTexture = function () {
  53381. return this._renderTexture;
  53382. };
  53383. return PostProcessRenderPass;
  53384. }());
  53385. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  53386. })(BABYLON || (BABYLON = {}));
  53387. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  53388. var BABYLON;
  53389. (function (BABYLON) {
  53390. var PostProcessRenderEffect = (function () {
  53391. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  53392. this._engine = engine;
  53393. this._name = name;
  53394. this._singleInstance = singleInstance || true;
  53395. this._getPostProcess = getPostProcess;
  53396. this._cameras = [];
  53397. this._indicesForCamera = [];
  53398. this._postProcesses = {};
  53399. this._renderPasses = {};
  53400. this._renderEffectAsPasses = {};
  53401. }
  53402. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  53403. get: function () {
  53404. for (var index in this._postProcesses) {
  53405. if (!this._postProcesses[index].isSupported) {
  53406. return false;
  53407. }
  53408. }
  53409. return true;
  53410. },
  53411. enumerable: true,
  53412. configurable: true
  53413. });
  53414. PostProcessRenderEffect.prototype._update = function () {
  53415. for (var renderPassName in this._renderPasses) {
  53416. this._renderPasses[renderPassName]._update();
  53417. }
  53418. };
  53419. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  53420. this._renderPasses[renderPass._name] = renderPass;
  53421. this._linkParameters();
  53422. };
  53423. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  53424. delete this._renderPasses[renderPass._name];
  53425. this._linkParameters();
  53426. };
  53427. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  53428. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  53429. this._linkParameters();
  53430. };
  53431. PostProcessRenderEffect.prototype.getPass = function (passName) {
  53432. for (var renderPassName in this._renderPasses) {
  53433. if (renderPassName === passName) {
  53434. return this._renderPasses[passName];
  53435. }
  53436. }
  53437. };
  53438. PostProcessRenderEffect.prototype.emptyPasses = function () {
  53439. this._renderPasses = {};
  53440. this._linkParameters();
  53441. };
  53442. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  53443. var cameraKey;
  53444. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53445. for (var i = 0; i < _cam.length; i++) {
  53446. var camera = _cam[i];
  53447. var cameraName = camera.name;
  53448. if (this._singleInstance) {
  53449. cameraKey = 0;
  53450. }
  53451. else {
  53452. cameraKey = cameraName;
  53453. }
  53454. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  53455. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  53456. if (!this._indicesForCamera[cameraName]) {
  53457. this._indicesForCamera[cameraName] = [];
  53458. }
  53459. this._indicesForCamera[cameraName].push(index);
  53460. if (this._cameras.indexOf(camera) === -1) {
  53461. this._cameras[cameraName] = camera;
  53462. }
  53463. for (var passName in this._renderPasses) {
  53464. this._renderPasses[passName]._incRefCount();
  53465. }
  53466. }
  53467. this._linkParameters();
  53468. };
  53469. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  53470. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53471. for (var i = 0; i < _cam.length; i++) {
  53472. var camera = _cam[i];
  53473. var cameraName = camera.name;
  53474. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  53475. var index = this._cameras.indexOf(cameraName);
  53476. this._indicesForCamera.splice(index, 1);
  53477. this._cameras.splice(index, 1);
  53478. for (var passName in this._renderPasses) {
  53479. this._renderPasses[passName]._decRefCount();
  53480. }
  53481. }
  53482. };
  53483. PostProcessRenderEffect.prototype._enable = function (cameras) {
  53484. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53485. for (var i = 0; i < _cam.length; i++) {
  53486. var camera = _cam[i];
  53487. var cameraName = camera.name;
  53488. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  53489. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  53490. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  53491. }
  53492. }
  53493. for (var passName in this._renderPasses) {
  53494. this._renderPasses[passName]._incRefCount();
  53495. }
  53496. }
  53497. };
  53498. PostProcessRenderEffect.prototype._disable = function (cameras) {
  53499. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53500. for (var i = 0; i < _cam.length; i++) {
  53501. var camera = _cam[i];
  53502. var cameraName = camera.Name;
  53503. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  53504. for (var passName in this._renderPasses) {
  53505. this._renderPasses[passName]._decRefCount();
  53506. }
  53507. }
  53508. };
  53509. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  53510. if (this._singleInstance) {
  53511. return this._postProcesses[0];
  53512. }
  53513. else {
  53514. return this._postProcesses[camera.name];
  53515. }
  53516. };
  53517. PostProcessRenderEffect.prototype._linkParameters = function () {
  53518. var _this = this;
  53519. for (var index in this._postProcesses) {
  53520. if (this.applyParameters) {
  53521. this.applyParameters(this._postProcesses[index]);
  53522. }
  53523. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  53524. _this._linkTextures(effect);
  53525. });
  53526. }
  53527. };
  53528. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  53529. for (var renderPassName in this._renderPasses) {
  53530. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  53531. }
  53532. for (var renderEffectName in this._renderEffectAsPasses) {
  53533. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  53534. }
  53535. };
  53536. return PostProcessRenderEffect;
  53537. }());
  53538. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  53539. })(BABYLON || (BABYLON = {}));
  53540. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  53541. var BABYLON;
  53542. (function (BABYLON) {
  53543. var PostProcessRenderPipeline = (function () {
  53544. function PostProcessRenderPipeline(engine, name) {
  53545. this._engine = engine;
  53546. this._name = name;
  53547. this._renderEffects = new Array();
  53548. this._renderEffectsForIsolatedPass = new Array();
  53549. this._cameras = [];
  53550. }
  53551. PostProcessRenderPipeline.prototype.getClassName = function () {
  53552. return "PostProcessRenderPipeline";
  53553. };
  53554. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  53555. get: function () {
  53556. for (var renderEffectName in this._renderEffects) {
  53557. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53558. if (!this._renderEffects[renderEffectName].isSupported) {
  53559. return false;
  53560. }
  53561. }
  53562. }
  53563. return true;
  53564. },
  53565. enumerable: true,
  53566. configurable: true
  53567. });
  53568. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  53569. this._renderEffects[renderEffect._name] = renderEffect;
  53570. };
  53571. // private
  53572. PostProcessRenderPipeline.prototype._rebuild = function () {
  53573. };
  53574. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  53575. var renderEffects = this._renderEffects[renderEffectName];
  53576. if (!renderEffects) {
  53577. return;
  53578. }
  53579. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  53580. };
  53581. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  53582. var renderEffects = this._renderEffects[renderEffectName];
  53583. if (!renderEffects) {
  53584. return;
  53585. }
  53586. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  53587. };
  53588. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  53589. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53590. var indicesToDelete = [];
  53591. var i;
  53592. for (i = 0; i < _cam.length; i++) {
  53593. var camera = _cam[i];
  53594. var cameraName = camera.name;
  53595. if (this._cameras.indexOf(camera) === -1) {
  53596. this._cameras[cameraName] = camera;
  53597. }
  53598. else if (unique) {
  53599. indicesToDelete.push(i);
  53600. }
  53601. }
  53602. for (i = 0; i < indicesToDelete.length; i++) {
  53603. cameras.splice(indicesToDelete[i], 1);
  53604. }
  53605. for (var renderEffectName in this._renderEffects) {
  53606. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53607. this._renderEffects[renderEffectName]._attachCameras(_cam);
  53608. }
  53609. }
  53610. };
  53611. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  53612. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53613. for (var renderEffectName in this._renderEffects) {
  53614. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53615. this._renderEffects[renderEffectName]._detachCameras(_cam);
  53616. }
  53617. }
  53618. for (var i = 0; i < _cam.length; i++) {
  53619. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  53620. }
  53621. };
  53622. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  53623. var _this = this;
  53624. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53625. var pass = null;
  53626. var renderEffectName;
  53627. for (renderEffectName in this._renderEffects) {
  53628. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53629. pass = this._renderEffects[renderEffectName].getPass(passName);
  53630. if (pass != null) {
  53631. break;
  53632. }
  53633. }
  53634. }
  53635. if (pass === null) {
  53636. return;
  53637. }
  53638. for (renderEffectName in this._renderEffects) {
  53639. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53640. this._renderEffects[renderEffectName]._disable(_cam);
  53641. }
  53642. }
  53643. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  53644. for (var i = 0; i < _cam.length; i++) {
  53645. var camera = _cam[i];
  53646. var cameraName = camera.name;
  53647. 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); });
  53648. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  53649. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  53650. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  53651. }
  53652. };
  53653. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  53654. var _this = this;
  53655. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  53656. for (var i = 0; i < _cam.length; i++) {
  53657. var camera = _cam[i];
  53658. var cameraName = camera.name;
  53659. 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); });
  53660. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  53661. }
  53662. for (var renderEffectName in this._renderEffects) {
  53663. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53664. this._renderEffects[renderEffectName]._enable(_cam);
  53665. }
  53666. }
  53667. };
  53668. PostProcessRenderPipeline.prototype._update = function () {
  53669. for (var renderEffectName in this._renderEffects) {
  53670. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  53671. this._renderEffects[renderEffectName]._update();
  53672. }
  53673. }
  53674. for (var i = 0; i < this._cameras.length; i++) {
  53675. var cameraName = this._cameras[i].name;
  53676. if (this._renderEffectsForIsolatedPass[cameraName]) {
  53677. this._renderEffectsForIsolatedPass[cameraName]._update();
  53678. }
  53679. }
  53680. };
  53681. PostProcessRenderPipeline.prototype._reset = function () {
  53682. this._renderEffects = new Array();
  53683. this._renderEffectsForIsolatedPass = new Array();
  53684. };
  53685. PostProcessRenderPipeline.prototype.dispose = function () {
  53686. // Must be implemented by children
  53687. };
  53688. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  53689. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  53690. __decorate([
  53691. BABYLON.serialize()
  53692. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  53693. return PostProcessRenderPipeline;
  53694. }());
  53695. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  53696. })(BABYLON || (BABYLON = {}));
  53697. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  53698. var BABYLON;
  53699. (function (BABYLON) {
  53700. var DepthRenderer = (function () {
  53701. function DepthRenderer(scene, type) {
  53702. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53703. var _this = this;
  53704. this._viewMatrix = BABYLON.Matrix.Zero();
  53705. this._projectionMatrix = BABYLON.Matrix.Zero();
  53706. this._transformMatrix = BABYLON.Matrix.Zero();
  53707. this._worldViewProjection = BABYLON.Matrix.Zero();
  53708. this._scene = scene;
  53709. var engine = scene.getEngine();
  53710. // Render target
  53711. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53712. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53713. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53714. this._depthMap.refreshRate = 1;
  53715. this._depthMap.renderParticles = false;
  53716. this._depthMap.renderList = null;
  53717. // set default depth value to 1.0 (far away)
  53718. this._depthMap.onClearObservable.add(function (engine) {
  53719. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53720. });
  53721. // Custom render function
  53722. var renderSubMesh = function (subMesh) {
  53723. var mesh = subMesh.getRenderingMesh();
  53724. var scene = _this._scene;
  53725. var engine = scene.getEngine();
  53726. // Culling
  53727. engine.setState(subMesh.getMaterial().backFaceCulling);
  53728. // Managing instances
  53729. var batch = mesh._getInstancesRenderList(subMesh._id);
  53730. if (batch.mustReturn) {
  53731. return;
  53732. }
  53733. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  53734. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53735. engine.enableEffect(_this._effect);
  53736. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53737. var material = subMesh.getMaterial();
  53738. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53739. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  53740. // Alpha test
  53741. if (material && material.needAlphaTesting()) {
  53742. var alphaTexture = material.getAlphaTestTexture();
  53743. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53744. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53745. }
  53746. // Bones
  53747. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53748. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53749. }
  53750. // Draw
  53751. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53752. }
  53753. };
  53754. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53755. var index;
  53756. if (depthOnlySubMeshes.length) {
  53757. engine.setColorWrite(false);
  53758. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53759. renderSubMesh(depthOnlySubMeshes.data[index]);
  53760. }
  53761. engine.setColorWrite(true);
  53762. }
  53763. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53764. renderSubMesh(opaqueSubMeshes.data[index]);
  53765. }
  53766. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53767. renderSubMesh(alphaTestSubMeshes.data[index]);
  53768. }
  53769. };
  53770. }
  53771. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53772. var material = subMesh.getMaterial();
  53773. if (material.disableDepthWrite) {
  53774. return false;
  53775. }
  53776. var defines = [];
  53777. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53778. var mesh = subMesh.getMesh();
  53779. var scene = mesh.getScene();
  53780. // Alpha test
  53781. if (material && material.needAlphaTesting()) {
  53782. defines.push("#define ALPHATEST");
  53783. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53784. attribs.push(BABYLON.VertexBuffer.UVKind);
  53785. defines.push("#define UV1");
  53786. }
  53787. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53788. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53789. defines.push("#define UV2");
  53790. }
  53791. }
  53792. // Bones
  53793. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53794. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53795. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53796. if (mesh.numBoneInfluencers > 4) {
  53797. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53798. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53799. }
  53800. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53801. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53802. }
  53803. else {
  53804. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53805. }
  53806. // Instances
  53807. if (useInstances) {
  53808. defines.push("#define INSTANCES");
  53809. attribs.push("world0");
  53810. attribs.push("world1");
  53811. attribs.push("world2");
  53812. attribs.push("world3");
  53813. }
  53814. // Get correct effect
  53815. var join = defines.join("\n");
  53816. if (this._cachedDefines !== join) {
  53817. this._cachedDefines = join;
  53818. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  53819. }
  53820. return this._effect.isReady();
  53821. };
  53822. DepthRenderer.prototype.getDepthMap = function () {
  53823. return this._depthMap;
  53824. };
  53825. // Methods
  53826. DepthRenderer.prototype.dispose = function () {
  53827. this._depthMap.dispose();
  53828. };
  53829. return DepthRenderer;
  53830. }());
  53831. BABYLON.DepthRenderer = DepthRenderer;
  53832. })(BABYLON || (BABYLON = {}));
  53833. //# sourceMappingURL=babylon.depthRenderer.js.map
  53834. var BABYLON;
  53835. (function (BABYLON) {
  53836. var SSAORenderingPipeline = (function (_super) {
  53837. __extends(SSAORenderingPipeline, _super);
  53838. /**
  53839. * @constructor
  53840. * @param {string} name - The rendering pipeline name
  53841. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53842. * @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 }
  53843. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53844. */
  53845. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53846. var _this = _super.call(this, scene.getEngine(), name) || this;
  53847. // Members
  53848. /**
  53849. * The PassPostProcess id in the pipeline that contains the original scene color
  53850. * @type {string}
  53851. */
  53852. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53853. /**
  53854. * The SSAO PostProcess id in the pipeline
  53855. * @type {string}
  53856. */
  53857. _this.SSAORenderEffect = "SSAORenderEffect";
  53858. /**
  53859. * The horizontal blur PostProcess id in the pipeline
  53860. * @type {string}
  53861. */
  53862. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53863. /**
  53864. * The vertical blur PostProcess id in the pipeline
  53865. * @type {string}
  53866. */
  53867. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53868. /**
  53869. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53870. * @type {string}
  53871. */
  53872. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53873. /**
  53874. * The output strength of the SSAO post-process. Default value is 1.0.
  53875. * @type {number}
  53876. */
  53877. _this.totalStrength = 1.0;
  53878. /**
  53879. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53880. * @type {number}
  53881. */
  53882. _this.radius = 0.0001;
  53883. /**
  53884. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53885. * Must not be equal to fallOff and superior to fallOff.
  53886. * Default value is 0.975
  53887. * @type {number}
  53888. */
  53889. _this.area = 0.0075;
  53890. /**
  53891. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53892. * Must not be equal to area and inferior to area.
  53893. * Default value is 0.0
  53894. * @type {number}
  53895. */
  53896. _this.fallOff = 0.000001;
  53897. /**
  53898. * The base color of the SSAO post-process
  53899. * The final result is "base + ssao" between [0, 1]
  53900. * @type {number}
  53901. */
  53902. _this.base = 0.5;
  53903. _this._firstUpdate = true;
  53904. _this._scene = scene;
  53905. // Set up assets
  53906. _this._createRandomTexture();
  53907. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53908. var ssaoRatio = ratio.ssaoRatio || ratio;
  53909. var combineRatio = ratio.combineRatio || ratio;
  53910. _this._ratio = {
  53911. ssaoRatio: ssaoRatio,
  53912. combineRatio: combineRatio
  53913. };
  53914. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53915. _this._createSSAOPostProcess(ssaoRatio);
  53916. _this._createBlurPostProcess(ssaoRatio);
  53917. _this._createSSAOCombinePostProcess(combineRatio);
  53918. // Set up pipeline
  53919. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53920. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53921. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53922. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53923. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53924. // Finish
  53925. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53926. if (cameras)
  53927. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53928. return _this;
  53929. }
  53930. // Public Methods
  53931. /**
  53932. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53933. */
  53934. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53935. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53936. for (var i = 0; i < this._scene.cameras.length; i++) {
  53937. var camera = this._scene.cameras[i];
  53938. this._originalColorPostProcess.dispose(camera);
  53939. this._ssaoPostProcess.dispose(camera);
  53940. this._blurHPostProcess.dispose(camera);
  53941. this._blurVPostProcess.dispose(camera);
  53942. this._ssaoCombinePostProcess.dispose(camera);
  53943. }
  53944. this._randomTexture.dispose();
  53945. if (disableDepthRender)
  53946. this._scene.disableDepthRenderer();
  53947. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53948. _super.prototype.dispose.call(this);
  53949. };
  53950. // Private Methods
  53951. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53952. var _this = this;
  53953. /*
  53954. var samplerOffsets = [
  53955. -8.0, -6.0, -4.0, -2.0,
  53956. 0.0,
  53957. 2.0, 4.0, 6.0, 8.0
  53958. ];
  53959. */
  53960. var samples = 16;
  53961. var samplerOffsets = [];
  53962. for (var i = -8; i < 8; i++) {
  53963. samplerOffsets.push(i * 2);
  53964. }
  53965. 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");
  53966. this._blurHPostProcess.onApply = function (effect) {
  53967. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53968. effect.setTexture("depthSampler", _this._depthTexture);
  53969. if (_this._firstUpdate) {
  53970. effect.setArray("samplerOffsets", samplerOffsets);
  53971. }
  53972. };
  53973. 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");
  53974. this._blurVPostProcess.onApply = function (effect) {
  53975. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53976. effect.setTexture("depthSampler", _this._depthTexture);
  53977. if (_this._firstUpdate) {
  53978. effect.setArray("samplerOffsets", samplerOffsets);
  53979. _this._firstUpdate = false;
  53980. }
  53981. };
  53982. };
  53983. SSAORenderingPipeline.prototype._rebuild = function () {
  53984. this._firstUpdate = true;
  53985. _super.prototype._rebuild.call(this);
  53986. };
  53987. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53988. var _this = this;
  53989. var numSamples = 16;
  53990. var sampleSphere = [
  53991. 0.5381, 0.1856, -0.4319,
  53992. 0.1379, 0.2486, 0.4430,
  53993. 0.3371, 0.5679, -0.0057,
  53994. -0.6999, -0.0451, -0.0019,
  53995. 0.0689, -0.1598, -0.8547,
  53996. 0.0560, 0.0069, -0.1843,
  53997. -0.0146, 0.1402, 0.0762,
  53998. 0.0100, -0.1924, -0.0344,
  53999. -0.3577, -0.5301, -0.4358,
  54000. -0.3169, 0.1063, 0.0158,
  54001. 0.0103, -0.5869, 0.0046,
  54002. -0.0897, -0.4940, 0.3287,
  54003. 0.7119, -0.0154, -0.0918,
  54004. -0.0533, 0.0596, -0.5411,
  54005. 0.0352, -0.0631, 0.5460,
  54006. -0.4776, 0.2847, -0.0271
  54007. ];
  54008. var samplesFactor = 1.0 / numSamples;
  54009. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  54010. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  54011. "area", "fallOff", "base", "range", "viewport"
  54012. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  54013. var viewport = new BABYLON.Vector2(0, 0);
  54014. this._ssaoPostProcess.onApply = function (effect) {
  54015. if (_this._firstUpdate) {
  54016. effect.setArray3("sampleSphere", sampleSphere);
  54017. effect.setFloat("samplesFactor", samplesFactor);
  54018. effect.setFloat("randTextureTiles", 4.0);
  54019. }
  54020. effect.setFloat("totalStrength", _this.totalStrength);
  54021. effect.setFloat("radius", _this.radius);
  54022. effect.setFloat("area", _this.area);
  54023. effect.setFloat("fallOff", _this.fallOff);
  54024. effect.setFloat("base", _this.base);
  54025. effect.setTexture("textureSampler", _this._depthTexture);
  54026. effect.setTexture("randomSampler", _this._randomTexture);
  54027. };
  54028. };
  54029. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  54030. var _this = this;
  54031. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54032. this._ssaoCombinePostProcess.onApply = function (effect) {
  54033. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  54034. };
  54035. };
  54036. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  54037. var size = 512;
  54038. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54039. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54040. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54041. var context = this._randomTexture.getContext();
  54042. var rand = function (min, max) {
  54043. return Math.random() * (max - min) + min;
  54044. };
  54045. var randVector = BABYLON.Vector3.Zero();
  54046. for (var x = 0; x < size; x++) {
  54047. for (var y = 0; y < size; y++) {
  54048. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  54049. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  54050. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  54051. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  54052. context.fillRect(x, y, 1, 1);
  54053. }
  54054. }
  54055. this._randomTexture.update(false);
  54056. };
  54057. __decorate([
  54058. BABYLON.serialize()
  54059. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  54060. __decorate([
  54061. BABYLON.serialize()
  54062. ], SSAORenderingPipeline.prototype, "radius", void 0);
  54063. __decorate([
  54064. BABYLON.serialize()
  54065. ], SSAORenderingPipeline.prototype, "area", void 0);
  54066. __decorate([
  54067. BABYLON.serialize()
  54068. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  54069. __decorate([
  54070. BABYLON.serialize()
  54071. ], SSAORenderingPipeline.prototype, "base", void 0);
  54072. __decorate([
  54073. BABYLON.serialize()
  54074. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  54075. return SSAORenderingPipeline;
  54076. }(BABYLON.PostProcessRenderPipeline));
  54077. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  54078. })(BABYLON || (BABYLON = {}));
  54079. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  54080. var BABYLON;
  54081. (function (BABYLON) {
  54082. var SSAO2RenderingPipeline = (function (_super) {
  54083. __extends(SSAO2RenderingPipeline, _super);
  54084. /**
  54085. * @constructor
  54086. * @param {string} name - The rendering pipeline name
  54087. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54088. * @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 }
  54089. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54090. */
  54091. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  54092. var _this = _super.call(this, scene.getEngine(), name) || this;
  54093. // Members
  54094. /**
  54095. * The PassPostProcess id in the pipeline that contains the original scene color
  54096. * @type {string}
  54097. */
  54098. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  54099. /**
  54100. * The SSAO PostProcess id in the pipeline
  54101. * @type {string}
  54102. */
  54103. _this.SSAORenderEffect = "SSAORenderEffect";
  54104. /**
  54105. * The horizontal blur PostProcess id in the pipeline
  54106. * @type {string}
  54107. */
  54108. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  54109. /**
  54110. * The vertical blur PostProcess id in the pipeline
  54111. * @type {string}
  54112. */
  54113. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  54114. /**
  54115. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  54116. * @type {string}
  54117. */
  54118. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  54119. /**
  54120. * The output strength of the SSAO post-process. Default value is 1.0.
  54121. * @type {number}
  54122. */
  54123. _this.totalStrength = 1.0;
  54124. /**
  54125. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  54126. * @type {number}
  54127. */
  54128. _this.maxZ = 100.0;
  54129. /**
  54130. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  54131. * @type {number}
  54132. */
  54133. _this.minZAspect = 0.2;
  54134. /**
  54135. * Number of samples used for the SSAO calculations. Default value is 8
  54136. * @type {number}
  54137. */
  54138. _this._samples = 8;
  54139. /**
  54140. * Are we using bilateral blur ?
  54141. * @type {boolean}
  54142. */
  54143. _this._expensiveBlur = true;
  54144. /**
  54145. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  54146. * @type {number}
  54147. */
  54148. _this.radius = 2.0;
  54149. /**
  54150. * The base color of the SSAO post-process
  54151. * The final result is "base + ssao" between [0, 1]
  54152. * @type {number}
  54153. */
  54154. _this.base = 0.1;
  54155. _this._firstUpdate = true;
  54156. _this._scene = scene;
  54157. if (!_this.isSupported) {
  54158. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  54159. return _this;
  54160. }
  54161. var ssaoRatio = ratio.ssaoRatio || ratio;
  54162. var blurRatio = ratio.blurRatio || ratio;
  54163. _this._ratio = {
  54164. ssaoRatio: ssaoRatio,
  54165. blurRatio: blurRatio
  54166. };
  54167. // Set up assets
  54168. _this._createRandomTexture();
  54169. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  54170. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  54171. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54172. _this._createSSAOPostProcess(1.0);
  54173. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  54174. _this._createSSAOCombinePostProcess(blurRatio);
  54175. // Set up pipeline
  54176. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  54177. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  54178. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  54179. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  54180. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  54181. // Finish
  54182. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54183. if (cameras)
  54184. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54185. return _this;
  54186. }
  54187. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  54188. get: function () {
  54189. return this._samples;
  54190. },
  54191. set: function (n) {
  54192. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  54193. this._samples = n;
  54194. this._sampleSphere = this._generateHemisphere();
  54195. this._firstUpdate = true;
  54196. },
  54197. enumerable: true,
  54198. configurable: true
  54199. });
  54200. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  54201. get: function () {
  54202. return this._expensiveBlur;
  54203. },
  54204. set: function (b) {
  54205. 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"]);
  54206. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  54207. this._expensiveBlur = b;
  54208. this._firstUpdate = true;
  54209. },
  54210. enumerable: true,
  54211. configurable: true
  54212. });
  54213. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  54214. /**
  54215. * Support test.
  54216. * @type {boolean}
  54217. */
  54218. get: function () {
  54219. var engine = BABYLON.Engine.LastCreatedEngine;
  54220. return engine.getCaps().drawBuffersExtension;
  54221. },
  54222. enumerable: true,
  54223. configurable: true
  54224. });
  54225. // Public Methods
  54226. /**
  54227. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  54228. */
  54229. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  54230. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  54231. for (var i = 0; i < this._scene.cameras.length; i++) {
  54232. var camera = this._scene.cameras[i];
  54233. this._originalColorPostProcess.dispose(camera);
  54234. this._ssaoPostProcess.dispose(camera);
  54235. this._blurHPostProcess.dispose(camera);
  54236. this._blurVPostProcess.dispose(camera);
  54237. this._ssaoCombinePostProcess.dispose(camera);
  54238. }
  54239. this._randomTexture.dispose();
  54240. if (disableGeometryBufferRenderer)
  54241. this._scene.disableGeometryBufferRenderer();
  54242. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54243. _super.prototype.dispose.call(this);
  54244. };
  54245. // Private Methods
  54246. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  54247. var _this = this;
  54248. var samples = 16;
  54249. this._samplerOffsets = [];
  54250. var expensive = this.expensiveBlur;
  54251. for (var i = -8; i < 8; i++) {
  54252. this._samplerOffsets.push(i * 2 + 0.5);
  54253. }
  54254. 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");
  54255. this._blurHPostProcess.onApply = function (effect) {
  54256. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  54257. effect.setFloat("near", _this._scene.activeCamera.minZ);
  54258. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  54259. effect.setFloat("radius", _this.radius);
  54260. effect.setTexture("depthSampler", _this._depthTexture);
  54261. if (_this._firstUpdate) {
  54262. effect.setArray("samplerOffsets", _this._samplerOffsets);
  54263. }
  54264. };
  54265. 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");
  54266. this._blurVPostProcess.onApply = function (effect) {
  54267. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  54268. effect.setFloat("near", _this._scene.activeCamera.minZ);
  54269. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  54270. effect.setFloat("radius", _this.radius);
  54271. effect.setTexture("depthSampler", _this._depthTexture);
  54272. if (_this._firstUpdate) {
  54273. effect.setArray("samplerOffsets", _this._samplerOffsets);
  54274. _this._firstUpdate = false;
  54275. }
  54276. };
  54277. };
  54278. SSAO2RenderingPipeline.prototype._rebuild = function () {
  54279. this._firstUpdate = true;
  54280. _super.prototype._rebuild.call(this);
  54281. };
  54282. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  54283. var numSamples = this.samples;
  54284. var result = [];
  54285. var vector, scale;
  54286. var rand = function (min, max) {
  54287. return Math.random() * (max - min) + min;
  54288. };
  54289. var lerp = function (start, end, percent) {
  54290. return (start + percent * (end - start));
  54291. };
  54292. var i = 0;
  54293. var normal = new BABYLON.Vector3(0, 0, 1);
  54294. while (i < numSamples) {
  54295. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  54296. vector.normalize();
  54297. scale = i / numSamples;
  54298. scale = lerp(0.1, 1.0, scale * scale);
  54299. vector.scaleInPlace(scale);
  54300. result.push(vector.x, vector.y, vector.z);
  54301. i++;
  54302. }
  54303. return result;
  54304. };
  54305. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  54306. var _this = this;
  54307. var numSamples = this.samples;
  54308. this._sampleSphere = this._generateHemisphere();
  54309. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  54310. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  54311. "base", "range", "projection", "near", "far", "texelSize",
  54312. "xViewport", "yViewport", "maxZ", "minZAspect"
  54313. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  54314. this._ssaoPostProcess.onApply = function (effect) {
  54315. if (_this._firstUpdate) {
  54316. effect.setArray3("sampleSphere", _this._sampleSphere);
  54317. effect.setFloat("randTextureTiles", 4.0);
  54318. }
  54319. effect.setFloat("samplesFactor", 1 / _this.samples);
  54320. effect.setFloat("totalStrength", _this.totalStrength);
  54321. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  54322. effect.setFloat("radius", _this.radius);
  54323. effect.setFloat("maxZ", _this.maxZ);
  54324. effect.setFloat("minZAspect", _this.minZAspect);
  54325. effect.setFloat("base", _this.base);
  54326. effect.setFloat("near", _this._scene.activeCamera.minZ);
  54327. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  54328. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  54329. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  54330. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  54331. effect.setTexture("textureSampler", _this._depthTexture);
  54332. effect.setTexture("normalSampler", _this._normalTexture);
  54333. effect.setTexture("randomSampler", _this._randomTexture);
  54334. };
  54335. };
  54336. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  54337. var _this = this;
  54338. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54339. this._ssaoCombinePostProcess.onApply = function (effect) {
  54340. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  54341. };
  54342. };
  54343. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  54344. var size = 512;
  54345. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54346. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54347. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54348. var context = this._randomTexture.getContext();
  54349. var rand = function (min, max) {
  54350. return Math.random() * (max - min) + min;
  54351. };
  54352. var randVector = BABYLON.Vector3.Zero();
  54353. for (var x = 0; x < size; x++) {
  54354. for (var y = 0; y < size; y++) {
  54355. randVector.x = rand(0.0, 1.0);
  54356. randVector.y = rand(0.0, 1.0);
  54357. randVector.z = 0.0;
  54358. randVector.normalize();
  54359. randVector.scaleInPlace(255);
  54360. randVector.x = Math.floor(randVector.x);
  54361. randVector.y = Math.floor(randVector.y);
  54362. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  54363. context.fillRect(x, y, 1, 1);
  54364. }
  54365. }
  54366. this._randomTexture.update(false);
  54367. };
  54368. __decorate([
  54369. BABYLON.serialize()
  54370. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  54371. __decorate([
  54372. BABYLON.serialize()
  54373. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  54374. __decorate([
  54375. BABYLON.serialize()
  54376. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  54377. __decorate([
  54378. BABYLON.serialize("samples")
  54379. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  54380. __decorate([
  54381. BABYLON.serialize("expensiveBlur")
  54382. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  54383. __decorate([
  54384. BABYLON.serialize()
  54385. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  54386. __decorate([
  54387. BABYLON.serialize()
  54388. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  54389. __decorate([
  54390. BABYLON.serialize()
  54391. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  54392. return SSAO2RenderingPipeline;
  54393. }(BABYLON.PostProcessRenderPipeline));
  54394. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  54395. })(BABYLON || (BABYLON = {}));
  54396. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  54397. // BABYLON.JS Chromatic Aberration GLSL Shader
  54398. // Author: Olivier Guyot
  54399. // Separates very slightly R, G and B colors on the edges of the screen
  54400. // Inspired by Francois Tarlier & Martins Upitis
  54401. var BABYLON;
  54402. (function (BABYLON) {
  54403. var LensRenderingPipeline = (function (_super) {
  54404. __extends(LensRenderingPipeline, _super);
  54405. /**
  54406. * @constructor
  54407. *
  54408. * Effect parameters are as follow:
  54409. * {
  54410. * chromatic_aberration: number; // from 0 to x (1 for realism)
  54411. * edge_blur: number; // from 0 to x (1 for realism)
  54412. * distortion: number; // from 0 to x (1 for realism)
  54413. * grain_amount: number; // from 0 to 1
  54414. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  54415. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  54416. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  54417. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  54418. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  54419. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  54420. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  54421. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  54422. * }
  54423. * Note: if an effect parameter is unset, effect is disabled
  54424. *
  54425. * @param {string} name - The rendering pipeline name
  54426. * @param {object} parameters - An object containing all parameters (see above)
  54427. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54428. * @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)
  54429. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54430. */
  54431. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  54432. if (ratio === void 0) { ratio = 1.0; }
  54433. var _this = _super.call(this, scene.getEngine(), name) || this;
  54434. // Lens effects can be of the following:
  54435. // - chromatic aberration (slight shift of RGB colors)
  54436. // - blur on the edge of the lens
  54437. // - lens distortion
  54438. // - depth-of-field blur & highlights enhancing
  54439. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  54440. // - grain effect (noise or custom texture)
  54441. // Two additional texture samplers are needed:
  54442. // - depth map (for depth-of-field)
  54443. // - grain texture
  54444. /**
  54445. * The chromatic aberration PostProcess id in the pipeline
  54446. * @type {string}
  54447. */
  54448. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  54449. /**
  54450. * The highlights enhancing PostProcess id in the pipeline
  54451. * @type {string}
  54452. */
  54453. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  54454. /**
  54455. * The depth-of-field PostProcess id in the pipeline
  54456. * @type {string}
  54457. */
  54458. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54459. _this._scene = scene;
  54460. // Fetch texture samplers
  54461. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54462. if (parameters.grain_texture) {
  54463. _this._grainTexture = parameters.grain_texture;
  54464. }
  54465. else {
  54466. _this._createGrainTexture();
  54467. }
  54468. // save parameters
  54469. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54470. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54471. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54472. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  54473. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54474. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54475. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54476. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54477. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54478. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54479. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54480. // Create effects
  54481. _this._createChromaticAberrationPostProcess(ratio);
  54482. _this._createHighlightsPostProcess(ratio);
  54483. _this._createDepthOfFieldPostProcess(ratio / 4);
  54484. // Set up pipeline
  54485. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54486. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54487. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54488. if (_this._highlightsGain === -1) {
  54489. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  54490. }
  54491. // Finish
  54492. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54493. if (cameras) {
  54494. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54495. }
  54496. return _this;
  54497. }
  54498. // public methods (self explanatory)
  54499. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54500. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54501. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54502. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54503. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54504. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54505. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54506. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54507. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54508. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54509. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54510. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54511. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54512. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54513. };
  54514. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54515. this._highlightsPostProcess.updateEffect();
  54516. };
  54517. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54518. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54519. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54520. this._highlightsGain = amount;
  54521. };
  54522. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54523. if (this._highlightsGain === -1) {
  54524. this._highlightsGain = 1.0;
  54525. }
  54526. this._highlightsThreshold = amount;
  54527. };
  54528. LensRenderingPipeline.prototype.disableHighlights = function () {
  54529. this._highlightsGain = -1;
  54530. };
  54531. /**
  54532. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54533. */
  54534. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54535. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54536. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54537. this._chromaticAberrationPostProcess = undefined;
  54538. this._highlightsPostProcess = undefined;
  54539. this._depthOfFieldPostProcess = undefined;
  54540. this._grainTexture.dispose();
  54541. if (disableDepthRender)
  54542. this._scene.disableDepthRenderer();
  54543. };
  54544. // colors shifting and distortion
  54545. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54546. var _this = this;
  54547. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54548. [], // samplers
  54549. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54550. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54551. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54552. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54553. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54554. };
  54555. };
  54556. // highlights enhancing
  54557. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54558. var _this = this;
  54559. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54560. [], // samplers
  54561. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54562. this._highlightsPostProcess.onApply = function (effect) {
  54563. effect.setFloat('gain', _this._highlightsGain);
  54564. effect.setFloat('threshold', _this._highlightsThreshold);
  54565. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54566. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54567. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54568. };
  54569. };
  54570. // colors shifting and distortion
  54571. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54572. var _this = this;
  54573. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54574. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54575. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54576. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54577. this._depthOfFieldPostProcess.onApply = function (effect) {
  54578. effect.setTexture("depthSampler", _this._depthTexture);
  54579. effect.setTexture("grainSampler", _this._grainTexture);
  54580. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54581. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54582. effect.setFloat('grain_amount', _this._grainAmount);
  54583. effect.setBool('blur_noise', _this._blurNoise);
  54584. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54585. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54586. effect.setFloat('distortion', _this._distortion);
  54587. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54588. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54589. effect.setFloat('aperture', _this._dofAperture);
  54590. effect.setFloat('darken', _this._dofDarken);
  54591. effect.setFloat('edge_blur', _this._edgeBlur);
  54592. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54593. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54594. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54595. };
  54596. };
  54597. // creates a black and white random noise texture, 512x512
  54598. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54599. var size = 512;
  54600. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54601. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54602. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54603. var context = this._grainTexture.getContext();
  54604. var rand = function (min, max) {
  54605. return Math.random() * (max - min) + min;
  54606. };
  54607. var value;
  54608. for (var x = 0; x < size; x++) {
  54609. for (var y = 0; y < size; y++) {
  54610. value = Math.floor(rand(0.42, 0.58) * 255);
  54611. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54612. context.fillRect(x, y, 1, 1);
  54613. }
  54614. }
  54615. this._grainTexture.update(false);
  54616. };
  54617. return LensRenderingPipeline;
  54618. }(BABYLON.PostProcessRenderPipeline));
  54619. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54620. })(BABYLON || (BABYLON = {}));
  54621. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  54622. var BABYLON;
  54623. (function (BABYLON) {
  54624. var StandardRenderingPipeline = (function (_super) {
  54625. __extends(StandardRenderingPipeline, _super);
  54626. /**
  54627. * @constructor
  54628. * @param {string} name - The rendering pipeline name
  54629. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54630. * @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)
  54631. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54632. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54633. */
  54634. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54635. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54636. var _this = _super.call(this, scene.getEngine(), name) || this;
  54637. _this.downSampleX4PostProcess = null;
  54638. _this.brightPassPostProcess = null;
  54639. _this.blurHPostProcesses = [];
  54640. _this.blurVPostProcesses = [];
  54641. _this.textureAdderPostProcess = null;
  54642. _this.volumetricLightPostProcess = null;
  54643. _this.volumetricLightSmoothXPostProcess = null;
  54644. _this.volumetricLightSmoothYPostProcess = null;
  54645. _this.volumetricLightMergePostProces = null;
  54646. _this.volumetricLightFinalPostProcess = null;
  54647. _this.luminancePostProcess = null;
  54648. _this.luminanceDownSamplePostProcesses = [];
  54649. _this.hdrPostProcess = null;
  54650. _this.textureAdderFinalPostProcess = null;
  54651. _this.lensFlareFinalPostProcess = null;
  54652. _this.hdrFinalPostProcess = null;
  54653. _this.lensFlarePostProcess = null;
  54654. _this.lensFlareComposePostProcess = null;
  54655. _this.motionBlurPostProcess = null;
  54656. _this.depthOfFieldPostProcess = null;
  54657. // Values
  54658. _this.brightThreshold = 1.0;
  54659. _this.blurWidth = 512.0;
  54660. _this.horizontalBlur = false;
  54661. _this.exposure = 1.0;
  54662. _this.lensTexture = null;
  54663. _this.volumetricLightCoefficient = 0.2;
  54664. _this.volumetricLightPower = 4.0;
  54665. _this.volumetricLightBlurScale = 64.0;
  54666. _this.sourceLight = null;
  54667. _this.hdrMinimumLuminance = 1.0;
  54668. _this.hdrDecreaseRate = 0.5;
  54669. _this.hdrIncreaseRate = 0.5;
  54670. _this.lensColorTexture = null;
  54671. _this.lensFlareStrength = 20.0;
  54672. _this.lensFlareGhostDispersal = 1.4;
  54673. _this.lensFlareHaloWidth = 0.7;
  54674. _this.lensFlareDistortionStrength = 16.0;
  54675. _this.lensStarTexture = null;
  54676. _this.lensFlareDirtTexture = null;
  54677. _this.depthOfFieldDistance = 10.0;
  54678. _this.depthOfFieldBlurWidth = 64.0;
  54679. _this.motionStrength = 1.0;
  54680. // IAnimatable
  54681. _this.animations = [];
  54682. _this._currentDepthOfFieldSource = null;
  54683. _this._hdrCurrentLuminance = 1.0;
  54684. // Getters and setters
  54685. _this._bloomEnabled = true;
  54686. _this._depthOfFieldEnabled = false;
  54687. _this._vlsEnabled = false;
  54688. _this._lensFlareEnabled = false;
  54689. _this._hdrEnabled = false;
  54690. _this._motionBlurEnabled = false;
  54691. _this._motionBlurSamples = 64.0;
  54692. _this._volumetricLightStepsCount = 50.0;
  54693. _this._cameras = cameras || [];
  54694. // Initialize
  54695. _this._scene = scene;
  54696. _this._basePostProcess = originalPostProcess;
  54697. _this._ratio = ratio;
  54698. // Misc
  54699. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54700. // Finish
  54701. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54702. _this._buildPipeline();
  54703. return _this;
  54704. }
  54705. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  54706. get: function () {
  54707. return this._bloomEnabled;
  54708. },
  54709. set: function (enabled) {
  54710. if (this._bloomEnabled === enabled) {
  54711. return;
  54712. }
  54713. this._bloomEnabled = enabled;
  54714. this._buildPipeline();
  54715. },
  54716. enumerable: true,
  54717. configurable: true
  54718. });
  54719. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54720. get: function () {
  54721. return this._depthOfFieldEnabled;
  54722. },
  54723. set: function (enabled) {
  54724. if (this._depthOfFieldEnabled === enabled) {
  54725. return;
  54726. }
  54727. this._depthOfFieldEnabled = enabled;
  54728. this._buildPipeline();
  54729. },
  54730. enumerable: true,
  54731. configurable: true
  54732. });
  54733. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54734. get: function () {
  54735. return this._lensFlareEnabled;
  54736. },
  54737. set: function (enabled) {
  54738. if (this._lensFlareEnabled === enabled) {
  54739. return;
  54740. }
  54741. this._lensFlareEnabled = enabled;
  54742. this._buildPipeline();
  54743. },
  54744. enumerable: true,
  54745. configurable: true
  54746. });
  54747. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  54748. get: function () {
  54749. return this._hdrEnabled;
  54750. },
  54751. set: function (enabled) {
  54752. if (this._hdrEnabled === enabled) {
  54753. return;
  54754. }
  54755. this._hdrEnabled = enabled;
  54756. this._buildPipeline();
  54757. },
  54758. enumerable: true,
  54759. configurable: true
  54760. });
  54761. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  54762. get: function () {
  54763. return this._vlsEnabled;
  54764. },
  54765. set: function (enabled) {
  54766. if (this._vlsEnabled === enabled) {
  54767. return;
  54768. }
  54769. if (enabled) {
  54770. var geometry = this._scene.enableGeometryBufferRenderer();
  54771. if (!geometry) {
  54772. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  54773. return;
  54774. }
  54775. }
  54776. this._vlsEnabled = enabled;
  54777. this._buildPipeline();
  54778. },
  54779. enumerable: true,
  54780. configurable: true
  54781. });
  54782. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  54783. get: function () {
  54784. return this._motionBlurEnabled;
  54785. },
  54786. set: function (enabled) {
  54787. if (this._motionBlurEnabled === enabled) {
  54788. return;
  54789. }
  54790. this._motionBlurEnabled = enabled;
  54791. this._buildPipeline();
  54792. },
  54793. enumerable: true,
  54794. configurable: true
  54795. });
  54796. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  54797. get: function () {
  54798. return this._volumetricLightStepsCount;
  54799. },
  54800. set: function (count) {
  54801. if (this.volumetricLightPostProcess) {
  54802. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  54803. }
  54804. this._volumetricLightStepsCount = count;
  54805. },
  54806. enumerable: true,
  54807. configurable: true
  54808. });
  54809. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  54810. get: function () {
  54811. return this._motionBlurSamples;
  54812. },
  54813. set: function (samples) {
  54814. if (this.motionBlurPostProcess) {
  54815. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  54816. }
  54817. this._motionBlurSamples = samples;
  54818. },
  54819. enumerable: true,
  54820. configurable: true
  54821. });
  54822. StandardRenderingPipeline.prototype._buildPipeline = function () {
  54823. var _this = this;
  54824. var ratio = this._ratio;
  54825. var scene = this._scene;
  54826. this._disposePostProcesses();
  54827. this._reset();
  54828. // Create pass post-process
  54829. if (!this._basePostProcess) {
  54830. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  54831. this.originalPostProcess.onApply = function (effect) {
  54832. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  54833. };
  54834. }
  54835. else {
  54836. this.originalPostProcess = this._basePostProcess;
  54837. }
  54838. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54839. this._currentDepthOfFieldSource = this.originalPostProcess;
  54840. if (this._vlsEnabled) {
  54841. // Create volumetric light
  54842. this._createVolumetricLightPostProcess(scene, ratio);
  54843. // Create volumetric light final post-process
  54844. 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);
  54845. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  54846. }
  54847. if (this._bloomEnabled) {
  54848. // Create down sample X4 post-process
  54849. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54850. // Create bright pass post-process
  54851. this._createBrightPassPostProcess(scene, ratio / 2);
  54852. // Create gaussian blur post-processes (down sampling blurs)
  54853. this._createBlurPostProcesses(scene, ratio / 4, 1);
  54854. // Create texture adder post-process
  54855. this._createTextureAdderPostProcess(scene, ratio);
  54856. // Create depth-of-field source post-process
  54857. 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);
  54858. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54859. }
  54860. if (this._lensFlareEnabled) {
  54861. // Create lens flare post-process
  54862. this._createLensFlarePostProcess(scene, ratio);
  54863. // Create depth-of-field source post-process post lens-flare and disable it now
  54864. 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);
  54865. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  54866. }
  54867. if (this._hdrEnabled) {
  54868. // Create luminance
  54869. this._createLuminancePostProcesses(scene, this._floatTextureType);
  54870. // Create HDR
  54871. this._createHdrPostProcess(scene, ratio);
  54872. // Create depth-of-field source post-process post hdr and disable it now
  54873. 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);
  54874. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  54875. }
  54876. if (this._depthOfFieldEnabled) {
  54877. // Create gaussian blur used by depth-of-field
  54878. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  54879. // Create depth-of-field post-process
  54880. this._createDepthOfFieldPostProcess(scene, ratio);
  54881. }
  54882. if (this._motionBlurEnabled) {
  54883. // Create motion blur post-process
  54884. this._createMotionBlurPostProcess(scene, ratio);
  54885. }
  54886. if (this._cameras !== null) {
  54887. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  54888. }
  54889. };
  54890. // Down Sample X4 Post-Processs
  54891. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54892. var _this = this;
  54893. var downSampleX4Offsets = new Array(32);
  54894. 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);
  54895. this.downSampleX4PostProcess.onApply = function (effect) {
  54896. var id = 0;
  54897. for (var i = -2; i < 2; i++) {
  54898. for (var j = -2; j < 2; j++) {
  54899. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54900. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54901. id += 2;
  54902. }
  54903. }
  54904. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54905. };
  54906. // Add to pipeline
  54907. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54908. };
  54909. // Brightpass Post-Process
  54910. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54911. var _this = this;
  54912. var brightOffsets = new Array(8);
  54913. 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);
  54914. this.brightPassPostProcess.onApply = function (effect) {
  54915. var sU = (1.0 / _this.brightPassPostProcess.width);
  54916. var sV = (1.0 / _this.brightPassPostProcess.height);
  54917. brightOffsets[0] = -0.5 * sU;
  54918. brightOffsets[1] = 0.5 * sV;
  54919. brightOffsets[2] = 0.5 * sU;
  54920. brightOffsets[3] = 0.5 * sV;
  54921. brightOffsets[4] = -0.5 * sU;
  54922. brightOffsets[5] = -0.5 * sV;
  54923. brightOffsets[6] = 0.5 * sU;
  54924. brightOffsets[7] = -0.5 * sV;
  54925. effect.setArray2("dsOffsets", brightOffsets);
  54926. effect.setFloat("brightThreshold", _this.brightThreshold);
  54927. };
  54928. // Add to pipeline
  54929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54930. };
  54931. // Create blur H&V post-processes
  54932. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  54933. var _this = this;
  54934. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  54935. var engine = scene.getEngine();
  54936. 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);
  54937. 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);
  54938. blurX.onActivateObservable.add(function () {
  54939. var dw = blurX.width / engine.getRenderingCanvas().width;
  54940. blurX.kernel = _this[blurWidthKey] * dw;
  54941. });
  54942. blurY.onActivateObservable.add(function () {
  54943. var dw = blurY.height / engine.getRenderingCanvas().height;
  54944. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  54945. });
  54946. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  54947. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  54948. this.blurHPostProcesses.push(blurX);
  54949. this.blurVPostProcesses.push(blurY);
  54950. };
  54951. // Create texture adder post-process
  54952. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54953. var _this = this;
  54954. 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);
  54955. this.textureAdderPostProcess.onApply = function (effect) {
  54956. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  54957. effect.setTexture("lensSampler", _this.lensTexture);
  54958. effect.setFloat("exposure", _this.exposure);
  54959. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  54960. };
  54961. // Add to pipeline
  54962. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54963. };
  54964. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  54965. var _this = this;
  54966. var geometryRenderer = scene.enableGeometryBufferRenderer();
  54967. geometryRenderer.enablePosition = true;
  54968. var geometry = geometryRenderer.getGBuffer();
  54969. // Base post-process
  54970. 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));
  54971. var depthValues = BABYLON.Vector2.Zero();
  54972. this.volumetricLightPostProcess.onApply = function (effect) {
  54973. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  54974. var generator = _this.sourceLight.getShadowGenerator();
  54975. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  54976. effect.setTexture("positionSampler", geometry.textures[2]);
  54977. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  54978. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  54979. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  54980. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  54981. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  54982. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  54983. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  54984. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  54985. effect.setVector2("depthValues", depthValues);
  54986. }
  54987. };
  54988. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  54989. // Smooth
  54990. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  54991. // Merge
  54992. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  54993. this.volumetricLightMergePostProces.onApply = function (effect) {
  54994. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  54995. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  54996. };
  54997. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  54998. };
  54999. // Create luminance
  55000. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  55001. var _this = this;
  55002. // Create luminance
  55003. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  55004. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  55005. var offsets = [];
  55006. this.luminancePostProcess.onApply = function (effect) {
  55007. var sU = (1.0 / _this.luminancePostProcess.width);
  55008. var sV = (1.0 / _this.luminancePostProcess.height);
  55009. offsets[0] = -0.5 * sU;
  55010. offsets[1] = 0.5 * sV;
  55011. offsets[2] = 0.5 * sU;
  55012. offsets[3] = 0.5 * sV;
  55013. offsets[4] = -0.5 * sU;
  55014. offsets[5] = -0.5 * sV;
  55015. offsets[6] = 0.5 * sU;
  55016. offsets[7] = -0.5 * sV;
  55017. effect.setArray2("lumOffsets", offsets);
  55018. };
  55019. // Add to pipeline
  55020. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  55021. // Create down sample luminance
  55022. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  55023. var size = Math.pow(3, i);
  55024. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  55025. if (i === 0) {
  55026. defines += "#define FINAL_DOWN_SAMPLER";
  55027. }
  55028. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  55029. this.luminanceDownSamplePostProcesses.push(postProcess);
  55030. }
  55031. // Create callbacks and add effects
  55032. var lastLuminance = this.luminancePostProcess;
  55033. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  55034. var downSampleOffsets = new Array(18);
  55035. pp.onApply = function (effect) {
  55036. var id = 0;
  55037. for (var x = -1; x < 2; x++) {
  55038. for (var y = -1; y < 2; y++) {
  55039. downSampleOffsets[id] = x / lastLuminance.width;
  55040. downSampleOffsets[id + 1] = y / lastLuminance.height;
  55041. id += 2;
  55042. }
  55043. }
  55044. effect.setArray2("dsOffsets", downSampleOffsets);
  55045. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  55046. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  55047. lastLuminance = _this.luminancePostProcess;
  55048. }
  55049. else {
  55050. lastLuminance = pp;
  55051. }
  55052. };
  55053. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  55054. pp.onAfterRender = function (effect) {
  55055. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  55056. 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);
  55057. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  55058. };
  55059. }
  55060. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  55061. });
  55062. };
  55063. // Create HDR post-process
  55064. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  55065. var _this = this;
  55066. 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);
  55067. var outputLiminance = 1;
  55068. var time = 0;
  55069. var lastTime = 0;
  55070. this.hdrPostProcess.onApply = function (effect) {
  55071. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  55072. time += scene.getEngine().getDeltaTime();
  55073. if (outputLiminance < 0) {
  55074. outputLiminance = _this._hdrCurrentLuminance;
  55075. }
  55076. else {
  55077. var dt = (lastTime - time) / 1000.0;
  55078. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  55079. outputLiminance += _this.hdrDecreaseRate * dt;
  55080. }
  55081. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  55082. outputLiminance -= _this.hdrIncreaseRate * dt;
  55083. }
  55084. else {
  55085. outputLiminance = _this._hdrCurrentLuminance;
  55086. }
  55087. }
  55088. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  55089. effect.setFloat("averageLuminance", outputLiminance);
  55090. lastTime = time;
  55091. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  55092. };
  55093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  55094. };
  55095. // Create lens flare post-process
  55096. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  55097. var _this = this;
  55098. 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);
  55099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  55100. this._createBlurPostProcesses(scene, ratio / 4, 2);
  55101. 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);
  55102. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  55103. var resolution = new BABYLON.Vector2(0, 0);
  55104. // Lens flare
  55105. this.lensFlarePostProcess.onApply = function (effect) {
  55106. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  55107. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  55108. effect.setFloat("strength", _this.lensFlareStrength);
  55109. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  55110. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  55111. // Shift
  55112. resolution.x = _this.lensFlarePostProcess.width;
  55113. resolution.y = _this.lensFlarePostProcess.height;
  55114. effect.setVector2("resolution", resolution);
  55115. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  55116. };
  55117. // Compose
  55118. 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);
  55119. 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);
  55120. this.lensFlareComposePostProcess.onApply = function (effect) {
  55121. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  55122. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  55123. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  55124. // Lens start rotation matrix
  55125. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  55126. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  55127. 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));
  55128. camRot *= 4.0;
  55129. 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);
  55130. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  55131. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  55132. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  55133. };
  55134. };
  55135. // Create depth-of-field post-process
  55136. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  55137. var _this = this;
  55138. 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);
  55139. this.depthOfFieldPostProcess.onApply = function (effect) {
  55140. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  55141. effect.setTexture("depthSampler", _this._getDepthTexture());
  55142. effect.setFloat("distance", _this.depthOfFieldDistance);
  55143. };
  55144. // Add to pipeline
  55145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  55146. };
  55147. // Create motion blur post-process
  55148. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  55149. var _this = this;
  55150. 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);
  55151. var motionScale = 0;
  55152. var prevViewProjection = BABYLON.Matrix.Identity();
  55153. var invViewProjection = BABYLON.Matrix.Identity();
  55154. var viewProjection = BABYLON.Matrix.Identity();
  55155. var screenSize = BABYLON.Vector2.Zero();
  55156. this.motionBlurPostProcess.onApply = function (effect) {
  55157. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  55158. viewProjection.invertToRef(invViewProjection);
  55159. effect.setMatrix("inverseViewProjection", invViewProjection);
  55160. effect.setMatrix("prevViewProjection", prevViewProjection);
  55161. prevViewProjection = viewProjection;
  55162. screenSize.x = _this.motionBlurPostProcess.width;
  55163. screenSize.y = _this.motionBlurPostProcess.height;
  55164. effect.setVector2("screenSize", screenSize);
  55165. motionScale = scene.getEngine().getFps() / 60.0;
  55166. effect.setFloat("motionScale", motionScale);
  55167. effect.setFloat("motionStrength", _this.motionStrength);
  55168. effect.setTexture("depthSampler", _this._getDepthTexture());
  55169. };
  55170. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  55171. };
  55172. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  55173. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  55174. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  55175. }
  55176. return this._scene.enableDepthRenderer().getDepthMap();
  55177. };
  55178. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  55179. for (var i = 0; i < this._cameras.length; i++) {
  55180. var camera = this._cameras[i];
  55181. if (this.originalPostProcess) {
  55182. this.originalPostProcess.dispose(camera);
  55183. }
  55184. if (this.downSampleX4PostProcess) {
  55185. this.downSampleX4PostProcess.dispose(camera);
  55186. }
  55187. if (this.brightPassPostProcess) {
  55188. this.brightPassPostProcess.dispose(camera);
  55189. }
  55190. if (this.textureAdderPostProcess) {
  55191. this.textureAdderPostProcess.dispose(camera);
  55192. }
  55193. if (this.textureAdderFinalPostProcess) {
  55194. this.textureAdderFinalPostProcess.dispose(camera);
  55195. }
  55196. if (this.volumetricLightPostProcess) {
  55197. this.volumetricLightPostProcess.dispose(camera);
  55198. }
  55199. if (this.volumetricLightSmoothXPostProcess) {
  55200. this.volumetricLightSmoothXPostProcess.dispose(camera);
  55201. }
  55202. if (this.volumetricLightSmoothYPostProcess) {
  55203. this.volumetricLightSmoothYPostProcess.dispose(camera);
  55204. }
  55205. if (this.volumetricLightMergePostProces) {
  55206. this.volumetricLightMergePostProces.dispose(camera);
  55207. }
  55208. if (this.volumetricLightFinalPostProcess) {
  55209. this.volumetricLightFinalPostProcess.dispose(camera);
  55210. }
  55211. if (this.lensFlarePostProcess) {
  55212. this.lensFlarePostProcess.dispose(camera);
  55213. }
  55214. if (this.lensFlareComposePostProcess) {
  55215. this.lensFlareComposePostProcess.dispose(camera);
  55216. }
  55217. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  55218. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  55219. }
  55220. if (this.luminancePostProcess) {
  55221. this.luminancePostProcess.dispose(camera);
  55222. }
  55223. if (this.hdrPostProcess) {
  55224. this.hdrPostProcess.dispose(camera);
  55225. }
  55226. if (this.hdrFinalPostProcess) {
  55227. this.hdrFinalPostProcess.dispose(camera);
  55228. }
  55229. if (this.depthOfFieldPostProcess) {
  55230. this.depthOfFieldPostProcess.dispose(camera);
  55231. }
  55232. if (this.motionBlurPostProcess) {
  55233. this.motionBlurPostProcess.dispose(camera);
  55234. }
  55235. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  55236. this.blurHPostProcesses[j].dispose(camera);
  55237. }
  55238. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  55239. this.blurVPostProcesses[j].dispose(camera);
  55240. }
  55241. }
  55242. this.originalPostProcess = null;
  55243. this.downSampleX4PostProcess = null;
  55244. this.brightPassPostProcess = null;
  55245. this.textureAdderPostProcess = null;
  55246. this.textureAdderFinalPostProcess = null;
  55247. this.volumetricLightPostProcess = null;
  55248. this.volumetricLightSmoothXPostProcess = null;
  55249. this.volumetricLightSmoothYPostProcess = null;
  55250. this.volumetricLightMergePostProces = null;
  55251. this.volumetricLightFinalPostProcess = null;
  55252. this.lensFlarePostProcess = null;
  55253. this.lensFlareComposePostProcess = null;
  55254. this.luminancePostProcess = null;
  55255. this.hdrPostProcess = null;
  55256. this.hdrFinalPostProcess = null;
  55257. this.depthOfFieldPostProcess = null;
  55258. this.motionBlurPostProcess = null;
  55259. this.luminanceDownSamplePostProcesses = [];
  55260. this.blurHPostProcesses = [];
  55261. this.blurVPostProcesses = [];
  55262. };
  55263. // Dispose
  55264. StandardRenderingPipeline.prototype.dispose = function () {
  55265. this._disposePostProcesses();
  55266. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  55267. _super.prototype.dispose.call(this);
  55268. };
  55269. // Serialize rendering pipeline
  55270. StandardRenderingPipeline.prototype.serialize = function () {
  55271. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55272. serializationObject.customType = "StandardRenderingPipeline";
  55273. return serializationObject;
  55274. };
  55275. /**
  55276. * Static members
  55277. */
  55278. // Parse serialized pipeline
  55279. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  55280. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  55281. };
  55282. // Luminance steps
  55283. StandardRenderingPipeline.LuminanceSteps = 6;
  55284. __decorate([
  55285. BABYLON.serialize()
  55286. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  55287. __decorate([
  55288. BABYLON.serialize()
  55289. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  55290. __decorate([
  55291. BABYLON.serialize()
  55292. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  55293. __decorate([
  55294. BABYLON.serialize()
  55295. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  55296. __decorate([
  55297. BABYLON.serializeAsTexture("lensTexture")
  55298. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  55299. __decorate([
  55300. BABYLON.serialize()
  55301. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  55302. __decorate([
  55303. BABYLON.serialize()
  55304. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  55305. __decorate([
  55306. BABYLON.serialize()
  55307. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  55308. __decorate([
  55309. BABYLON.serialize()
  55310. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  55311. __decorate([
  55312. BABYLON.serialize()
  55313. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  55314. __decorate([
  55315. BABYLON.serialize()
  55316. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  55317. __decorate([
  55318. BABYLON.serializeAsTexture("lensColorTexture")
  55319. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  55320. __decorate([
  55321. BABYLON.serialize()
  55322. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  55323. __decorate([
  55324. BABYLON.serialize()
  55325. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  55326. __decorate([
  55327. BABYLON.serialize()
  55328. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  55329. __decorate([
  55330. BABYLON.serialize()
  55331. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  55332. __decorate([
  55333. BABYLON.serializeAsTexture("lensStarTexture")
  55334. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  55335. __decorate([
  55336. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  55337. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  55338. __decorate([
  55339. BABYLON.serialize()
  55340. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  55341. __decorate([
  55342. BABYLON.serialize()
  55343. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  55344. __decorate([
  55345. BABYLON.serialize()
  55346. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  55347. __decorate([
  55348. BABYLON.serialize()
  55349. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  55350. __decorate([
  55351. BABYLON.serialize()
  55352. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  55353. __decorate([
  55354. BABYLON.serialize()
  55355. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  55356. __decorate([
  55357. BABYLON.serialize()
  55358. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  55359. __decorate([
  55360. BABYLON.serialize()
  55361. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  55362. __decorate([
  55363. BABYLON.serialize()
  55364. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  55365. __decorate([
  55366. BABYLON.serialize()
  55367. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  55368. __decorate([
  55369. BABYLON.serialize()
  55370. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  55371. return StandardRenderingPipeline;
  55372. }(BABYLON.PostProcessRenderPipeline));
  55373. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  55374. })(BABYLON || (BABYLON = {}));
  55375. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  55376. var BABYLON;
  55377. (function (BABYLON) {
  55378. var FxaaPostProcess = (function (_super) {
  55379. __extends(FxaaPostProcess, _super);
  55380. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55381. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55382. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  55383. _this.onApplyObservable.add(function (effect) {
  55384. var texelSize = _this.texelSize;
  55385. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  55386. });
  55387. return _this;
  55388. }
  55389. return FxaaPostProcess;
  55390. }(BABYLON.PostProcess));
  55391. BABYLON.FxaaPostProcess = FxaaPostProcess;
  55392. })(BABYLON || (BABYLON = {}));
  55393. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  55394. var BABYLON;
  55395. (function (BABYLON) {
  55396. var DefaultRenderingPipeline = (function (_super) {
  55397. __extends(DefaultRenderingPipeline, _super);
  55398. /**
  55399. * @constructor
  55400. * @param {string} name - The rendering pipeline name
  55401. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55402. * @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)
  55403. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55404. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  55405. */
  55406. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  55407. if (automaticBuild === void 0) { automaticBuild = true; }
  55408. var _this = _super.call(this, scene.getEngine(), name) || this;
  55409. _this.PassPostProcessId = "PassPostProcessEffect";
  55410. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  55411. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  55412. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  55413. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  55414. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  55415. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  55416. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  55417. // IAnimatable
  55418. _this.animations = [];
  55419. // Values
  55420. _this._bloomEnabled = false;
  55421. _this._fxaaEnabled = false;
  55422. _this._imageProcessingEnabled = true;
  55423. _this._bloomScale = 0.6;
  55424. _this._buildAllowed = true;
  55425. /**
  55426. * Specifies the size of the bloom blur kernel, relative to the final output size
  55427. */
  55428. _this.bloomKernel = 64;
  55429. /**
  55430. * Specifies the weight of the bloom in the final rendering
  55431. */
  55432. _this._bloomWeight = 0.15;
  55433. _this._cameras = cameras || [];
  55434. _this._buildAllowed = automaticBuild;
  55435. // Initialize
  55436. _this._scene = scene;
  55437. var caps = _this._scene.getEngine().getCaps();
  55438. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  55439. // Misc
  55440. if (_this._hdr) {
  55441. if (caps.textureHalfFloatRender) {
  55442. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55443. }
  55444. else if (caps.textureFloatRender) {
  55445. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55446. }
  55447. }
  55448. else {
  55449. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55450. }
  55451. // Attach
  55452. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55453. _this._buildPipeline();
  55454. return _this;
  55455. }
  55456. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  55457. get: function () {
  55458. return this._bloomWeight;
  55459. },
  55460. set: function (value) {
  55461. if (this._bloomWeight === value) {
  55462. return;
  55463. }
  55464. this._bloomWeight = value;
  55465. if (this._hdr && this.copyBack) {
  55466. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  55467. }
  55468. },
  55469. enumerable: true,
  55470. configurable: true
  55471. });
  55472. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  55473. get: function () {
  55474. return this._bloomScale;
  55475. },
  55476. set: function (value) {
  55477. if (this._bloomScale === value) {
  55478. return;
  55479. }
  55480. this._bloomScale = value;
  55481. this._buildPipeline();
  55482. },
  55483. enumerable: true,
  55484. configurable: true
  55485. });
  55486. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  55487. get: function () {
  55488. return this._bloomEnabled;
  55489. },
  55490. set: function (enabled) {
  55491. if (this._bloomEnabled === enabled) {
  55492. return;
  55493. }
  55494. this._bloomEnabled = enabled;
  55495. this._buildPipeline();
  55496. },
  55497. enumerable: true,
  55498. configurable: true
  55499. });
  55500. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  55501. get: function () {
  55502. return this._fxaaEnabled;
  55503. },
  55504. set: function (enabled) {
  55505. if (this._fxaaEnabled === enabled) {
  55506. return;
  55507. }
  55508. this._fxaaEnabled = enabled;
  55509. this._buildPipeline();
  55510. },
  55511. enumerable: true,
  55512. configurable: true
  55513. });
  55514. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  55515. get: function () {
  55516. return this._imageProcessingEnabled;
  55517. },
  55518. set: function (enabled) {
  55519. if (this._imageProcessingEnabled === enabled) {
  55520. return;
  55521. }
  55522. this._imageProcessingEnabled = enabled;
  55523. this._buildPipeline();
  55524. },
  55525. enumerable: true,
  55526. configurable: true
  55527. });
  55528. /**
  55529. * Force the compilation of the entire pipeline.
  55530. */
  55531. DefaultRenderingPipeline.prototype.prepare = function () {
  55532. var previousState = this._buildAllowed;
  55533. this._buildAllowed = true;
  55534. this._buildPipeline();
  55535. this._buildAllowed = previousState;
  55536. };
  55537. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  55538. var _this = this;
  55539. if (!this._buildAllowed) {
  55540. return;
  55541. }
  55542. var engine = this._scene.getEngine();
  55543. this._disposePostProcesses();
  55544. this._reset();
  55545. if (this.bloomEnabled) {
  55546. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55547. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  55548. if (!this._hdr) {
  55549. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55550. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  55551. this.highlights.autoClear = false;
  55552. this.highlights.alwaysForcePOT = true;
  55553. }
  55554. 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);
  55555. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  55556. this.blurX.alwaysForcePOT = true;
  55557. this.blurX.autoClear = false;
  55558. this.blurX.onActivateObservable.add(function () {
  55559. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  55560. _this.blurX.kernel = _this.bloomKernel * dw;
  55561. });
  55562. 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);
  55563. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  55564. this.blurY.alwaysForcePOT = true;
  55565. this.blurY.autoClear = false;
  55566. this.blurY.onActivateObservable.add(function () {
  55567. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  55568. _this.blurY.kernel = _this.bloomKernel * dh;
  55569. });
  55570. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55571. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  55572. this.copyBack.alwaysForcePOT = true;
  55573. if (this._hdr) {
  55574. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  55575. var w = this.bloomWeight;
  55576. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  55577. }
  55578. else {
  55579. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  55580. }
  55581. this.copyBack.autoClear = false;
  55582. }
  55583. if (this._imageProcessingEnabled) {
  55584. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55585. if (this._hdr) {
  55586. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  55587. }
  55588. else {
  55589. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  55590. }
  55591. }
  55592. if (this.fxaaEnabled) {
  55593. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55594. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  55595. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  55596. }
  55597. else {
  55598. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  55599. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  55600. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  55601. }
  55602. if (this.bloomEnabled) {
  55603. if (this._hdr) {
  55604. this.copyBack.shareOutputWith(this.blurX);
  55605. if (this.imageProcessing) {
  55606. this.imageProcessing.shareOutputWith(this.pass);
  55607. this.imageProcessing.autoClear = false;
  55608. }
  55609. else if (this.fxaa) {
  55610. this.fxaa.shareOutputWith(this.pass);
  55611. }
  55612. else {
  55613. this.finalMerge.shareOutputWith(this.pass);
  55614. }
  55615. }
  55616. else {
  55617. if (this.fxaa) {
  55618. this.fxaa.shareOutputWith(this.pass);
  55619. }
  55620. else {
  55621. this.finalMerge.shareOutputWith(this.pass);
  55622. }
  55623. }
  55624. }
  55625. if (this._cameras !== null) {
  55626. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  55627. }
  55628. };
  55629. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  55630. for (var i = 0; i < this._cameras.length; i++) {
  55631. var camera = this._cameras[i];
  55632. if (this.pass) {
  55633. this.pass.dispose(camera);
  55634. }
  55635. if (this.highlights) {
  55636. this.highlights.dispose(camera);
  55637. }
  55638. if (this.blurX) {
  55639. this.blurX.dispose(camera);
  55640. }
  55641. if (this.blurY) {
  55642. this.blurY.dispose(camera);
  55643. }
  55644. if (this.copyBack) {
  55645. this.copyBack.dispose(camera);
  55646. }
  55647. if (this.imageProcessing) {
  55648. this.imageProcessing.dispose(camera);
  55649. }
  55650. if (this.fxaa) {
  55651. this.fxaa.dispose(camera);
  55652. }
  55653. if (this.finalMerge) {
  55654. this.finalMerge.dispose(camera);
  55655. }
  55656. }
  55657. this.pass = null;
  55658. this.highlights = null;
  55659. this.blurX = null;
  55660. this.blurY = null;
  55661. this.copyBack = null;
  55662. this.imageProcessing = null;
  55663. this.fxaa = null;
  55664. this.finalMerge = null;
  55665. };
  55666. // Dispose
  55667. DefaultRenderingPipeline.prototype.dispose = function () {
  55668. this._disposePostProcesses();
  55669. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  55670. _super.prototype.dispose.call(this);
  55671. };
  55672. // Serialize rendering pipeline
  55673. DefaultRenderingPipeline.prototype.serialize = function () {
  55674. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55675. serializationObject.customType = "DefaultRenderingPipeline";
  55676. return serializationObject;
  55677. };
  55678. // Parse serialized pipeline
  55679. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  55680. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  55681. };
  55682. __decorate([
  55683. BABYLON.serialize()
  55684. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  55685. __decorate([
  55686. BABYLON.serialize()
  55687. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  55688. __decorate([
  55689. BABYLON.serialize()
  55690. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  55691. __decorate([
  55692. BABYLON.serialize()
  55693. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  55694. __decorate([
  55695. BABYLON.serialize()
  55696. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  55697. __decorate([
  55698. BABYLON.serialize()
  55699. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  55700. __decorate([
  55701. BABYLON.serialize()
  55702. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  55703. __decorate([
  55704. BABYLON.serialize()
  55705. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  55706. return DefaultRenderingPipeline;
  55707. }(BABYLON.PostProcessRenderPipeline));
  55708. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  55709. })(BABYLON || (BABYLON = {}));
  55710. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  55711. var BABYLON;
  55712. (function (BABYLON) {
  55713. var GeometryBufferRenderer = (function () {
  55714. function GeometryBufferRenderer(scene, ratio) {
  55715. if (ratio === void 0) { ratio = 1; }
  55716. this._viewMatrix = BABYLON.Matrix.Zero();
  55717. this._projectionMatrix = BABYLON.Matrix.Zero();
  55718. this._transformMatrix = BABYLON.Matrix.Zero();
  55719. this._worldViewProjection = BABYLON.Matrix.Zero();
  55720. this._enablePosition = false;
  55721. this._scene = scene;
  55722. this._ratio = ratio;
  55723. // Render target
  55724. this._createRenderTargets();
  55725. }
  55726. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  55727. set: function (meshes) {
  55728. this._multiRenderTarget.renderList = meshes;
  55729. },
  55730. enumerable: true,
  55731. configurable: true
  55732. });
  55733. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  55734. get: function () {
  55735. return this._multiRenderTarget.isSupported;
  55736. },
  55737. enumerable: true,
  55738. configurable: true
  55739. });
  55740. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  55741. get: function () {
  55742. return this._enablePosition;
  55743. },
  55744. set: function (enable) {
  55745. this._enablePosition = enable;
  55746. this.dispose();
  55747. this._createRenderTargets();
  55748. },
  55749. enumerable: true,
  55750. configurable: true
  55751. });
  55752. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  55753. var material = subMesh.getMaterial();
  55754. if (material && material.disableDepthWrite) {
  55755. return false;
  55756. }
  55757. var defines = [];
  55758. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  55759. var mesh = subMesh.getMesh();
  55760. var scene = mesh.getScene();
  55761. // Alpha test
  55762. if (material && material.needAlphaTesting()) {
  55763. defines.push("#define ALPHATEST");
  55764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55765. attribs.push(BABYLON.VertexBuffer.UVKind);
  55766. defines.push("#define UV1");
  55767. }
  55768. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55769. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55770. defines.push("#define UV2");
  55771. }
  55772. }
  55773. // Buffers
  55774. if (this._enablePosition) {
  55775. defines.push("#define POSITION");
  55776. }
  55777. // Bones
  55778. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55779. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55780. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55781. if (mesh.numBoneInfluencers > 4) {
  55782. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55783. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55784. }
  55785. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55786. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55787. }
  55788. else {
  55789. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55790. }
  55791. // Instances
  55792. if (useInstances) {
  55793. defines.push("#define INSTANCES");
  55794. attribs.push("world0");
  55795. attribs.push("world1");
  55796. attribs.push("world2");
  55797. attribs.push("world3");
  55798. }
  55799. // Get correct effect
  55800. var join = defines.join("\n");
  55801. if (this._cachedDefines !== join) {
  55802. this._cachedDefines = join;
  55803. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  55804. }
  55805. return this._effect.isReady();
  55806. };
  55807. GeometryBufferRenderer.prototype.getGBuffer = function () {
  55808. return this._multiRenderTarget;
  55809. };
  55810. // Methods
  55811. GeometryBufferRenderer.prototype.dispose = function () {
  55812. this.getGBuffer().dispose();
  55813. };
  55814. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  55815. var _this = this;
  55816. var engine = this._scene.getEngine();
  55817. var count = this._enablePosition ? 3 : 2;
  55818. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  55819. if (!this.isSupported) {
  55820. return null;
  55821. }
  55822. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55823. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55824. this._multiRenderTarget.refreshRate = 1;
  55825. this._multiRenderTarget.renderParticles = false;
  55826. this._multiRenderTarget.renderList = null;
  55827. // set default depth value to 1.0 (far away)
  55828. this._multiRenderTarget.onClearObservable.add(function (engine) {
  55829. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  55830. });
  55831. // Custom render function
  55832. var renderSubMesh = function (subMesh) {
  55833. var mesh = subMesh.getRenderingMesh();
  55834. var scene = _this._scene;
  55835. var engine = scene.getEngine();
  55836. // Culling
  55837. engine.setState(subMesh.getMaterial().backFaceCulling);
  55838. // Managing instances
  55839. var batch = mesh._getInstancesRenderList(subMesh._id);
  55840. if (batch.mustReturn) {
  55841. return;
  55842. }
  55843. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55844. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55845. engine.enableEffect(_this._effect);
  55846. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55847. var material = subMesh.getMaterial();
  55848. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55849. _this._effect.setMatrix("view", scene.getViewMatrix());
  55850. // Alpha test
  55851. if (material && material.needAlphaTesting()) {
  55852. var alphaTexture = material.getAlphaTestTexture();
  55853. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55854. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55855. }
  55856. // Bones
  55857. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55858. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55859. }
  55860. // Draw
  55861. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55862. }
  55863. };
  55864. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55865. var index;
  55866. if (depthOnlySubMeshes.length) {
  55867. engine.setColorWrite(false);
  55868. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55869. renderSubMesh(depthOnlySubMeshes.data[index]);
  55870. }
  55871. engine.setColorWrite(true);
  55872. }
  55873. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55874. renderSubMesh(opaqueSubMeshes.data[index]);
  55875. }
  55876. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55877. renderSubMesh(alphaTestSubMeshes.data[index]);
  55878. }
  55879. };
  55880. };
  55881. return GeometryBufferRenderer;
  55882. }());
  55883. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  55884. })(BABYLON || (BABYLON = {}));
  55885. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  55886. var BABYLON;
  55887. (function (BABYLON) {
  55888. var RefractionPostProcess = (function (_super) {
  55889. __extends(RefractionPostProcess, _super);
  55890. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  55891. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  55892. _this.color = color;
  55893. _this.depth = depth;
  55894. _this.colorLevel = colorLevel;
  55895. _this.onActivateObservable.add(function (cam) {
  55896. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  55897. });
  55898. _this.onApplyObservable.add(function (effect) {
  55899. effect.setColor3("baseColor", _this.color);
  55900. effect.setFloat("depth", _this.depth);
  55901. effect.setFloat("colorLevel", _this.colorLevel);
  55902. effect.setTexture("refractionSampler", _this._refRexture);
  55903. });
  55904. return _this;
  55905. }
  55906. // Methods
  55907. RefractionPostProcess.prototype.dispose = function (camera) {
  55908. if (this._refRexture) {
  55909. this._refRexture.dispose();
  55910. }
  55911. _super.prototype.dispose.call(this, camera);
  55912. };
  55913. return RefractionPostProcess;
  55914. }(BABYLON.PostProcess));
  55915. BABYLON.RefractionPostProcess = RefractionPostProcess;
  55916. })(BABYLON || (BABYLON = {}));
  55917. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  55918. var BABYLON;
  55919. (function (BABYLON) {
  55920. var BlackAndWhitePostProcess = (function (_super) {
  55921. __extends(BlackAndWhitePostProcess, _super);
  55922. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  55923. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  55924. _this.degree = 1;
  55925. _this.onApplyObservable.add(function (effect) {
  55926. effect.setFloat("degree", _this.degree);
  55927. });
  55928. return _this;
  55929. }
  55930. return BlackAndWhitePostProcess;
  55931. }(BABYLON.PostProcess));
  55932. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  55933. })(BABYLON || (BABYLON = {}));
  55934. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  55935. var BABYLON;
  55936. (function (BABYLON) {
  55937. var ConvolutionPostProcess = (function (_super) {
  55938. __extends(ConvolutionPostProcess, _super);
  55939. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  55940. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  55941. _this.kernel = kernel;
  55942. _this.onApply = function (effect) {
  55943. effect.setFloat2("screenSize", _this.width, _this.height);
  55944. effect.setArray("kernel", _this.kernel);
  55945. };
  55946. return _this;
  55947. }
  55948. // Statics
  55949. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  55950. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  55951. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  55952. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  55953. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  55954. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  55955. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  55956. return ConvolutionPostProcess;
  55957. }(BABYLON.PostProcess));
  55958. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  55959. })(BABYLON || (BABYLON = {}));
  55960. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  55961. var BABYLON;
  55962. (function (BABYLON) {
  55963. var FilterPostProcess = (function (_super) {
  55964. __extends(FilterPostProcess, _super);
  55965. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  55966. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  55967. _this.kernelMatrix = kernelMatrix;
  55968. _this.onApply = function (effect) {
  55969. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  55970. };
  55971. return _this;
  55972. }
  55973. return FilterPostProcess;
  55974. }(BABYLON.PostProcess));
  55975. BABYLON.FilterPostProcess = FilterPostProcess;
  55976. })(BABYLON || (BABYLON = {}));
  55977. //# sourceMappingURL=babylon.filterPostProcess.js.map
  55978. var BABYLON;
  55979. (function (BABYLON) {
  55980. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55981. var VolumetricLightScatteringPostProcess = (function (_super) {
  55982. __extends(VolumetricLightScatteringPostProcess, _super);
  55983. /**
  55984. * @constructor
  55985. * @param {string} name - The post-process name
  55986. * @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)
  55987. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55988. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55989. * @param {number} samples - The post-process quality, default 100
  55990. * @param {number} samplingMode - The post-process filtering mode
  55991. * @param {BABYLON.Engine} engine - The babylon engine
  55992. * @param {boolean} reusable - If the post-process is reusable
  55993. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55994. */
  55995. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55996. if (samples === void 0) { samples = 100; }
  55997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55998. 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;
  55999. _this._screenCoordinates = BABYLON.Vector2.Zero();
  56000. /**
  56001. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  56002. * @type {Vector3}
  56003. */
  56004. _this.customMeshPosition = BABYLON.Vector3.Zero();
  56005. /**
  56006. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  56007. * @type {boolean}
  56008. */
  56009. _this.useCustomMeshPosition = false;
  56010. /**
  56011. * If the post-process should inverse the light scattering direction
  56012. * @type {boolean}
  56013. */
  56014. _this.invert = true;
  56015. /**
  56016. * Array containing the excluded meshes not rendered in the internal pass
  56017. */
  56018. _this.excludedMeshes = new Array();
  56019. /**
  56020. * Controls the overall intensity of the post-process
  56021. * @type {number}
  56022. */
  56023. _this.exposure = 0.3;
  56024. /**
  56025. * Dissipates each sample's contribution in range [0, 1]
  56026. * @type {number}
  56027. */
  56028. _this.decay = 0.96815;
  56029. /**
  56030. * Controls the overall intensity of each sample
  56031. * @type {number}
  56032. */
  56033. _this.weight = 0.58767;
  56034. /**
  56035. * Controls the density of each sample
  56036. * @type {number}
  56037. */
  56038. _this.density = 0.926;
  56039. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  56040. var engine = scene.getEngine();
  56041. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  56042. // Configure mesh
  56043. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  56044. // Configure
  56045. _this._createPass(scene, ratio.passRatio || ratio);
  56046. _this.onActivate = function (camera) {
  56047. if (!_this.isSupported) {
  56048. _this.dispose(camera);
  56049. }
  56050. _this.onActivate = null;
  56051. };
  56052. _this.onApplyObservable.add(function (effect) {
  56053. _this._updateMeshScreenCoordinates(scene);
  56054. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  56055. effect.setFloat("exposure", _this.exposure);
  56056. effect.setFloat("decay", _this.decay);
  56057. effect.setFloat("weight", _this.weight);
  56058. effect.setFloat("density", _this.density);
  56059. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  56060. });
  56061. return _this;
  56062. }
  56063. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  56064. get: function () {
  56065. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  56066. return false;
  56067. },
  56068. set: function (useDiffuseColor) {
  56069. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  56070. },
  56071. enumerable: true,
  56072. configurable: true
  56073. });
  56074. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  56075. return "VolumetricLightScatteringPostProcess";
  56076. };
  56077. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  56078. var mesh = subMesh.getMesh();
  56079. // Render this.mesh as default
  56080. if (mesh === this.mesh) {
  56081. return mesh.material.isReady(mesh);
  56082. }
  56083. var defines = [];
  56084. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56085. var material = subMesh.getMaterial();
  56086. var needUV = false;
  56087. // Alpha test
  56088. if (material) {
  56089. if (material.needAlphaTesting()) {
  56090. defines.push("#define ALPHATEST");
  56091. }
  56092. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56093. attribs.push(BABYLON.VertexBuffer.UVKind);
  56094. defines.push("#define UV1");
  56095. }
  56096. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56097. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56098. defines.push("#define UV2");
  56099. }
  56100. }
  56101. // Bones
  56102. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56103. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56104. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56105. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56106. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56107. }
  56108. else {
  56109. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56110. }
  56111. // Instances
  56112. if (useInstances) {
  56113. defines.push("#define INSTANCES");
  56114. attribs.push("world0");
  56115. attribs.push("world1");
  56116. attribs.push("world2");
  56117. attribs.push("world3");
  56118. }
  56119. // Get correct effect
  56120. var join = defines.join("\n");
  56121. if (this._cachedDefines !== join) {
  56122. this._cachedDefines = join;
  56123. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  56124. }
  56125. return this._volumetricLightScatteringPass.isReady();
  56126. };
  56127. /**
  56128. * Sets the new light position for light scattering effect
  56129. * @param {BABYLON.Vector3} The new custom light position
  56130. */
  56131. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  56132. this.customMeshPosition = position;
  56133. };
  56134. /**
  56135. * Returns the light position for light scattering effect
  56136. * @return {BABYLON.Vector3} The custom light position
  56137. */
  56138. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  56139. return this.customMeshPosition;
  56140. };
  56141. /**
  56142. * Disposes the internal assets and detaches the post-process from the camera
  56143. */
  56144. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  56145. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  56146. if (rttIndex !== -1) {
  56147. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  56148. }
  56149. this._volumetricLightScatteringRTT.dispose();
  56150. _super.prototype.dispose.call(this, camera);
  56151. };
  56152. /**
  56153. * Returns the render target texture used by the post-process
  56154. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  56155. */
  56156. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  56157. return this._volumetricLightScatteringRTT;
  56158. };
  56159. // Private methods
  56160. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  56161. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  56162. return true;
  56163. }
  56164. return false;
  56165. };
  56166. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  56167. var _this = this;
  56168. var engine = scene.getEngine();
  56169. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56170. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56171. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56172. this._volumetricLightScatteringRTT.renderList = null;
  56173. this._volumetricLightScatteringRTT.renderParticles = false;
  56174. var camera = this.getCamera();
  56175. if (camera) {
  56176. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  56177. }
  56178. else {
  56179. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  56180. }
  56181. // Custom render function for submeshes
  56182. var renderSubMesh = function (subMesh) {
  56183. var mesh = subMesh.getRenderingMesh();
  56184. if (_this._meshExcluded(mesh)) {
  56185. return;
  56186. }
  56187. var scene = mesh.getScene();
  56188. var engine = scene.getEngine();
  56189. // Culling
  56190. engine.setState(subMesh.getMaterial().backFaceCulling);
  56191. // Managing instances
  56192. var batch = mesh._getInstancesRenderList(subMesh._id);
  56193. if (batch.mustReturn) {
  56194. return;
  56195. }
  56196. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56197. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  56198. var effect = _this._volumetricLightScatteringPass;
  56199. if (mesh === _this.mesh) {
  56200. if (subMesh.effect) {
  56201. effect = subMesh.effect;
  56202. }
  56203. else {
  56204. effect = subMesh.getMaterial().getEffect();
  56205. }
  56206. }
  56207. engine.enableEffect(effect);
  56208. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  56209. if (mesh === _this.mesh) {
  56210. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  56211. }
  56212. else {
  56213. var material = subMesh.getMaterial();
  56214. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  56215. // Alpha test
  56216. if (material && material.needAlphaTesting()) {
  56217. var alphaTexture = material.getAlphaTestTexture();
  56218. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  56219. if (alphaTexture) {
  56220. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56221. }
  56222. }
  56223. // Bones
  56224. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56225. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56226. }
  56227. }
  56228. // Draw
  56229. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  56230. }
  56231. };
  56232. // Render target texture callbacks
  56233. var savedSceneClearColor;
  56234. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  56235. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  56236. savedSceneClearColor = scene.clearColor;
  56237. scene.clearColor = sceneClearColor;
  56238. });
  56239. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  56240. scene.clearColor = savedSceneClearColor;
  56241. });
  56242. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56243. var engine = scene.getEngine();
  56244. var index;
  56245. if (depthOnlySubMeshes.length) {
  56246. engine.setColorWrite(false);
  56247. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56248. renderSubMesh(depthOnlySubMeshes.data[index]);
  56249. }
  56250. engine.setColorWrite(true);
  56251. }
  56252. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56253. renderSubMesh(opaqueSubMeshes.data[index]);
  56254. }
  56255. engine.setAlphaTesting(true);
  56256. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56257. renderSubMesh(alphaTestSubMeshes.data[index]);
  56258. }
  56259. engine.setAlphaTesting(false);
  56260. if (transparentSubMeshes.length) {
  56261. // Sort sub meshes
  56262. for (index = 0; index < transparentSubMeshes.length; index++) {
  56263. var submesh = transparentSubMeshes.data[index];
  56264. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  56265. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  56266. }
  56267. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  56268. sortedArray.sort(function (a, b) {
  56269. // Alpha index first
  56270. if (a._alphaIndex > b._alphaIndex) {
  56271. return 1;
  56272. }
  56273. if (a._alphaIndex < b._alphaIndex) {
  56274. return -1;
  56275. }
  56276. // Then distance to camera
  56277. if (a._distanceToCamera < b._distanceToCamera) {
  56278. return 1;
  56279. }
  56280. if (a._distanceToCamera > b._distanceToCamera) {
  56281. return -1;
  56282. }
  56283. return 0;
  56284. });
  56285. // Render sub meshes
  56286. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56287. for (index = 0; index < sortedArray.length; index++) {
  56288. renderSubMesh(sortedArray[index]);
  56289. }
  56290. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56291. }
  56292. };
  56293. };
  56294. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  56295. var transform = scene.getTransformMatrix();
  56296. var meshPosition;
  56297. if (this.useCustomMeshPosition) {
  56298. meshPosition = this.customMeshPosition;
  56299. }
  56300. else if (this.attachedNode) {
  56301. meshPosition = this.attachedNode.position;
  56302. }
  56303. else {
  56304. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  56305. }
  56306. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  56307. this._screenCoordinates.x = pos.x / this._viewPort.width;
  56308. this._screenCoordinates.y = pos.y / this._viewPort.height;
  56309. if (this.invert)
  56310. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  56311. };
  56312. // Static methods
  56313. /**
  56314. * Creates a default mesh for the Volumeric Light Scattering post-process
  56315. * @param {string} The mesh name
  56316. * @param {BABYLON.Scene} The scene where to create the mesh
  56317. * @return {BABYLON.Mesh} the default mesh
  56318. */
  56319. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  56320. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  56321. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56322. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  56323. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  56324. mesh.material = material;
  56325. return mesh;
  56326. };
  56327. __decorate([
  56328. BABYLON.serializeAsVector3()
  56329. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  56330. __decorate([
  56331. BABYLON.serialize()
  56332. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  56333. __decorate([
  56334. BABYLON.serialize()
  56335. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  56336. __decorate([
  56337. BABYLON.serializeAsMeshReference()
  56338. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  56339. __decorate([
  56340. BABYLON.serialize()
  56341. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  56342. __decorate([
  56343. BABYLON.serialize()
  56344. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  56345. __decorate([
  56346. BABYLON.serialize()
  56347. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  56348. __decorate([
  56349. BABYLON.serialize()
  56350. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  56351. __decorate([
  56352. BABYLON.serialize()
  56353. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  56354. return VolumetricLightScatteringPostProcess;
  56355. }(BABYLON.PostProcess));
  56356. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  56357. })(BABYLON || (BABYLON = {}));
  56358. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  56359. //
  56360. // This post-process allows the modification of rendered colors by using
  56361. // a 'look-up table' (LUT). This effect is also called Color Grading.
  56362. //
  56363. // The object needs to be provided an url to a texture containing the color
  56364. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  56365. // Use an image editing software to tweak the LUT to match your needs.
  56366. //
  56367. // For an example of a color LUT, see here:
  56368. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  56369. // For explanations on color grading, see here:
  56370. // http://udn.epicgames.com/Three/ColorGrading.html
  56371. //
  56372. var BABYLON;
  56373. (function (BABYLON) {
  56374. var ColorCorrectionPostProcess = (function (_super) {
  56375. __extends(ColorCorrectionPostProcess, _super);
  56376. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  56377. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  56378. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  56379. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  56380. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56381. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56382. _this.onApply = function (effect) {
  56383. effect.setTexture("colorTable", _this._colorTableTexture);
  56384. };
  56385. return _this;
  56386. }
  56387. return ColorCorrectionPostProcess;
  56388. }(BABYLON.PostProcess));
  56389. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  56390. })(BABYLON || (BABYLON = {}));
  56391. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  56392. var BABYLON;
  56393. (function (BABYLON) {
  56394. var TonemappingOperator;
  56395. (function (TonemappingOperator) {
  56396. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  56397. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  56398. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  56399. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  56400. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  56401. ;
  56402. var TonemapPostProcess = (function (_super) {
  56403. __extends(TonemapPostProcess, _super);
  56404. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  56405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56406. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56407. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  56408. _this._operator = _operator;
  56409. _this.exposureAdjustment = exposureAdjustment;
  56410. var defines = "#define ";
  56411. if (_this._operator === TonemappingOperator.Hable)
  56412. defines += "HABLE_TONEMAPPING";
  56413. else if (_this._operator === TonemappingOperator.Reinhard)
  56414. defines += "REINHARD_TONEMAPPING";
  56415. else if (_this._operator === TonemappingOperator.HejiDawson)
  56416. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  56417. else if (_this._operator === TonemappingOperator.Photographic)
  56418. defines += "PHOTOGRAPHIC_TONEMAPPING";
  56419. //sadly a second call to create the effect.
  56420. _this.updateEffect(defines);
  56421. _this.onApply = function (effect) {
  56422. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  56423. };
  56424. return _this;
  56425. }
  56426. return TonemapPostProcess;
  56427. }(BABYLON.PostProcess));
  56428. BABYLON.TonemapPostProcess = TonemapPostProcess;
  56429. })(BABYLON || (BABYLON = {}));
  56430. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  56431. var BABYLON;
  56432. (function (BABYLON) {
  56433. var DisplayPassPostProcess = (function (_super) {
  56434. __extends(DisplayPassPostProcess, _super);
  56435. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  56436. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  56437. }
  56438. return DisplayPassPostProcess;
  56439. }(BABYLON.PostProcess));
  56440. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  56441. })(BABYLON || (BABYLON = {}));
  56442. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  56443. var BABYLON;
  56444. (function (BABYLON) {
  56445. var HighlightsPostProcess = (function (_super) {
  56446. __extends(HighlightsPostProcess, _super);
  56447. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56448. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56449. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  56450. }
  56451. return HighlightsPostProcess;
  56452. }(BABYLON.PostProcess));
  56453. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  56454. })(BABYLON || (BABYLON = {}));
  56455. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  56456. var BABYLON;
  56457. (function (BABYLON) {
  56458. var ImageProcessingPostProcess = (function (_super) {
  56459. __extends(ImageProcessingPostProcess, _super);
  56460. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56461. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56462. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  56463. _this._fromLinearSpace = true;
  56464. /**
  56465. * Defines cache preventing GC.
  56466. */
  56467. _this._defines = {
  56468. IMAGEPROCESSING: false,
  56469. VIGNETTE: false,
  56470. VIGNETTEBLENDMODEMULTIPLY: false,
  56471. VIGNETTEBLENDMODEOPAQUE: false,
  56472. TONEMAPPING: false,
  56473. CONTRAST: false,
  56474. COLORCURVES: false,
  56475. COLORGRADING: false,
  56476. FROMLINEARSPACE: false,
  56477. SAMPLER3DGREENDEPTH: false,
  56478. SAMPLER3DBGRMAP: false,
  56479. IMAGEPROCESSINGPOSTPROCESS: false,
  56480. EXPOSURE: false,
  56481. };
  56482. // Setup the default processing configuration to the scene.
  56483. _this._attachImageProcessingConfiguration(null, true);
  56484. _this.imageProcessingConfiguration.applyByPostProcess = true;
  56485. _this.onApply = function (effect) {
  56486. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  56487. };
  56488. return _this;
  56489. }
  56490. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  56491. /**
  56492. * Gets the image processing configuration used either in this material.
  56493. */
  56494. get: function () {
  56495. return this._imageProcessingConfiguration;
  56496. },
  56497. /**
  56498. * Sets the Default image processing configuration used either in the this material.
  56499. *
  56500. * If sets to null, the scene one is in use.
  56501. */
  56502. set: function (value) {
  56503. this._attachImageProcessingConfiguration(value);
  56504. },
  56505. enumerable: true,
  56506. configurable: true
  56507. });
  56508. /**
  56509. * Attaches a new image processing configuration to the PBR Material.
  56510. * @param configuration
  56511. */
  56512. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  56513. var _this = this;
  56514. if (doNotBuild === void 0) { doNotBuild = false; }
  56515. if (configuration === this._imageProcessingConfiguration) {
  56516. return;
  56517. }
  56518. // Detaches observer.
  56519. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  56520. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  56521. }
  56522. // Pick the scene configuration if needed.
  56523. if (!configuration) {
  56524. var scene = null;
  56525. var engine = this.getEngine();
  56526. var camera = this.getCamera();
  56527. if (camera) {
  56528. scene = camera.getScene();
  56529. }
  56530. else if (engine && engine.scenes) {
  56531. var scenes = engine.scenes;
  56532. scene = scenes[scenes.length - 1];
  56533. }
  56534. else {
  56535. scene = BABYLON.Engine.LastCreatedScene;
  56536. }
  56537. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  56538. }
  56539. else {
  56540. this._imageProcessingConfiguration = configuration;
  56541. }
  56542. // Attaches observer.
  56543. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  56544. _this._updateParameters();
  56545. });
  56546. // Ensure the effect will be rebuilt.
  56547. if (!doNotBuild) {
  56548. this._updateParameters();
  56549. }
  56550. };
  56551. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  56552. /**
  56553. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  56554. */
  56555. get: function () {
  56556. return this.imageProcessingConfiguration.colorCurves;
  56557. },
  56558. /**
  56559. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  56560. */
  56561. set: function (value) {
  56562. this.imageProcessingConfiguration.colorCurves = value;
  56563. },
  56564. enumerable: true,
  56565. configurable: true
  56566. });
  56567. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  56568. /**
  56569. * Gets wether the color curves effect is enabled.
  56570. */
  56571. get: function () {
  56572. return this.imageProcessingConfiguration.colorCurvesEnabled;
  56573. },
  56574. /**
  56575. * Sets wether the color curves effect is enabled.
  56576. */
  56577. set: function (value) {
  56578. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  56579. },
  56580. enumerable: true,
  56581. configurable: true
  56582. });
  56583. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  56584. /**
  56585. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  56586. */
  56587. get: function () {
  56588. return this.imageProcessingConfiguration.colorGradingTexture;
  56589. },
  56590. /**
  56591. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  56592. */
  56593. set: function (value) {
  56594. this.imageProcessingConfiguration.colorGradingTexture = value;
  56595. },
  56596. enumerable: true,
  56597. configurable: true
  56598. });
  56599. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  56600. /**
  56601. * Gets wether the color grading effect is enabled.
  56602. */
  56603. get: function () {
  56604. return this.imageProcessingConfiguration.colorGradingEnabled;
  56605. },
  56606. /**
  56607. * Gets wether the color grading effect is enabled.
  56608. */
  56609. set: function (value) {
  56610. this.imageProcessingConfiguration.colorGradingEnabled = value;
  56611. },
  56612. enumerable: true,
  56613. configurable: true
  56614. });
  56615. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  56616. /**
  56617. * Gets exposure used in the effect.
  56618. */
  56619. get: function () {
  56620. return this.imageProcessingConfiguration.exposure;
  56621. },
  56622. /**
  56623. * Sets exposure used in the effect.
  56624. */
  56625. set: function (value) {
  56626. this.imageProcessingConfiguration.exposure = value;
  56627. },
  56628. enumerable: true,
  56629. configurable: true
  56630. });
  56631. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  56632. /**
  56633. * Gets wether tonemapping is enabled or not.
  56634. */
  56635. get: function () {
  56636. return this._imageProcessingConfiguration.toneMappingEnabled;
  56637. },
  56638. /**
  56639. * Sets wether tonemapping is enabled or not
  56640. */
  56641. set: function (value) {
  56642. this._imageProcessingConfiguration.toneMappingEnabled = value;
  56643. },
  56644. enumerable: true,
  56645. configurable: true
  56646. });
  56647. ;
  56648. ;
  56649. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  56650. /**
  56651. * Gets contrast used in the effect.
  56652. */
  56653. get: function () {
  56654. return this.imageProcessingConfiguration.contrast;
  56655. },
  56656. /**
  56657. * Sets contrast used in the effect.
  56658. */
  56659. set: function (value) {
  56660. this.imageProcessingConfiguration.contrast = value;
  56661. },
  56662. enumerable: true,
  56663. configurable: true
  56664. });
  56665. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  56666. /**
  56667. * Gets Vignette stretch size.
  56668. */
  56669. get: function () {
  56670. return this.imageProcessingConfiguration.vignetteStretch;
  56671. },
  56672. /**
  56673. * Sets Vignette stretch size.
  56674. */
  56675. set: function (value) {
  56676. this.imageProcessingConfiguration.vignetteStretch = value;
  56677. },
  56678. enumerable: true,
  56679. configurable: true
  56680. });
  56681. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  56682. /**
  56683. * Gets Vignette centre X Offset.
  56684. */
  56685. get: function () {
  56686. return this.imageProcessingConfiguration.vignetteCentreX;
  56687. },
  56688. /**
  56689. * Sets Vignette centre X Offset.
  56690. */
  56691. set: function (value) {
  56692. this.imageProcessingConfiguration.vignetteCentreX = value;
  56693. },
  56694. enumerable: true,
  56695. configurable: true
  56696. });
  56697. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  56698. /**
  56699. * Gets Vignette centre Y Offset.
  56700. */
  56701. get: function () {
  56702. return this.imageProcessingConfiguration.vignetteCentreY;
  56703. },
  56704. /**
  56705. * Sets Vignette centre Y Offset.
  56706. */
  56707. set: function (value) {
  56708. this.imageProcessingConfiguration.vignetteCentreY = value;
  56709. },
  56710. enumerable: true,
  56711. configurable: true
  56712. });
  56713. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  56714. /**
  56715. * Gets Vignette weight or intensity of the vignette effect.
  56716. */
  56717. get: function () {
  56718. return this.imageProcessingConfiguration.vignetteWeight;
  56719. },
  56720. /**
  56721. * Sets Vignette weight or intensity of the vignette effect.
  56722. */
  56723. set: function (value) {
  56724. this.imageProcessingConfiguration.vignetteWeight = value;
  56725. },
  56726. enumerable: true,
  56727. configurable: true
  56728. });
  56729. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  56730. /**
  56731. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56732. * if vignetteEnabled is set to true.
  56733. */
  56734. get: function () {
  56735. return this.imageProcessingConfiguration.vignetteColor;
  56736. },
  56737. /**
  56738. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  56739. * if vignetteEnabled is set to true.
  56740. */
  56741. set: function (value) {
  56742. this.imageProcessingConfiguration.vignetteColor = value;
  56743. },
  56744. enumerable: true,
  56745. configurable: true
  56746. });
  56747. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  56748. /**
  56749. * Gets Camera field of view used by the Vignette effect.
  56750. */
  56751. get: function () {
  56752. return this.imageProcessingConfiguration.vignetteCameraFov;
  56753. },
  56754. /**
  56755. * Sets Camera field of view used by the Vignette effect.
  56756. */
  56757. set: function (value) {
  56758. this.imageProcessingConfiguration.vignetteCameraFov = value;
  56759. },
  56760. enumerable: true,
  56761. configurable: true
  56762. });
  56763. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  56764. /**
  56765. * Gets the vignette blend mode allowing different kind of effect.
  56766. */
  56767. get: function () {
  56768. return this.imageProcessingConfiguration.vignetteBlendMode;
  56769. },
  56770. /**
  56771. * Sets the vignette blend mode allowing different kind of effect.
  56772. */
  56773. set: function (value) {
  56774. this.imageProcessingConfiguration.vignetteBlendMode = value;
  56775. },
  56776. enumerable: true,
  56777. configurable: true
  56778. });
  56779. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  56780. /**
  56781. * Gets wether the vignette effect is enabled.
  56782. */
  56783. get: function () {
  56784. return this.imageProcessingConfiguration.vignetteEnabled;
  56785. },
  56786. /**
  56787. * Sets wether the vignette effect is enabled.
  56788. */
  56789. set: function (value) {
  56790. this.imageProcessingConfiguration.vignetteEnabled = value;
  56791. },
  56792. enumerable: true,
  56793. configurable: true
  56794. });
  56795. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  56796. /**
  56797. * Gets wether the input of the processing is in Gamma or Linear Space.
  56798. */
  56799. get: function () {
  56800. return this._fromLinearSpace;
  56801. },
  56802. /**
  56803. * Sets wether the input of the processing is in Gamma or Linear Space.
  56804. */
  56805. set: function (value) {
  56806. if (this._fromLinearSpace === value) {
  56807. return;
  56808. }
  56809. this._fromLinearSpace = value;
  56810. this._updateParameters();
  56811. },
  56812. enumerable: true,
  56813. configurable: true
  56814. });
  56815. ImageProcessingPostProcess.prototype.getClassName = function () {
  56816. return "ImageProcessingPostProcess";
  56817. };
  56818. ImageProcessingPostProcess.prototype._updateParameters = function () {
  56819. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  56820. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  56821. var defines = "";
  56822. for (var define in this._defines) {
  56823. if (this._defines[define]) {
  56824. defines += "#define " + define + ";\r\n";
  56825. }
  56826. }
  56827. var samplers = ["textureSampler"];
  56828. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  56829. var uniforms = ["scale"];
  56830. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  56831. this.updateEffect(defines, uniforms, samplers);
  56832. };
  56833. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  56834. _super.prototype.dispose.call(this, camera);
  56835. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  56836. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  56837. }
  56838. this.imageProcessingConfiguration.applyByPostProcess = false;
  56839. };
  56840. __decorate([
  56841. BABYLON.serialize()
  56842. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  56843. return ImageProcessingPostProcess;
  56844. }(BABYLON.PostProcess));
  56845. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  56846. })(BABYLON || (BABYLON = {}));
  56847. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  56848. var BABYLON;
  56849. (function (BABYLON) {
  56850. var BlurPostProcess = (function (_super) {
  56851. __extends(BlurPostProcess, _super);
  56852. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  56853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56854. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56855. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  56856. _this.direction = direction;
  56857. _this._packedFloat = false;
  56858. _this.onApplyObservable.add(function (effect) {
  56859. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  56860. });
  56861. _this.kernel = kernel;
  56862. return _this;
  56863. }
  56864. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  56865. /**
  56866. * Gets the length in pixels of the blur sample region
  56867. */
  56868. get: function () {
  56869. return this._idealKernel;
  56870. },
  56871. /**
  56872. * Sets the length in pixels of the blur sample region
  56873. */
  56874. set: function (v) {
  56875. if (this._idealKernel === v) {
  56876. return;
  56877. }
  56878. v = Math.max(v, 1);
  56879. this._idealKernel = v;
  56880. this._kernel = this._nearestBestKernel(v);
  56881. this._updateParameters();
  56882. },
  56883. enumerable: true,
  56884. configurable: true
  56885. });
  56886. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  56887. /**
  56888. * Gets wether or not the blur is unpacking/repacking floats
  56889. */
  56890. get: function () {
  56891. return this._packedFloat;
  56892. },
  56893. /**
  56894. * Sets wether or not the blur needs to unpack/repack floats
  56895. */
  56896. set: function (v) {
  56897. if (this._packedFloat === v) {
  56898. return;
  56899. }
  56900. this._packedFloat = v;
  56901. this._updateParameters();
  56902. },
  56903. enumerable: true,
  56904. configurable: true
  56905. });
  56906. BlurPostProcess.prototype._updateParameters = function () {
  56907. // Generate sampling offsets and weights
  56908. var N = this._kernel;
  56909. var centerIndex = (N - 1) / 2;
  56910. // Generate Gaussian sampling weights over kernel
  56911. var offsets = [];
  56912. var weights = [];
  56913. var totalWeight = 0;
  56914. for (var i = 0; i < N; i++) {
  56915. var u = i / (N - 1);
  56916. var w = this._gaussianWeight(u * 2.0 - 1);
  56917. offsets[i] = (i - centerIndex);
  56918. weights[i] = w;
  56919. totalWeight += w;
  56920. }
  56921. // Normalize weights
  56922. for (var i = 0; i < weights.length; i++) {
  56923. weights[i] /= totalWeight;
  56924. }
  56925. // Optimize: combine samples to take advantage of hardware linear sampling
  56926. // Walk from left to center, combining pairs (symmetrically)
  56927. var linearSamplingWeights = [];
  56928. var linearSamplingOffsets = [];
  56929. var linearSamplingMap = [];
  56930. for (var i = 0; i <= centerIndex; i += 2) {
  56931. var j = Math.min(i + 1, Math.floor(centerIndex));
  56932. var singleCenterSample = i === j;
  56933. if (singleCenterSample) {
  56934. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56935. }
  56936. else {
  56937. var sharedCell = j === centerIndex;
  56938. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  56939. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  56940. if (offsetLinear === 0) {
  56941. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  56942. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  56943. }
  56944. else {
  56945. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  56946. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  56947. }
  56948. }
  56949. }
  56950. for (var i = 0; i < linearSamplingMap.length; i++) {
  56951. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  56952. linearSamplingWeights[i] = linearSamplingMap[i].w;
  56953. }
  56954. // Replace with optimized
  56955. offsets = linearSamplingOffsets;
  56956. weights = linearSamplingWeights;
  56957. // Generate shaders
  56958. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  56959. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  56960. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  56961. var defines = "";
  56962. for (var i = 0; i < varyingCount; i++) {
  56963. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  56964. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  56965. }
  56966. var depCount = 0;
  56967. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  56968. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  56969. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  56970. depCount++;
  56971. }
  56972. if (this.packedFloat) {
  56973. defines += "#define PACKEDFLOAT 1";
  56974. }
  56975. this.updateEffect(defines, null, null, {
  56976. varyingCount: varyingCount,
  56977. depCount: depCount
  56978. });
  56979. };
  56980. /**
  56981. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  56982. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  56983. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  56984. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  56985. * The gaps between physical kernels are compensated for in the weighting of the samples
  56986. * @param idealKernel Ideal blur kernel.
  56987. * @return Nearest best kernel.
  56988. */
  56989. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  56990. var v = Math.round(idealKernel);
  56991. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  56992. var k = _a[_i];
  56993. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  56994. return Math.max(k, 3);
  56995. }
  56996. }
  56997. return Math.max(v, 3);
  56998. };
  56999. /**
  57000. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  57001. * @param x The point on the Gaussian distribution to sample.
  57002. * @return the value of the Gaussian function at x.
  57003. */
  57004. BlurPostProcess.prototype._gaussianWeight = function (x) {
  57005. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  57006. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  57007. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  57008. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  57009. // truncated at around 1.3% of peak strength.
  57010. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  57011. var sigma = (1 / 3);
  57012. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  57013. var exponent = -((x * x) / (2.0 * sigma * sigma));
  57014. var weight = (1.0 / denominator) * Math.exp(exponent);
  57015. return weight;
  57016. };
  57017. /**
  57018. * Generates a string that can be used as a floating point number in GLSL.
  57019. * @param x Value to print.
  57020. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  57021. * @return GLSL float string.
  57022. */
  57023. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  57024. if (decimalFigures === void 0) { decimalFigures = 8; }
  57025. return x.toFixed(decimalFigures).replace(/0+$/, '');
  57026. };
  57027. return BlurPostProcess;
  57028. }(BABYLON.PostProcess));
  57029. BABYLON.BlurPostProcess = BlurPostProcess;
  57030. })(BABYLON || (BABYLON = {}));
  57031. //# sourceMappingURL=babylon.blurPostProcess.js.map
  57032. /// <reference path="..\babylon.node.ts" />
  57033. var BABYLON;
  57034. (function (BABYLON) {
  57035. var Bone = (function (_super) {
  57036. __extends(Bone, _super);
  57037. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  57038. if (parentBone === void 0) { parentBone = null; }
  57039. var _this = _super.call(this, name, skeleton.getScene()) || this;
  57040. _this.name = name;
  57041. _this.children = new Array();
  57042. _this.animations = new Array();
  57043. _this._worldTransform = new BABYLON.Matrix();
  57044. _this._absoluteTransform = new BABYLON.Matrix();
  57045. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  57046. _this._scaleMatrix = BABYLON.Matrix.Identity();
  57047. _this._scaleVector = BABYLON.Vector3.One();
  57048. _this._negateScaleChildren = BABYLON.Vector3.One();
  57049. _this._scalingDeterminant = 1;
  57050. _this._skeleton = skeleton;
  57051. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  57052. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  57053. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  57054. _this._index = index;
  57055. skeleton.bones.push(_this);
  57056. _this.setParent(parentBone, false);
  57057. _this._updateDifferenceMatrix();
  57058. return _this;
  57059. }
  57060. Object.defineProperty(Bone.prototype, "_matrix", {
  57061. get: function () {
  57062. return this._localMatrix;
  57063. },
  57064. set: function (val) {
  57065. if (this._localMatrix) {
  57066. this._localMatrix.copyFrom(val);
  57067. }
  57068. else {
  57069. this._localMatrix = val;
  57070. }
  57071. },
  57072. enumerable: true,
  57073. configurable: true
  57074. });
  57075. // Members
  57076. Bone.prototype.getSkeleton = function () {
  57077. return this._skeleton;
  57078. };
  57079. Bone.prototype.getParent = function () {
  57080. return this._parent;
  57081. };
  57082. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  57083. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  57084. if (this._parent === parent) {
  57085. return;
  57086. }
  57087. if (this._parent) {
  57088. var index = this._parent.children.indexOf(this);
  57089. if (index !== -1) {
  57090. this._parent.children.splice(index);
  57091. }
  57092. }
  57093. this._parent = parent;
  57094. if (this._parent) {
  57095. this._parent.children.push(this);
  57096. }
  57097. if (updateDifferenceMatrix) {
  57098. this._updateDifferenceMatrix();
  57099. }
  57100. };
  57101. Bone.prototype.getLocalMatrix = function () {
  57102. return this._localMatrix;
  57103. };
  57104. Bone.prototype.getBaseMatrix = function () {
  57105. return this._baseMatrix;
  57106. };
  57107. Bone.prototype.getRestPose = function () {
  57108. return this._restPose;
  57109. };
  57110. Bone.prototype.returnToRest = function () {
  57111. this.updateMatrix(this._restPose.clone());
  57112. };
  57113. Bone.prototype.getWorldMatrix = function () {
  57114. return this._worldTransform;
  57115. };
  57116. Bone.prototype.getInvertedAbsoluteTransform = function () {
  57117. return this._invertedAbsoluteTransform;
  57118. };
  57119. Bone.prototype.getAbsoluteTransform = function () {
  57120. return this._absoluteTransform;
  57121. };
  57122. Object.defineProperty(Bone.prototype, "position", {
  57123. // Properties (matches AbstractMesh properties)
  57124. get: function () {
  57125. return this.getPosition();
  57126. },
  57127. set: function (newPosition) {
  57128. this.setPosition(newPosition);
  57129. },
  57130. enumerable: true,
  57131. configurable: true
  57132. });
  57133. Object.defineProperty(Bone.prototype, "rotation", {
  57134. get: function () {
  57135. return this.getRotation();
  57136. },
  57137. set: function (newRotation) {
  57138. this.setRotation(newRotation);
  57139. },
  57140. enumerable: true,
  57141. configurable: true
  57142. });
  57143. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  57144. get: function () {
  57145. return this.getRotationQuaternion();
  57146. },
  57147. set: function (newRotation) {
  57148. this.setRotationQuaternion(newRotation);
  57149. },
  57150. enumerable: true,
  57151. configurable: true
  57152. });
  57153. Object.defineProperty(Bone.prototype, "scaling", {
  57154. get: function () {
  57155. return this.getScale();
  57156. },
  57157. set: function (newScaling) {
  57158. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  57159. },
  57160. enumerable: true,
  57161. configurable: true
  57162. });
  57163. // Methods
  57164. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  57165. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  57166. this._baseMatrix = matrix.clone();
  57167. this._localMatrix = matrix.clone();
  57168. this._skeleton._markAsDirty();
  57169. if (updateDifferenceMatrix) {
  57170. this._updateDifferenceMatrix();
  57171. }
  57172. };
  57173. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  57174. if (!rootMatrix) {
  57175. rootMatrix = this._baseMatrix;
  57176. }
  57177. if (this._parent) {
  57178. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  57179. }
  57180. else {
  57181. this._absoluteTransform.copyFrom(rootMatrix);
  57182. }
  57183. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  57184. for (var index = 0; index < this.children.length; index++) {
  57185. this.children[index]._updateDifferenceMatrix();
  57186. }
  57187. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  57188. };
  57189. Bone.prototype.markAsDirty = function () {
  57190. this._currentRenderId++;
  57191. this._skeleton._markAsDirty();
  57192. };
  57193. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  57194. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  57195. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  57196. // all animation may be coming from a library skeleton, so may need to create animation
  57197. if (this.animations.length === 0) {
  57198. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  57199. this.animations[0].setKeys([]);
  57200. }
  57201. // get animation info / verify there is such a range from the source bone
  57202. var sourceRange = source.animations[0].getRange(rangeName);
  57203. if (!sourceRange) {
  57204. return false;
  57205. }
  57206. var from = sourceRange.from;
  57207. var to = sourceRange.to;
  57208. var sourceKeys = source.animations[0].getKeys();
  57209. // rescaling prep
  57210. var sourceBoneLength = source.length;
  57211. var sourceParent = source.getParent();
  57212. var parent = this.getParent();
  57213. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  57214. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  57215. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  57216. var destKeys = this.animations[0].getKeys();
  57217. // loop vars declaration
  57218. var orig;
  57219. var origTranslation;
  57220. var mat;
  57221. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  57222. orig = sourceKeys[key];
  57223. if (orig.frame >= from && orig.frame <= to) {
  57224. if (rescaleAsRequired) {
  57225. mat = orig.value.clone();
  57226. // scale based on parent ratio, when bone has parent
  57227. if (parentScalingReqd) {
  57228. origTranslation = mat.getTranslation();
  57229. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  57230. // scale based on skeleton dimension ratio when root bone, and value is passed
  57231. }
  57232. else if (dimensionsScalingReqd) {
  57233. origTranslation = mat.getTranslation();
  57234. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  57235. // use original when root bone, and no data for skelDimensionsRatio
  57236. }
  57237. else {
  57238. mat = orig.value;
  57239. }
  57240. }
  57241. else {
  57242. mat = orig.value;
  57243. }
  57244. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  57245. }
  57246. }
  57247. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  57248. return true;
  57249. };
  57250. /**
  57251. * Translate the bone in local or world space.
  57252. * @param vec The amount to translate the bone.
  57253. * @param space The space that the translation is in.
  57254. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57255. */
  57256. Bone.prototype.translate = function (vec, space, mesh) {
  57257. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57258. var lm = this.getLocalMatrix();
  57259. if (space == BABYLON.Space.LOCAL) {
  57260. lm.m[12] += vec.x;
  57261. lm.m[13] += vec.y;
  57262. lm.m[14] += vec.z;
  57263. }
  57264. else {
  57265. var wm;
  57266. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57267. if (mesh) {
  57268. wm = mesh.getWorldMatrix();
  57269. }
  57270. this._skeleton.computeAbsoluteTransforms();
  57271. var tmat = Bone._tmpMats[0];
  57272. var tvec = Bone._tmpVecs[0];
  57273. if (mesh) {
  57274. tmat.copyFrom(this._parent.getAbsoluteTransform());
  57275. tmat.multiplyToRef(wm, tmat);
  57276. }
  57277. else {
  57278. tmat.copyFrom(this._parent.getAbsoluteTransform());
  57279. }
  57280. tmat.m[12] = 0;
  57281. tmat.m[13] = 0;
  57282. tmat.m[14] = 0;
  57283. tmat.invert();
  57284. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  57285. lm.m[12] += tvec.x;
  57286. lm.m[13] += tvec.y;
  57287. lm.m[14] += tvec.z;
  57288. }
  57289. this.markAsDirty();
  57290. };
  57291. /**
  57292. * Set the postion of the bone in local or world space.
  57293. * @param position The position to set the bone.
  57294. * @param space The space that the position is in.
  57295. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57296. */
  57297. Bone.prototype.setPosition = function (position, space, mesh) {
  57298. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57299. var lm = this.getLocalMatrix();
  57300. if (space == BABYLON.Space.LOCAL) {
  57301. lm.m[12] = position.x;
  57302. lm.m[13] = position.y;
  57303. lm.m[14] = position.z;
  57304. }
  57305. else {
  57306. var wm;
  57307. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57308. if (mesh) {
  57309. wm = mesh.getWorldMatrix();
  57310. }
  57311. this._skeleton.computeAbsoluteTransforms();
  57312. var tmat = Bone._tmpMats[0];
  57313. var vec = Bone._tmpVecs[0];
  57314. if (mesh) {
  57315. tmat.copyFrom(this._parent.getAbsoluteTransform());
  57316. tmat.multiplyToRef(wm, tmat);
  57317. }
  57318. else {
  57319. tmat.copyFrom(this._parent.getAbsoluteTransform());
  57320. }
  57321. tmat.invert();
  57322. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  57323. lm.m[12] = vec.x;
  57324. lm.m[13] = vec.y;
  57325. lm.m[14] = vec.z;
  57326. }
  57327. this.markAsDirty();
  57328. };
  57329. /**
  57330. * Set the absolute postion of the bone (world space).
  57331. * @param position The position to set the bone.
  57332. * @param mesh The mesh that this bone is attached to.
  57333. */
  57334. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  57335. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  57336. };
  57337. /**
  57338. * Set the scale of the bone on the x, y and z axes.
  57339. * @param x The scale of the bone on the x axis.
  57340. * @param x The scale of the bone on the y axis.
  57341. * @param z The scale of the bone on the z axis.
  57342. * @param scaleChildren Set this to true if children of the bone should be scaled.
  57343. */
  57344. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  57345. if (scaleChildren === void 0) { scaleChildren = false; }
  57346. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  57347. if (!scaleChildren) {
  57348. this._negateScaleChildren.x = 1 / x;
  57349. this._negateScaleChildren.y = 1 / y;
  57350. this._negateScaleChildren.z = 1 / z;
  57351. }
  57352. this._syncScaleVector();
  57353. }
  57354. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  57355. };
  57356. /**
  57357. * Scale the bone on the x, y and z axes.
  57358. * @param x The amount to scale the bone on the x axis.
  57359. * @param x The amount to scale the bone on the y axis.
  57360. * @param z The amount to scale the bone on the z axis.
  57361. * @param scaleChildren Set this to true if children of the bone should be scaled.
  57362. */
  57363. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  57364. if (scaleChildren === void 0) { scaleChildren = false; }
  57365. var locMat = this.getLocalMatrix();
  57366. var origLocMat = Bone._tmpMats[0];
  57367. origLocMat.copyFrom(locMat);
  57368. var origLocMatInv = Bone._tmpMats[1];
  57369. origLocMatInv.copyFrom(origLocMat);
  57370. origLocMatInv.invert();
  57371. var scaleMat = Bone._tmpMats[2];
  57372. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  57373. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  57374. this._scaleVector.x *= x;
  57375. this._scaleVector.y *= y;
  57376. this._scaleVector.z *= z;
  57377. locMat.multiplyToRef(origLocMatInv, locMat);
  57378. locMat.multiplyToRef(scaleMat, locMat);
  57379. locMat.multiplyToRef(origLocMat, locMat);
  57380. var parent = this.getParent();
  57381. if (parent) {
  57382. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  57383. }
  57384. else {
  57385. this.getAbsoluteTransform().copyFrom(locMat);
  57386. }
  57387. var len = this.children.length;
  57388. scaleMat.invert();
  57389. for (var i = 0; i < len; i++) {
  57390. var child = this.children[i];
  57391. var cm = child.getLocalMatrix();
  57392. cm.multiplyToRef(scaleMat, cm);
  57393. var lm = child.getLocalMatrix();
  57394. lm.m[12] *= x;
  57395. lm.m[13] *= y;
  57396. lm.m[14] *= z;
  57397. }
  57398. this.computeAbsoluteTransforms();
  57399. if (scaleChildren) {
  57400. for (var i = 0; i < len; i++) {
  57401. this.children[i].scale(x, y, z, scaleChildren);
  57402. }
  57403. }
  57404. this.markAsDirty();
  57405. };
  57406. /**
  57407. * Set the yaw, pitch, and roll of the bone in local or world space.
  57408. * @param yaw The rotation of the bone on the y axis.
  57409. * @param pitch The rotation of the bone on the x axis.
  57410. * @param roll The rotation of the bone on the z axis.
  57411. * @param space The space that the axes of rotation are in.
  57412. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57413. */
  57414. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  57415. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57416. var rotMat = Bone._tmpMats[0];
  57417. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  57418. var rotMatInv = Bone._tmpMats[1];
  57419. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57420. rotMatInv.multiplyToRef(rotMat, rotMat);
  57421. this._rotateWithMatrix(rotMat, space, mesh);
  57422. };
  57423. /**
  57424. * Rotate the bone on an axis in local or world space.
  57425. * @param axis The axis to rotate the bone on.
  57426. * @param amount The amount to rotate the bone.
  57427. * @param space The space that the axis is in.
  57428. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57429. */
  57430. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  57431. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57432. var rmat = Bone._tmpMats[0];
  57433. rmat.m[12] = 0;
  57434. rmat.m[13] = 0;
  57435. rmat.m[14] = 0;
  57436. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  57437. this._rotateWithMatrix(rmat, space, mesh);
  57438. };
  57439. /**
  57440. * Set the rotation of the bone to a particular axis angle in local or world space.
  57441. * @param axis The axis to rotate the bone on.
  57442. * @param angle The angle that the bone should be rotated to.
  57443. * @param space The space that the axis is in.
  57444. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57445. */
  57446. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  57447. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57448. var rotMat = Bone._tmpMats[0];
  57449. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  57450. var rotMatInv = Bone._tmpMats[1];
  57451. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57452. rotMatInv.multiplyToRef(rotMat, rotMat);
  57453. this._rotateWithMatrix(rotMat, space, mesh);
  57454. };
  57455. /**
  57456. * Set the euler rotation of the bone in local of world space.
  57457. * @param rotation The euler rotation that the bone should be set to.
  57458. * @param space The space that the rotation is in.
  57459. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57460. */
  57461. Bone.prototype.setRotation = function (rotation, space, mesh) {
  57462. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57463. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  57464. };
  57465. /**
  57466. * Set the quaternion rotation of the bone in local of world space.
  57467. * @param quat The quaternion rotation that the bone should be set to.
  57468. * @param space The space that the rotation is in.
  57469. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57470. */
  57471. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  57472. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57473. var rotMatInv = Bone._tmpMats[0];
  57474. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57475. var rotMat = Bone._tmpMats[1];
  57476. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  57477. rotMatInv.multiplyToRef(rotMat, rotMat);
  57478. this._rotateWithMatrix(rotMat, space, mesh);
  57479. };
  57480. /**
  57481. * Set the rotation matrix of the bone in local of world space.
  57482. * @param rotMat The rotation matrix that the bone should be set to.
  57483. * @param space The space that the rotation is in.
  57484. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57485. */
  57486. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  57487. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57488. var rotMatInv = Bone._tmpMats[0];
  57489. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  57490. var rotMat2 = Bone._tmpMats[1];
  57491. rotMat2.copyFrom(rotMat);
  57492. rotMatInv.multiplyToRef(rotMat, rotMat2);
  57493. this._rotateWithMatrix(rotMat2, space, mesh);
  57494. };
  57495. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  57496. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57497. var lmat = this.getLocalMatrix();
  57498. var lx = lmat.m[12];
  57499. var ly = lmat.m[13];
  57500. var lz = lmat.m[14];
  57501. var parent = this.getParent();
  57502. var parentScale = Bone._tmpMats[3];
  57503. var parentScaleInv = Bone._tmpMats[4];
  57504. if (parent) {
  57505. if (space == BABYLON.Space.WORLD) {
  57506. if (mesh) {
  57507. parentScale.copyFrom(mesh.getWorldMatrix());
  57508. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  57509. }
  57510. else {
  57511. parentScale.copyFrom(parent.getAbsoluteTransform());
  57512. }
  57513. }
  57514. else {
  57515. parentScale = parent._scaleMatrix;
  57516. }
  57517. parentScaleInv.copyFrom(parentScale);
  57518. parentScaleInv.invert();
  57519. lmat.multiplyToRef(parentScale, lmat);
  57520. lmat.multiplyToRef(rmat, lmat);
  57521. lmat.multiplyToRef(parentScaleInv, lmat);
  57522. }
  57523. else {
  57524. if (space == BABYLON.Space.WORLD && mesh) {
  57525. parentScale.copyFrom(mesh.getWorldMatrix());
  57526. parentScaleInv.copyFrom(parentScale);
  57527. parentScaleInv.invert();
  57528. lmat.multiplyToRef(parentScale, lmat);
  57529. lmat.multiplyToRef(rmat, lmat);
  57530. lmat.multiplyToRef(parentScaleInv, lmat);
  57531. }
  57532. else {
  57533. lmat.multiplyToRef(rmat, lmat);
  57534. }
  57535. }
  57536. lmat.m[12] = lx;
  57537. lmat.m[13] = ly;
  57538. lmat.m[14] = lz;
  57539. this.computeAbsoluteTransforms();
  57540. this.markAsDirty();
  57541. };
  57542. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  57543. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57544. if (space == BABYLON.Space.WORLD) {
  57545. var scaleMatrix = Bone._tmpMats[2];
  57546. scaleMatrix.copyFrom(this._scaleMatrix);
  57547. rotMatInv.copyFrom(this.getAbsoluteTransform());
  57548. if (mesh) {
  57549. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  57550. var meshScale = Bone._tmpMats[3];
  57551. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  57552. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  57553. }
  57554. rotMatInv.invert();
  57555. scaleMatrix.m[0] *= this._scalingDeterminant;
  57556. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  57557. }
  57558. else {
  57559. rotMatInv.copyFrom(this.getLocalMatrix());
  57560. rotMatInv.invert();
  57561. var scaleMatrix = Bone._tmpMats[2];
  57562. scaleMatrix.copyFrom(this._scaleMatrix);
  57563. if (this._parent) {
  57564. var pscaleMatrix = Bone._tmpMats[3];
  57565. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  57566. pscaleMatrix.invert();
  57567. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  57568. }
  57569. else {
  57570. scaleMatrix.m[0] *= this._scalingDeterminant;
  57571. }
  57572. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  57573. }
  57574. };
  57575. /**
  57576. * Get the scale of the bone
  57577. * @returns the scale of the bone
  57578. */
  57579. Bone.prototype.getScale = function () {
  57580. return this._scaleVector.clone();
  57581. };
  57582. /**
  57583. * Copy the scale of the bone to a vector3.
  57584. * @param result The vector3 to copy the scale to
  57585. */
  57586. Bone.prototype.getScaleToRef = function (result) {
  57587. result.copyFrom(this._scaleVector);
  57588. };
  57589. /**
  57590. * Get the position of the bone in local or world space.
  57591. * @param space The space that the returned position is in.
  57592. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57593. * @returns The position of the bone
  57594. */
  57595. Bone.prototype.getPosition = function (space, mesh) {
  57596. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57597. var pos = BABYLON.Vector3.Zero();
  57598. this.getPositionToRef(space, mesh, pos);
  57599. return pos;
  57600. };
  57601. /**
  57602. * Copy the position of the bone to a vector3 in local or world space.
  57603. * @param space The space that the returned position is in.
  57604. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57605. * @param result The vector3 to copy the position to.
  57606. */
  57607. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  57608. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57609. if (space == BABYLON.Space.LOCAL) {
  57610. var lm = this.getLocalMatrix();
  57611. result.x = lm.m[12];
  57612. result.y = lm.m[13];
  57613. result.z = lm.m[14];
  57614. }
  57615. else {
  57616. var wm;
  57617. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57618. if (mesh) {
  57619. wm = mesh.getWorldMatrix();
  57620. }
  57621. this._skeleton.computeAbsoluteTransforms();
  57622. var tmat = Bone._tmpMats[0];
  57623. if (mesh) {
  57624. tmat.copyFrom(this.getAbsoluteTransform());
  57625. tmat.multiplyToRef(wm, tmat);
  57626. }
  57627. else {
  57628. tmat = this.getAbsoluteTransform();
  57629. }
  57630. result.x = tmat.m[12];
  57631. result.y = tmat.m[13];
  57632. result.z = tmat.m[14];
  57633. }
  57634. };
  57635. /**
  57636. * Get the absolute position of the bone (world space).
  57637. * @param mesh The mesh that this bone is attached to.
  57638. * @returns The absolute position of the bone
  57639. */
  57640. Bone.prototype.getAbsolutePosition = function (mesh) {
  57641. var pos = BABYLON.Vector3.Zero();
  57642. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  57643. return pos;
  57644. };
  57645. /**
  57646. * Copy the absolute position of the bone (world space) to the result param.
  57647. * @param mesh The mesh that this bone is attached to.
  57648. * @param result The vector3 to copy the absolute position to.
  57649. */
  57650. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  57651. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  57652. };
  57653. /**
  57654. * Compute the absolute transforms of this bone and its children.
  57655. */
  57656. Bone.prototype.computeAbsoluteTransforms = function () {
  57657. if (this._parent) {
  57658. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  57659. }
  57660. else {
  57661. this._absoluteTransform.copyFrom(this._localMatrix);
  57662. var poseMatrix = this._skeleton.getPoseMatrix();
  57663. if (poseMatrix) {
  57664. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  57665. }
  57666. }
  57667. var children = this.children;
  57668. var len = children.length;
  57669. for (var i = 0; i < len; i++) {
  57670. children[i].computeAbsoluteTransforms();
  57671. }
  57672. };
  57673. Bone.prototype._syncScaleVector = function () {
  57674. var lm = this.getLocalMatrix();
  57675. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  57676. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  57677. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  57678. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  57679. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  57680. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  57681. this._scaleVector.x = xs * Math.sqrt(xsq);
  57682. this._scaleVector.y = ys * Math.sqrt(ysq);
  57683. this._scaleVector.z = zs * Math.sqrt(zsq);
  57684. if (this._parent) {
  57685. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  57686. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  57687. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  57688. }
  57689. 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);
  57690. };
  57691. /**
  57692. * Get the world direction from an axis that is in the local space of the bone.
  57693. * @param localAxis The local direction that is used to compute the world direction.
  57694. * @param mesh The mesh that this bone is attached to.
  57695. * @returns The world direction
  57696. */
  57697. Bone.prototype.getDirection = function (localAxis, mesh) {
  57698. var result = BABYLON.Vector3.Zero();
  57699. this.getDirectionToRef(localAxis, mesh, result);
  57700. return result;
  57701. };
  57702. /**
  57703. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  57704. * @param localAxis The local direction that is used to compute the world direction.
  57705. * @param mesh The mesh that this bone is attached to.
  57706. * @param result The vector3 that the world direction will be copied to.
  57707. */
  57708. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  57709. var wm;
  57710. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57711. if (mesh) {
  57712. wm = mesh.getWorldMatrix();
  57713. }
  57714. this._skeleton.computeAbsoluteTransforms();
  57715. var mat = Bone._tmpMats[0];
  57716. mat.copyFrom(this.getAbsoluteTransform());
  57717. if (mesh) {
  57718. mat.multiplyToRef(wm, mat);
  57719. }
  57720. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  57721. result.normalize();
  57722. };
  57723. /**
  57724. * Get the euler rotation of the bone in local or world space.
  57725. * @param space The space that the rotation should be in.
  57726. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57727. * @returns The euler rotation
  57728. */
  57729. Bone.prototype.getRotation = function (space, mesh) {
  57730. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57731. var result = BABYLON.Vector3.Zero();
  57732. this.getRotationToRef(space, mesh, result);
  57733. return result;
  57734. };
  57735. /**
  57736. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  57737. * @param space The space that the rotation should be in.
  57738. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57739. * @param result The vector3 that the rotation should be copied to.
  57740. */
  57741. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  57742. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57743. var quat = Bone._tmpQuat;
  57744. this.getRotationQuaternionToRef(space, mesh, quat);
  57745. quat.toEulerAnglesToRef(result);
  57746. };
  57747. /**
  57748. * Get the quaternion rotation of the bone in either local or world space.
  57749. * @param space The space that the rotation should be in.
  57750. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57751. * @returns The quaternion rotation
  57752. */
  57753. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  57754. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57755. var result = BABYLON.Quaternion.Identity();
  57756. this.getRotationQuaternionToRef(space, mesh, result);
  57757. return result;
  57758. };
  57759. /**
  57760. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  57761. * @param space The space that the rotation should be in.
  57762. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57763. * @param result The quaternion that the rotation should be copied to.
  57764. */
  57765. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  57766. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57767. if (space == BABYLON.Space.LOCAL) {
  57768. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57769. }
  57770. else {
  57771. var mat = Bone._tmpMats[0];
  57772. var amat = this.getAbsoluteTransform();
  57773. if (mesh) {
  57774. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57775. }
  57776. else {
  57777. mat.copyFrom(amat);
  57778. }
  57779. mat.m[0] *= this._scalingDeterminant;
  57780. mat.m[1] *= this._scalingDeterminant;
  57781. mat.m[2] *= this._scalingDeterminant;
  57782. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  57783. }
  57784. };
  57785. /**
  57786. * Get the rotation matrix of the bone in local or world space.
  57787. * @param space The space that the rotation should be in.
  57788. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57789. * @returns The rotation matrix
  57790. */
  57791. Bone.prototype.getRotationMatrix = function (space, mesh) {
  57792. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57793. var result = BABYLON.Matrix.Identity();
  57794. this.getRotationMatrixToRef(space, mesh, result);
  57795. return result;
  57796. };
  57797. /**
  57798. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  57799. * @param space The space that the rotation should be in.
  57800. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  57801. * @param result The quaternion that the rotation should be copied to.
  57802. */
  57803. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  57804. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  57805. if (space == BABYLON.Space.LOCAL) {
  57806. this.getLocalMatrix().getRotationMatrixToRef(result);
  57807. }
  57808. else {
  57809. var mat = Bone._tmpMats[0];
  57810. var amat = this.getAbsoluteTransform();
  57811. if (mesh) {
  57812. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  57813. }
  57814. else {
  57815. mat.copyFrom(amat);
  57816. }
  57817. mat.m[0] *= this._scalingDeterminant;
  57818. mat.m[1] *= this._scalingDeterminant;
  57819. mat.m[2] *= this._scalingDeterminant;
  57820. mat.getRotationMatrixToRef(result);
  57821. }
  57822. };
  57823. /**
  57824. * Get the world position of a point that is in the local space of the bone.
  57825. * @param position The local position
  57826. * @param mesh The mesh that this bone is attached to.
  57827. * @returns The world position
  57828. */
  57829. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  57830. var result = BABYLON.Vector3.Zero();
  57831. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  57832. return result;
  57833. };
  57834. /**
  57835. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  57836. * @param position The local position
  57837. * @param mesh The mesh that this bone is attached to.
  57838. * @param result The vector3 that the world position should be copied to.
  57839. */
  57840. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  57841. var wm;
  57842. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57843. if (mesh) {
  57844. wm = mesh.getWorldMatrix();
  57845. }
  57846. this._skeleton.computeAbsoluteTransforms();
  57847. var tmat = Bone._tmpMats[0];
  57848. if (mesh) {
  57849. tmat.copyFrom(this.getAbsoluteTransform());
  57850. tmat.multiplyToRef(wm, tmat);
  57851. }
  57852. else {
  57853. tmat = this.getAbsoluteTransform();
  57854. }
  57855. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57856. };
  57857. /**
  57858. * Get the local position of a point that is in world space.
  57859. * @param position The world position
  57860. * @param mesh The mesh that this bone is attached to.
  57861. * @returns The local position
  57862. */
  57863. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  57864. var result = BABYLON.Vector3.Zero();
  57865. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  57866. return result;
  57867. };
  57868. /**
  57869. * Get the local position of a point that is in world space and copy it to the result param.
  57870. * @param position The world position
  57871. * @param mesh The mesh that this bone is attached to.
  57872. * @param result The vector3 that the local position should be copied to.
  57873. */
  57874. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  57875. var wm;
  57876. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  57877. if (mesh) {
  57878. wm = mesh.getWorldMatrix();
  57879. }
  57880. this._skeleton.computeAbsoluteTransforms();
  57881. var tmat = Bone._tmpMats[0];
  57882. tmat.copyFrom(this.getAbsoluteTransform());
  57883. if (mesh) {
  57884. tmat.multiplyToRef(wm, tmat);
  57885. }
  57886. tmat.invert();
  57887. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  57888. };
  57889. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57890. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  57891. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57892. return Bone;
  57893. }(BABYLON.Node));
  57894. BABYLON.Bone = Bone;
  57895. })(BABYLON || (BABYLON = {}));
  57896. //# sourceMappingURL=babylon.bone.js.map
  57897. var BABYLON;
  57898. (function (BABYLON) {
  57899. var BoneIKController = (function () {
  57900. function BoneIKController(mesh, bone, options) {
  57901. this.targetPosition = BABYLON.Vector3.Zero();
  57902. this.poleTargetPosition = BABYLON.Vector3.Zero();
  57903. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  57904. this.poleAngle = 0;
  57905. this.slerpAmount = 1;
  57906. this._bone1Quat = BABYLON.Quaternion.Identity();
  57907. this._bone1Mat = BABYLON.Matrix.Identity();
  57908. this._bone2Ang = Math.PI;
  57909. this._maxAngle = Math.PI;
  57910. this._rightHandedSystem = false;
  57911. this._bendAxis = BABYLON.Vector3.Right();
  57912. this._slerping = false;
  57913. this._adjustRoll = 0;
  57914. this._bone2 = bone;
  57915. this._bone1 = bone.getParent();
  57916. this.mesh = mesh;
  57917. var bonePos = bone.getPosition();
  57918. if (bone.getAbsoluteTransform().determinant() > 0) {
  57919. this._rightHandedSystem = true;
  57920. this._bendAxis.x = 0;
  57921. this._bendAxis.y = 0;
  57922. this._bendAxis.z = -1;
  57923. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  57924. this._adjustRoll = Math.PI * .5;
  57925. this._bendAxis.z = 1;
  57926. }
  57927. }
  57928. if (this._bone1.length) {
  57929. var boneScale1 = this._bone1.getScale();
  57930. var boneScale2 = this._bone2.getScale();
  57931. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  57932. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  57933. }
  57934. else if (this._bone1.children[0]) {
  57935. mesh.computeWorldMatrix(true);
  57936. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  57937. var pos2 = this._bone2.getAbsolutePosition(mesh);
  57938. var pos3 = this._bone1.getAbsolutePosition(mesh);
  57939. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  57940. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  57941. }
  57942. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  57943. this.maxAngle = Math.PI;
  57944. if (options) {
  57945. if (options.targetMesh) {
  57946. this.targetMesh = options.targetMesh;
  57947. this.targetMesh.computeWorldMatrix(true);
  57948. }
  57949. if (options.poleTargetMesh) {
  57950. this.poleTargetMesh = options.poleTargetMesh;
  57951. this.poleTargetMesh.computeWorldMatrix(true);
  57952. }
  57953. else if (options.poleTargetBone) {
  57954. this.poleTargetBone = options.poleTargetBone;
  57955. }
  57956. else if (this._bone1.getParent()) {
  57957. this.poleTargetBone = this._bone1.getParent();
  57958. }
  57959. if (options.poleTargetLocalOffset) {
  57960. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  57961. }
  57962. if (options.poleAngle) {
  57963. this.poleAngle = options.poleAngle;
  57964. }
  57965. if (options.bendAxis) {
  57966. this._bendAxis.copyFrom(options.bendAxis);
  57967. }
  57968. if (options.maxAngle) {
  57969. this.maxAngle = options.maxAngle;
  57970. }
  57971. if (options.slerpAmount) {
  57972. this.slerpAmount = options.slerpAmount;
  57973. }
  57974. }
  57975. }
  57976. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  57977. get: function () {
  57978. return this._maxAngle;
  57979. },
  57980. set: function (value) {
  57981. this._setMaxAngle(value);
  57982. },
  57983. enumerable: true,
  57984. configurable: true
  57985. });
  57986. BoneIKController.prototype._setMaxAngle = function (ang) {
  57987. if (ang < 0) {
  57988. ang = 0;
  57989. }
  57990. if (ang > Math.PI || ang == undefined) {
  57991. ang = Math.PI;
  57992. }
  57993. this._maxAngle = ang;
  57994. var a = this._bone1Length;
  57995. var b = this._bone2Length;
  57996. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  57997. };
  57998. BoneIKController.prototype.update = function () {
  57999. var bone1 = this._bone1;
  58000. var target = this.targetPosition;
  58001. var poleTarget = this.poleTargetPosition;
  58002. var mat1 = BoneIKController._tmpMats[0];
  58003. var mat2 = BoneIKController._tmpMats[1];
  58004. if (this.targetMesh) {
  58005. target.copyFrom(this.targetMesh.getAbsolutePosition());
  58006. }
  58007. if (this.poleTargetBone) {
  58008. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  58009. }
  58010. else if (this.poleTargetMesh) {
  58011. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  58012. }
  58013. var bonePos = BoneIKController._tmpVecs[0];
  58014. var zaxis = BoneIKController._tmpVecs[1];
  58015. var xaxis = BoneIKController._tmpVecs[2];
  58016. var yaxis = BoneIKController._tmpVecs[3];
  58017. var upAxis = BoneIKController._tmpVecs[4];
  58018. var _tmpQuat = BoneIKController._tmpQuat;
  58019. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  58020. poleTarget.subtractToRef(bonePos, upAxis);
  58021. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  58022. upAxis.y = 1;
  58023. }
  58024. else {
  58025. upAxis.normalize();
  58026. }
  58027. target.subtractToRef(bonePos, yaxis);
  58028. yaxis.normalize();
  58029. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  58030. zaxis.normalize();
  58031. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  58032. xaxis.normalize();
  58033. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  58034. var a = this._bone1Length;
  58035. var b = this._bone2Length;
  58036. var c = BABYLON.Vector3.Distance(bonePos, target);
  58037. if (this._maxReach > 0) {
  58038. c = Math.min(this._maxReach, c);
  58039. }
  58040. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  58041. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  58042. if (acosa > 1) {
  58043. acosa = 1;
  58044. }
  58045. if (acosb > 1) {
  58046. acosb = 1;
  58047. }
  58048. if (acosa < -1) {
  58049. acosa = -1;
  58050. }
  58051. if (acosb < -1) {
  58052. acosb = -1;
  58053. }
  58054. var angA = Math.acos(acosa);
  58055. var angB = Math.acos(acosb);
  58056. var angC = -angA - angB;
  58057. if (this._rightHandedSystem) {
  58058. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  58059. mat2.multiplyToRef(mat1, mat1);
  58060. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  58061. mat2.multiplyToRef(mat1, mat1);
  58062. }
  58063. else {
  58064. var _tmpVec = BoneIKController._tmpVecs[5];
  58065. _tmpVec.copyFrom(this._bendAxis);
  58066. _tmpVec.x *= -1;
  58067. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  58068. mat2.multiplyToRef(mat1, mat1);
  58069. }
  58070. if (this.poleAngle) {
  58071. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  58072. mat1.multiplyToRef(mat2, mat1);
  58073. }
  58074. if (this.slerpAmount < 1) {
  58075. if (!this._slerping) {
  58076. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  58077. }
  58078. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  58079. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  58080. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  58081. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  58082. this._slerping = true;
  58083. }
  58084. else {
  58085. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  58086. this._bone1Mat.copyFrom(mat1);
  58087. this._slerping = false;
  58088. }
  58089. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  58090. this._bone2Ang = angC;
  58091. };
  58092. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58093. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  58094. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  58095. return BoneIKController;
  58096. }());
  58097. BABYLON.BoneIKController = BoneIKController;
  58098. })(BABYLON || (BABYLON = {}));
  58099. //# sourceMappingURL=babylon.boneIKController.js.map
  58100. var BABYLON;
  58101. (function (BABYLON) {
  58102. var BoneLookController = (function () {
  58103. /**
  58104. * Create a BoneLookController
  58105. * @param mesh the mesh that the bone belongs to
  58106. * @param bone the bone that will be looking to the target
  58107. * @param target the target Vector3 to look at
  58108. * @param settings optional settings:
  58109. * - maxYaw: the maximum angle the bone will yaw to
  58110. * - minYaw: the minimum angle the bone will yaw to
  58111. * - maxPitch: the maximum angle the bone will pitch to
  58112. * - minPitch: the minimum angle the bone will yaw to
  58113. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  58114. * - upAxis: the up axis of the coordinate system
  58115. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  58116. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  58117. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  58118. * - adjustYaw: used to make an adjustment to the yaw of the bone
  58119. * - adjustPitch: used to make an adjustment to the pitch of the bone
  58120. * - adjustRoll: used to make an adjustment to the roll of the bone
  58121. **/
  58122. function BoneLookController(mesh, bone, target, options) {
  58123. /**
  58124. * The up axis of the coordinate system that is used when the bone is rotated.
  58125. */
  58126. this.upAxis = BABYLON.Vector3.Up();
  58127. /**
  58128. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  58129. */
  58130. this.upAxisSpace = BABYLON.Space.LOCAL;
  58131. /**
  58132. * Used to make an adjustment to the yaw of the bone.
  58133. */
  58134. this.adjustYaw = 0;
  58135. /**
  58136. * Used to make an adjustment to the pitch of the bone.
  58137. */
  58138. this.adjustPitch = 0;
  58139. /**
  58140. * Used to make an adjustment to the roll of the bone.
  58141. */
  58142. this.adjustRoll = 0;
  58143. /**
  58144. * 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).
  58145. */
  58146. this.slerpAmount = 1;
  58147. this._boneQuat = BABYLON.Quaternion.Identity();
  58148. this._slerping = false;
  58149. this._firstFrameSkipped = false;
  58150. this._fowardAxis = BABYLON.Vector3.Forward();
  58151. this.mesh = mesh;
  58152. this.bone = bone;
  58153. this.target = target;
  58154. if (options) {
  58155. if (options.adjustYaw) {
  58156. this.adjustYaw = options.adjustYaw;
  58157. }
  58158. if (options.adjustPitch) {
  58159. this.adjustPitch = options.adjustPitch;
  58160. }
  58161. if (options.adjustRoll) {
  58162. this.adjustRoll = options.adjustRoll;
  58163. }
  58164. if (options.maxYaw != null) {
  58165. this.maxYaw = options.maxYaw;
  58166. }
  58167. else {
  58168. this.maxYaw = Math.PI;
  58169. }
  58170. if (options.minYaw != null) {
  58171. this.minYaw = options.minYaw;
  58172. }
  58173. else {
  58174. this.minYaw = -Math.PI;
  58175. }
  58176. if (options.maxPitch != null) {
  58177. this.maxPitch = options.maxPitch;
  58178. }
  58179. else {
  58180. this.maxPitch = Math.PI;
  58181. }
  58182. if (options.minPitch != null) {
  58183. this.minPitch = options.minPitch;
  58184. }
  58185. else {
  58186. this.minPitch = -Math.PI;
  58187. }
  58188. if (options.slerpAmount != null) {
  58189. this.slerpAmount = options.slerpAmount;
  58190. }
  58191. if (options.upAxis != null) {
  58192. this.upAxis = options.upAxis;
  58193. }
  58194. if (options.upAxisSpace != null) {
  58195. this.upAxisSpace = options.upAxisSpace;
  58196. }
  58197. if (options.yawAxis != null || options.pitchAxis != null) {
  58198. var newYawAxis = BABYLON.Axis.Y;
  58199. var newPitchAxis = BABYLON.Axis.X;
  58200. if (options.yawAxis != null) {
  58201. newYawAxis = options.yawAxis.clone();
  58202. newYawAxis.normalize();
  58203. }
  58204. if (options.pitchAxis != null) {
  58205. newPitchAxis = options.pitchAxis.clone();
  58206. newPitchAxis.normalize();
  58207. }
  58208. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  58209. this._transformYawPitch = BABYLON.Matrix.Identity();
  58210. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  58211. this._transformYawPitchInv = this._transformYawPitch.clone();
  58212. this._transformYawPitch.invert();
  58213. }
  58214. }
  58215. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  58216. this.upAxisSpace = BABYLON.Space.LOCAL;
  58217. }
  58218. }
  58219. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  58220. /**
  58221. * Get/set the minimum yaw angle that the bone can look to.
  58222. */
  58223. get: function () {
  58224. return this._minYaw;
  58225. },
  58226. set: function (value) {
  58227. this._minYaw = value;
  58228. this._minYawSin = Math.sin(value);
  58229. this._minYawCos = Math.cos(value);
  58230. if (this._maxYaw != null) {
  58231. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  58232. this._yawRange = this._maxYaw - this._minYaw;
  58233. }
  58234. },
  58235. enumerable: true,
  58236. configurable: true
  58237. });
  58238. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  58239. /**
  58240. * Get/set the maximum yaw angle that the bone can look to.
  58241. */
  58242. get: function () {
  58243. return this._maxYaw;
  58244. },
  58245. set: function (value) {
  58246. this._maxYaw = value;
  58247. this._maxYawSin = Math.sin(value);
  58248. this._maxYawCos = Math.cos(value);
  58249. if (this._minYaw != null) {
  58250. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  58251. this._yawRange = this._maxYaw - this._minYaw;
  58252. }
  58253. },
  58254. enumerable: true,
  58255. configurable: true
  58256. });
  58257. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  58258. /**
  58259. * Get/set the minimum pitch angle that the bone can look to.
  58260. */
  58261. get: function () {
  58262. return this._minPitch;
  58263. },
  58264. set: function (value) {
  58265. this._minPitch = value;
  58266. this._minPitchTan = Math.tan(value);
  58267. },
  58268. enumerable: true,
  58269. configurable: true
  58270. });
  58271. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  58272. /**
  58273. * Get/set the maximum pitch angle that the bone can look to.
  58274. */
  58275. get: function () {
  58276. return this._maxPitch;
  58277. },
  58278. set: function (value) {
  58279. this._maxPitch = value;
  58280. this._maxPitchTan = Math.tan(value);
  58281. },
  58282. enumerable: true,
  58283. configurable: true
  58284. });
  58285. /**
  58286. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  58287. */
  58288. BoneLookController.prototype.update = function () {
  58289. //skip the first frame when slerping so that the mesh rotation is correct
  58290. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  58291. this._firstFrameSkipped = true;
  58292. return;
  58293. }
  58294. var bone = this.bone;
  58295. var bonePos = BoneLookController._tmpVecs[0];
  58296. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  58297. var target = this.target;
  58298. var _tmpMat1 = BoneLookController._tmpMats[0];
  58299. var _tmpMat2 = BoneLookController._tmpMats[1];
  58300. var mesh = this.mesh;
  58301. var parentBone = bone.getParent();
  58302. var upAxis = BoneLookController._tmpVecs[1];
  58303. upAxis.copyFrom(this.upAxis);
  58304. if (this.upAxisSpace == BABYLON.Space.BONE) {
  58305. if (this._transformYawPitch) {
  58306. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  58307. }
  58308. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  58309. }
  58310. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  58311. mesh.getDirectionToRef(upAxis, upAxis);
  58312. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  58313. upAxis.normalize();
  58314. }
  58315. }
  58316. var checkYaw = false;
  58317. var checkPitch = false;
  58318. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  58319. checkYaw = true;
  58320. }
  58321. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  58322. checkPitch = true;
  58323. }
  58324. if (checkYaw || checkPitch) {
  58325. var spaceMat = BoneLookController._tmpMats[2];
  58326. var spaceMatInv = BoneLookController._tmpMats[3];
  58327. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  58328. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  58329. }
  58330. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  58331. spaceMat.copyFrom(mesh.getWorldMatrix());
  58332. }
  58333. else {
  58334. var forwardAxis = BoneLookController._tmpVecs[2];
  58335. forwardAxis.copyFrom(this._fowardAxis);
  58336. if (this._transformYawPitch) {
  58337. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  58338. }
  58339. if (parentBone) {
  58340. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  58341. }
  58342. else {
  58343. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  58344. }
  58345. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  58346. rightAxis.normalize();
  58347. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  58348. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  58349. }
  58350. spaceMat.invertToRef(spaceMatInv);
  58351. var xzlen;
  58352. if (checkPitch) {
  58353. var localTarget = BoneLookController._tmpVecs[3];
  58354. target.subtractToRef(bonePos, localTarget);
  58355. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  58356. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58357. var pitch = Math.atan2(localTarget.y, xzlen);
  58358. var newPitch = pitch;
  58359. if (pitch > this._maxPitch) {
  58360. localTarget.y = this._maxPitchTan * xzlen;
  58361. newPitch = this._maxPitch;
  58362. }
  58363. else if (pitch < this._minPitch) {
  58364. localTarget.y = this._minPitchTan * xzlen;
  58365. newPitch = this._minPitch;
  58366. }
  58367. if (pitch != newPitch) {
  58368. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  58369. localTarget.addInPlace(bonePos);
  58370. target = localTarget;
  58371. }
  58372. }
  58373. if (checkYaw) {
  58374. var localTarget = BoneLookController._tmpVecs[4];
  58375. target.subtractToRef(bonePos, localTarget);
  58376. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  58377. var yaw = Math.atan2(localTarget.x, localTarget.z);
  58378. var newYaw = yaw;
  58379. if (yaw > this._maxYaw || yaw < this._minYaw) {
  58380. if (xzlen == null) {
  58381. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58382. }
  58383. if (this._yawRange > Math.PI) {
  58384. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  58385. localTarget.z = this._maxYawCos * xzlen;
  58386. localTarget.x = this._maxYawSin * xzlen;
  58387. newYaw = this._maxYaw;
  58388. }
  58389. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  58390. localTarget.z = this._minYawCos * xzlen;
  58391. localTarget.x = this._minYawSin * xzlen;
  58392. newYaw = this._minYaw;
  58393. }
  58394. }
  58395. else {
  58396. if (yaw > this._maxYaw) {
  58397. localTarget.z = this._maxYawCos * xzlen;
  58398. localTarget.x = this._maxYawSin * xzlen;
  58399. newYaw = this._maxYaw;
  58400. }
  58401. else if (yaw < this._minYaw) {
  58402. localTarget.z = this._minYawCos * xzlen;
  58403. localTarget.x = this._minYawSin * xzlen;
  58404. newYaw = this._minYaw;
  58405. }
  58406. }
  58407. }
  58408. if (this._slerping && this._yawRange > Math.PI) {
  58409. //are we going to be crossing into the min/max region?
  58410. var boneFwd = BoneLookController._tmpVecs[8];
  58411. boneFwd.copyFrom(BABYLON.Axis.Z);
  58412. if (this._transformYawPitch) {
  58413. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  58414. }
  58415. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  58416. this._boneQuat.toRotationMatrix(boneRotMat);
  58417. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  58418. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  58419. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  58420. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  58421. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  58422. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  58423. if (angBtwTar > angBtwMidYaw) {
  58424. if (xzlen == null) {
  58425. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  58426. }
  58427. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  58428. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  58429. if (angBtwMin < angBtwMax) {
  58430. newYaw = boneYaw + Math.PI * .75;
  58431. localTarget.z = Math.cos(newYaw) * xzlen;
  58432. localTarget.x = Math.sin(newYaw) * xzlen;
  58433. }
  58434. else {
  58435. newYaw = boneYaw - Math.PI * .75;
  58436. localTarget.z = Math.cos(newYaw) * xzlen;
  58437. localTarget.x = Math.sin(newYaw) * xzlen;
  58438. }
  58439. }
  58440. }
  58441. if (yaw != newYaw) {
  58442. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  58443. localTarget.addInPlace(bonePos);
  58444. target = localTarget;
  58445. }
  58446. }
  58447. }
  58448. var zaxis = BoneLookController._tmpVecs[5];
  58449. var xaxis = BoneLookController._tmpVecs[6];
  58450. var yaxis = BoneLookController._tmpVecs[7];
  58451. var _tmpQuat = BoneLookController._tmpQuat;
  58452. target.subtractToRef(bonePos, zaxis);
  58453. zaxis.normalize();
  58454. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  58455. xaxis.normalize();
  58456. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  58457. yaxis.normalize();
  58458. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  58459. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  58460. return;
  58461. }
  58462. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  58463. return;
  58464. }
  58465. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  58466. return;
  58467. }
  58468. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  58469. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  58470. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  58471. }
  58472. if (this.slerpAmount < 1) {
  58473. if (!this._slerping) {
  58474. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  58475. }
  58476. if (this._transformYawPitch) {
  58477. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  58478. }
  58479. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  58480. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  58481. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  58482. this._slerping = true;
  58483. }
  58484. else {
  58485. if (this._transformYawPitch) {
  58486. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  58487. }
  58488. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  58489. this._slerping = false;
  58490. }
  58491. };
  58492. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  58493. var angDiff = ang2 - ang1;
  58494. angDiff %= Math.PI * 2;
  58495. if (angDiff > Math.PI) {
  58496. angDiff -= Math.PI * 2;
  58497. }
  58498. else if (angDiff < -Math.PI) {
  58499. angDiff += Math.PI * 2;
  58500. }
  58501. return angDiff;
  58502. };
  58503. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  58504. ang1 %= (2 * Math.PI);
  58505. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  58506. ang2 %= (2 * Math.PI);
  58507. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  58508. var ab = 0;
  58509. if (ang1 < ang2) {
  58510. ab = ang2 - ang1;
  58511. }
  58512. else {
  58513. ab = ang1 - ang2;
  58514. }
  58515. if (ab > Math.PI) {
  58516. ab = Math.PI * 2 - ab;
  58517. }
  58518. return ab;
  58519. };
  58520. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  58521. ang %= (2 * Math.PI);
  58522. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  58523. ang1 %= (2 * Math.PI);
  58524. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  58525. ang2 %= (2 * Math.PI);
  58526. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  58527. if (ang1 < ang2) {
  58528. if (ang > ang1 && ang < ang2) {
  58529. return true;
  58530. }
  58531. }
  58532. else {
  58533. if (ang > ang2 && ang < ang1) {
  58534. return true;
  58535. }
  58536. }
  58537. return false;
  58538. };
  58539. 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()];
  58540. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  58541. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  58542. return BoneLookController;
  58543. }());
  58544. BABYLON.BoneLookController = BoneLookController;
  58545. })(BABYLON || (BABYLON = {}));
  58546. //# sourceMappingURL=babylon.boneLookController.js.map
  58547. var BABYLON;
  58548. (function (BABYLON) {
  58549. var Skeleton = (function () {
  58550. function Skeleton(name, id, scene) {
  58551. this.name = name;
  58552. this.id = id;
  58553. this.bones = new Array();
  58554. this.needInitialSkinMatrix = false;
  58555. this._isDirty = true;
  58556. this._meshesWithPoseMatrix = new Array();
  58557. this._identity = BABYLON.Matrix.Identity();
  58558. this._ranges = {};
  58559. this._lastAbsoluteTransformsUpdateId = -1;
  58560. // Events
  58561. /**
  58562. * An event triggered before computing the skeleton's matrices
  58563. * @type {BABYLON.Observable}
  58564. */
  58565. this.onBeforeComputeObservable = new BABYLON.Observable();
  58566. this.bones = [];
  58567. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58568. scene.skeletons.push(this);
  58569. //make sure it will recalculate the matrix next time prepare is called.
  58570. this._isDirty = true;
  58571. }
  58572. // Members
  58573. Skeleton.prototype.getTransformMatrices = function (mesh) {
  58574. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  58575. return mesh._bonesTransformMatrices;
  58576. }
  58577. if (!this._transformMatrices) {
  58578. this.prepare();
  58579. }
  58580. return this._transformMatrices;
  58581. };
  58582. Skeleton.prototype.getScene = function () {
  58583. return this._scene;
  58584. };
  58585. // Methods
  58586. /**
  58587. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  58588. */
  58589. Skeleton.prototype.toString = function (fullDetails) {
  58590. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  58591. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  58592. if (fullDetails) {
  58593. ret += ", Ranges: {";
  58594. var first = true;
  58595. for (var name_1 in this._ranges) {
  58596. if (first) {
  58597. ret += ", ";
  58598. first = false;
  58599. }
  58600. ret += name_1;
  58601. }
  58602. ret += "}";
  58603. }
  58604. return ret;
  58605. };
  58606. /**
  58607. * Get bone's index searching by name
  58608. * @param {string} name is bone's name to search for
  58609. * @return {number} Indice of the bone. Returns -1 if not found
  58610. */
  58611. Skeleton.prototype.getBoneIndexByName = function (name) {
  58612. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  58613. if (this.bones[boneIndex].name === name) {
  58614. return boneIndex;
  58615. }
  58616. }
  58617. return -1;
  58618. };
  58619. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  58620. // check name not already in use
  58621. if (!this._ranges[name]) {
  58622. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  58623. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58624. if (this.bones[i].animations[0]) {
  58625. this.bones[i].animations[0].createRange(name, from, to);
  58626. }
  58627. }
  58628. }
  58629. };
  58630. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  58631. if (deleteFrames === void 0) { deleteFrames = true; }
  58632. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58633. if (this.bones[i].animations[0]) {
  58634. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  58635. }
  58636. }
  58637. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  58638. };
  58639. Skeleton.prototype.getAnimationRange = function (name) {
  58640. return this._ranges[name];
  58641. };
  58642. /**
  58643. * Returns as an Array, all AnimationRanges defined on this skeleton
  58644. */
  58645. Skeleton.prototype.getAnimationRanges = function () {
  58646. var animationRanges = [];
  58647. var name;
  58648. var i = 0;
  58649. for (name in this._ranges) {
  58650. animationRanges[i] = this._ranges[name];
  58651. i++;
  58652. }
  58653. return animationRanges;
  58654. };
  58655. /**
  58656. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  58657. */
  58658. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  58659. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  58660. if (this._ranges[name] || !source.getAnimationRange(name)) {
  58661. return false;
  58662. }
  58663. var ret = true;
  58664. var frameOffset = this._getHighestAnimationFrame() + 1;
  58665. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  58666. var boneDict = {};
  58667. var sourceBones = source.bones;
  58668. var nBones;
  58669. var i;
  58670. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  58671. boneDict[sourceBones[i].name] = sourceBones[i];
  58672. }
  58673. if (this.bones.length !== sourceBones.length) {
  58674. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  58675. ret = false;
  58676. }
  58677. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  58678. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  58679. var boneName = this.bones[i].name;
  58680. var sourceBone = boneDict[boneName];
  58681. if (sourceBone) {
  58682. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  58683. }
  58684. else {
  58685. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  58686. ret = false;
  58687. }
  58688. }
  58689. // do not call createAnimationRange(), since it also is done to bones, which was already done
  58690. var range = source.getAnimationRange(name);
  58691. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  58692. return ret;
  58693. };
  58694. Skeleton.prototype.returnToRest = function () {
  58695. for (var index = 0; index < this.bones.length; index++) {
  58696. this.bones[index].returnToRest();
  58697. }
  58698. };
  58699. Skeleton.prototype._getHighestAnimationFrame = function () {
  58700. var ret = 0;
  58701. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  58702. if (this.bones[i].animations[0]) {
  58703. var highest = this.bones[i].animations[0].getHighestFrame();
  58704. if (ret < highest) {
  58705. ret = highest;
  58706. }
  58707. }
  58708. }
  58709. return ret;
  58710. };
  58711. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  58712. var range = this.getAnimationRange(name);
  58713. if (!range) {
  58714. return null;
  58715. }
  58716. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  58717. };
  58718. Skeleton.prototype._markAsDirty = function () {
  58719. this._isDirty = true;
  58720. };
  58721. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  58722. this._meshesWithPoseMatrix.push(mesh);
  58723. };
  58724. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  58725. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  58726. if (index > -1) {
  58727. this._meshesWithPoseMatrix.splice(index, 1);
  58728. }
  58729. };
  58730. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  58731. this.onBeforeComputeObservable.notifyObservers(this);
  58732. for (var index = 0; index < this.bones.length; index++) {
  58733. var bone = this.bones[index];
  58734. var parentBone = bone.getParent();
  58735. if (parentBone) {
  58736. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  58737. }
  58738. else {
  58739. if (initialSkinMatrix) {
  58740. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  58741. }
  58742. else {
  58743. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  58744. }
  58745. }
  58746. if (bone._index !== -1) {
  58747. var mappedIndex = bone._index === undefined ? index : bone._index;
  58748. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  58749. }
  58750. }
  58751. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  58752. };
  58753. Skeleton.prototype.prepare = function () {
  58754. if (!this._isDirty) {
  58755. return;
  58756. }
  58757. if (this.needInitialSkinMatrix) {
  58758. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  58759. var mesh = this._meshesWithPoseMatrix[index];
  58760. var poseMatrix = mesh.getPoseMatrix();
  58761. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  58762. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58763. }
  58764. if (this._synchronizedWithMesh !== mesh) {
  58765. this._synchronizedWithMesh = mesh;
  58766. // Prepare bones
  58767. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  58768. var bone = this.bones[boneIndex];
  58769. if (!bone.getParent()) {
  58770. var matrix = bone.getBaseMatrix();
  58771. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  58772. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  58773. }
  58774. }
  58775. }
  58776. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  58777. }
  58778. }
  58779. else {
  58780. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  58781. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  58782. }
  58783. this._computeTransformMatrices(this._transformMatrices, null);
  58784. }
  58785. this._isDirty = false;
  58786. this._scene._activeBones.addCount(this.bones.length, false);
  58787. };
  58788. Skeleton.prototype.getAnimatables = function () {
  58789. if (!this._animatables || this._animatables.length !== this.bones.length) {
  58790. this._animatables = [];
  58791. for (var index = 0; index < this.bones.length; index++) {
  58792. this._animatables.push(this.bones[index]);
  58793. }
  58794. }
  58795. return this._animatables;
  58796. };
  58797. Skeleton.prototype.clone = function (name, id) {
  58798. var result = new Skeleton(name, id || name, this._scene);
  58799. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58800. for (var index = 0; index < this.bones.length; index++) {
  58801. var source = this.bones[index];
  58802. var parentBone = null;
  58803. if (source.getParent()) {
  58804. var parentIndex = this.bones.indexOf(source.getParent());
  58805. parentBone = result.bones[parentIndex];
  58806. }
  58807. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  58808. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  58809. }
  58810. if (this._ranges) {
  58811. result._ranges = {};
  58812. for (var rangeName in this._ranges) {
  58813. result._ranges[rangeName] = this._ranges[rangeName].clone();
  58814. }
  58815. }
  58816. this._isDirty = true;
  58817. return result;
  58818. };
  58819. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  58820. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  58821. this.bones.forEach(function (bone) {
  58822. bone.animations.forEach(function (animation) {
  58823. animation.enableBlending = true;
  58824. animation.blendingSpeed = blendingSpeed;
  58825. });
  58826. });
  58827. };
  58828. Skeleton.prototype.dispose = function () {
  58829. this._meshesWithPoseMatrix = [];
  58830. // Animations
  58831. this.getScene().stopAnimation(this);
  58832. // Remove from scene
  58833. this.getScene().removeSkeleton(this);
  58834. };
  58835. Skeleton.prototype.serialize = function () {
  58836. var serializationObject = {};
  58837. serializationObject.name = this.name;
  58838. serializationObject.id = this.id;
  58839. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  58840. serializationObject.bones = [];
  58841. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  58842. for (var index = 0; index < this.bones.length; index++) {
  58843. var bone = this.bones[index];
  58844. var serializedBone = {
  58845. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  58846. name: bone.name,
  58847. matrix: bone.getBaseMatrix().toArray(),
  58848. rest: bone.getRestPose().toArray()
  58849. };
  58850. serializationObject.bones.push(serializedBone);
  58851. if (bone.length) {
  58852. serializedBone.length = bone.length;
  58853. }
  58854. if (bone.animations && bone.animations.length > 0) {
  58855. serializedBone.animation = bone.animations[0].serialize();
  58856. }
  58857. serializationObject.ranges = [];
  58858. for (var name in this._ranges) {
  58859. var range = {};
  58860. range.name = name;
  58861. range.from = this._ranges[name].from;
  58862. range.to = this._ranges[name].to;
  58863. serializationObject.ranges.push(range);
  58864. }
  58865. }
  58866. return serializationObject;
  58867. };
  58868. Skeleton.Parse = function (parsedSkeleton, scene) {
  58869. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  58870. if (parsedSkeleton.dimensionsAtRest) {
  58871. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  58872. }
  58873. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  58874. var index;
  58875. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  58876. var parsedBone = parsedSkeleton.bones[index];
  58877. var parentBone = null;
  58878. if (parsedBone.parentBoneIndex > -1) {
  58879. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  58880. }
  58881. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  58882. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  58883. if (parsedBone.length) {
  58884. bone.length = parsedBone.length;
  58885. }
  58886. if (parsedBone.animation) {
  58887. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  58888. }
  58889. }
  58890. // placed after bones, so createAnimationRange can cascade down
  58891. if (parsedSkeleton.ranges) {
  58892. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  58893. var data = parsedSkeleton.ranges[index];
  58894. skeleton.createAnimationRange(data.name, data.from, data.to);
  58895. }
  58896. }
  58897. return skeleton;
  58898. };
  58899. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  58900. if (forceUpdate === void 0) { forceUpdate = false; }
  58901. var renderId = this._scene.getRenderId();
  58902. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  58903. this.bones[0].computeAbsoluteTransforms();
  58904. this._lastAbsoluteTransformsUpdateId = renderId;
  58905. }
  58906. };
  58907. Skeleton.prototype.getPoseMatrix = function () {
  58908. var poseMatrix;
  58909. if (this._meshesWithPoseMatrix.length > 0) {
  58910. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  58911. }
  58912. return poseMatrix;
  58913. };
  58914. Skeleton.prototype.sortBones = function () {
  58915. var bones = new Array();
  58916. var visited = new Array(this.bones.length);
  58917. for (var index = 0; index < this.bones.length; index++) {
  58918. this._sortBones(index, bones, visited);
  58919. }
  58920. this.bones = bones;
  58921. };
  58922. Skeleton.prototype._sortBones = function (index, bones, visited) {
  58923. if (visited[index]) {
  58924. return;
  58925. }
  58926. visited[index] = true;
  58927. var bone = this.bones[index];
  58928. if (bone._index === undefined) {
  58929. bone._index = index;
  58930. }
  58931. var parentBone = bone.getParent();
  58932. if (parentBone) {
  58933. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  58934. }
  58935. bones.push(bone);
  58936. };
  58937. return Skeleton;
  58938. }());
  58939. BABYLON.Skeleton = Skeleton;
  58940. })(BABYLON || (BABYLON = {}));
  58941. //# sourceMappingURL=babylon.skeleton.js.map
  58942. var BABYLON;
  58943. (function (BABYLON) {
  58944. var SphericalPolynomial = (function () {
  58945. function SphericalPolynomial() {
  58946. this.x = BABYLON.Vector3.Zero();
  58947. this.y = BABYLON.Vector3.Zero();
  58948. this.z = BABYLON.Vector3.Zero();
  58949. this.xx = BABYLON.Vector3.Zero();
  58950. this.yy = BABYLON.Vector3.Zero();
  58951. this.zz = BABYLON.Vector3.Zero();
  58952. this.xy = BABYLON.Vector3.Zero();
  58953. this.yz = BABYLON.Vector3.Zero();
  58954. this.zx = BABYLON.Vector3.Zero();
  58955. }
  58956. SphericalPolynomial.prototype.addAmbient = function (color) {
  58957. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58958. this.xx = this.xx.add(colorVector);
  58959. this.yy = this.yy.add(colorVector);
  58960. this.zz = this.zz.add(colorVector);
  58961. };
  58962. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  58963. var result = new SphericalPolynomial();
  58964. result.x = harmonics.L11.scale(1.02333);
  58965. result.y = harmonics.L1_1.scale(1.02333);
  58966. result.z = harmonics.L10.scale(1.02333);
  58967. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  58968. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  58969. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  58970. result.yz = harmonics.L2_1.scale(0.858086);
  58971. result.zx = harmonics.L21.scale(0.858086);
  58972. result.xy = harmonics.L2_2.scale(0.858086);
  58973. result.scale(1.0 / Math.PI);
  58974. return result;
  58975. };
  58976. SphericalPolynomial.prototype.scale = function (scale) {
  58977. this.x = this.x.scale(scale);
  58978. this.y = this.y.scale(scale);
  58979. this.z = this.z.scale(scale);
  58980. this.xx = this.xx.scale(scale);
  58981. this.yy = this.yy.scale(scale);
  58982. this.zz = this.zz.scale(scale);
  58983. this.yz = this.yz.scale(scale);
  58984. this.zx = this.zx.scale(scale);
  58985. this.xy = this.xy.scale(scale);
  58986. };
  58987. return SphericalPolynomial;
  58988. }());
  58989. BABYLON.SphericalPolynomial = SphericalPolynomial;
  58990. var SphericalHarmonics = (function () {
  58991. function SphericalHarmonics() {
  58992. this.L00 = BABYLON.Vector3.Zero();
  58993. this.L1_1 = BABYLON.Vector3.Zero();
  58994. this.L10 = BABYLON.Vector3.Zero();
  58995. this.L11 = BABYLON.Vector3.Zero();
  58996. this.L2_2 = BABYLON.Vector3.Zero();
  58997. this.L2_1 = BABYLON.Vector3.Zero();
  58998. this.L20 = BABYLON.Vector3.Zero();
  58999. this.L21 = BABYLON.Vector3.Zero();
  59000. this.L22 = BABYLON.Vector3.Zero();
  59001. }
  59002. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  59003. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  59004. var c = colorVector.scale(deltaSolidAngle);
  59005. this.L00 = this.L00.add(c.scale(0.282095));
  59006. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  59007. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  59008. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  59009. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  59010. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  59011. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  59012. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  59013. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  59014. };
  59015. SphericalHarmonics.prototype.scale = function (scale) {
  59016. this.L00 = this.L00.scale(scale);
  59017. this.L1_1 = this.L1_1.scale(scale);
  59018. this.L10 = this.L10.scale(scale);
  59019. this.L11 = this.L11.scale(scale);
  59020. this.L2_2 = this.L2_2.scale(scale);
  59021. this.L2_1 = this.L2_1.scale(scale);
  59022. this.L20 = this.L20.scale(scale);
  59023. this.L21 = this.L21.scale(scale);
  59024. this.L22 = this.L22.scale(scale);
  59025. };
  59026. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  59027. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  59028. //
  59029. // E_lm = A_l * L_lm
  59030. //
  59031. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  59032. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  59033. // the scaling factors are given in equation 9.
  59034. // Constant (Band 0)
  59035. this.L00 = this.L00.scale(3.141593);
  59036. // Linear (Band 1)
  59037. this.L1_1 = this.L1_1.scale(2.094395);
  59038. this.L10 = this.L10.scale(2.094395);
  59039. this.L11 = this.L11.scale(2.094395);
  59040. // Quadratic (Band 2)
  59041. this.L2_2 = this.L2_2.scale(0.785398);
  59042. this.L2_1 = this.L2_1.scale(0.785398);
  59043. this.L20 = this.L20.scale(0.785398);
  59044. this.L21 = this.L21.scale(0.785398);
  59045. this.L22 = this.L22.scale(0.785398);
  59046. };
  59047. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  59048. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  59049. // L = (1/pi) * E * rho
  59050. //
  59051. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  59052. this.scale(1.0 / Math.PI);
  59053. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  59054. // (The pixel shader must apply albedo after texture fetches, etc).
  59055. };
  59056. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  59057. var result = new SphericalHarmonics();
  59058. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  59059. result.L1_1 = polynomial.y.scale(0.977204);
  59060. result.L10 = polynomial.z.scale(0.977204);
  59061. result.L11 = polynomial.x.scale(0.977204);
  59062. result.L2_2 = polynomial.xy.scale(1.16538);
  59063. result.L2_1 = polynomial.yz.scale(1.16538);
  59064. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  59065. result.L21 = polynomial.zx.scale(1.16538);
  59066. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  59067. result.scale(Math.PI);
  59068. return result;
  59069. };
  59070. return SphericalHarmonics;
  59071. }());
  59072. BABYLON.SphericalHarmonics = SphericalHarmonics;
  59073. })(BABYLON || (BABYLON = {}));
  59074. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  59075. var BABYLON;
  59076. (function (BABYLON) {
  59077. var Internals;
  59078. (function (Internals) {
  59079. var FileFaceOrientation = (function () {
  59080. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  59081. this.name = name;
  59082. this.worldAxisForNormal = worldAxisForNormal;
  59083. this.worldAxisForFileX = worldAxisForFileX;
  59084. this.worldAxisForFileY = worldAxisForFileY;
  59085. }
  59086. return FileFaceOrientation;
  59087. }());
  59088. ;
  59089. /**
  59090. * Helper class dealing with the extraction of spherical polynomial dataArray
  59091. * from a cube map.
  59092. */
  59093. var CubeMapToSphericalPolynomialTools = (function () {
  59094. function CubeMapToSphericalPolynomialTools() {
  59095. }
  59096. /**
  59097. * Converts a texture to the according Spherical Polynomial data.
  59098. * This extracts the first 3 orders only as they are the only one used in the lighting.
  59099. *
  59100. * @param texture The texture to extract the information from.
  59101. * @return The Spherical Polynomial data.
  59102. */
  59103. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  59104. if (!texture.isCube) {
  59105. // Only supports cube Textures currently.
  59106. return null;
  59107. }
  59108. var size = texture.getSize().width;
  59109. var right = texture.readPixels(0);
  59110. var left = texture.readPixels(1);
  59111. var up;
  59112. var down;
  59113. if (texture.isRenderTarget) {
  59114. up = texture.readPixels(3);
  59115. down = texture.readPixels(2);
  59116. }
  59117. else {
  59118. up = texture.readPixels(2);
  59119. down = texture.readPixels(3);
  59120. }
  59121. var front = texture.readPixels(4);
  59122. var back = texture.readPixels(5);
  59123. var gammaSpace = texture.gammaSpace;
  59124. // Always read as RGBA.
  59125. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  59126. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59127. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59128. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59129. }
  59130. var cubeInfo = {
  59131. size: size,
  59132. right: right,
  59133. left: left,
  59134. up: up,
  59135. down: down,
  59136. front: front,
  59137. back: back,
  59138. format: format,
  59139. type: type,
  59140. gammaSpace: gammaSpace,
  59141. };
  59142. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  59143. };
  59144. /**
  59145. * Converts a cubemap to the according Spherical Polynomial data.
  59146. * This extracts the first 3 orders only as they are the only one used in the lighting.
  59147. *
  59148. * @param cubeInfo The Cube map to extract the information from.
  59149. * @return The Spherical Polynomial data.
  59150. */
  59151. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  59152. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  59153. var totalSolidAngle = 0.0;
  59154. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  59155. var du = 2.0 / cubeInfo.size;
  59156. var dv = du;
  59157. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  59158. var minUV = du * 0.5 - 1.0;
  59159. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59160. var fileFace = this.FileFaces[faceIndex];
  59161. var dataArray = cubeInfo[fileFace.name];
  59162. var v = minUV;
  59163. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  59164. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  59165. // Because SP is still linear, so summation is fine in that basis.
  59166. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  59167. for (var y = 0; y < cubeInfo.size; y++) {
  59168. var u = minUV;
  59169. for (var x = 0; x < cubeInfo.size; x++) {
  59170. // World direction (not normalised)
  59171. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  59172. worldDirection.normalize();
  59173. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  59174. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  59175. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  59176. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  59177. // Handle Integer types.
  59178. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59179. r /= 255;
  59180. g /= 255;
  59181. b /= 255;
  59182. }
  59183. // Handle Gamma space textures.
  59184. if (cubeInfo.gammaSpace) {
  59185. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  59186. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  59187. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  59188. }
  59189. var color = new BABYLON.Color3(r, g, b);
  59190. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  59191. totalSolidAngle += deltaSolidAngle;
  59192. u += du;
  59193. }
  59194. v += dv;
  59195. }
  59196. }
  59197. // Solid angle for entire sphere is 4*pi
  59198. var sphereSolidAngle = 4.0 * Math.PI;
  59199. // Adjust the solid angle to allow for how many faces we processed.
  59200. var facesProcessed = 6.0;
  59201. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  59202. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  59203. // This is needed because the numerical integration over the cube uses a
  59204. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  59205. // and also to compensate for accumulative error due to float precision in the summation.
  59206. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  59207. sphericalHarmonics.scale(correctionFactor);
  59208. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  59209. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  59210. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  59211. };
  59212. CubeMapToSphericalPolynomialTools.FileFaces = [
  59213. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  59214. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  59215. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  59216. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  59217. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  59218. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  59219. ];
  59220. return CubeMapToSphericalPolynomialTools;
  59221. }());
  59222. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  59223. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59224. })(BABYLON || (BABYLON = {}));
  59225. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  59226. var BABYLON;
  59227. (function (BABYLON) {
  59228. var Internals;
  59229. (function (Internals) {
  59230. /**
  59231. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  59232. */
  59233. var PanoramaToCubeMapTools = (function () {
  59234. function PanoramaToCubeMapTools() {
  59235. }
  59236. /**
  59237. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  59238. *
  59239. * @param float32Array The source data.
  59240. * @param inputWidth The width of the input panorama.
  59241. * @param inputhHeight The height of the input panorama.
  59242. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  59243. * @return The cubemap data
  59244. */
  59245. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  59246. if (!float32Array) {
  59247. throw "ConvertPanoramaToCubemap: input cannot be null";
  59248. }
  59249. if (float32Array.length != inputWidth * inputHeight * 3) {
  59250. throw "ConvertPanoramaToCubemap: input size is wrong";
  59251. }
  59252. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  59253. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  59254. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  59255. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  59256. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  59257. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  59258. return {
  59259. front: textureFront,
  59260. back: textureBack,
  59261. left: textureLeft,
  59262. right: textureRight,
  59263. up: textureUp,
  59264. down: textureDown,
  59265. size: size,
  59266. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  59267. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  59268. gammaSpace: false,
  59269. };
  59270. };
  59271. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  59272. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  59273. var textureArray = new Float32Array(buffer);
  59274. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  59275. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  59276. var dy = 1 / texSize;
  59277. var fy = 0;
  59278. for (var y = 0; y < texSize; y++) {
  59279. var xv1 = faceData[0];
  59280. var xv2 = faceData[2];
  59281. for (var x = 0; x < texSize; x++) {
  59282. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  59283. v.normalize();
  59284. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  59285. // 3 channels per pixels
  59286. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  59287. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  59288. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  59289. xv1 = xv1.add(rotDX1);
  59290. xv2 = xv2.add(rotDX2);
  59291. }
  59292. fy += dy;
  59293. }
  59294. return textureArray;
  59295. };
  59296. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  59297. var theta = Math.atan2(vDir.z, vDir.x);
  59298. var phi = Math.acos(vDir.y);
  59299. while (theta < -Math.PI)
  59300. theta += 2 * Math.PI;
  59301. while (theta > Math.PI)
  59302. theta -= 2 * Math.PI;
  59303. var dx = theta / Math.PI;
  59304. var dy = phi / Math.PI;
  59305. // recenter.
  59306. dx = dx * 0.5 + 0.5;
  59307. var px = Math.round(dx * inputWidth);
  59308. if (px < 0)
  59309. px = 0;
  59310. else if (px >= inputWidth)
  59311. px = inputWidth - 1;
  59312. var py = Math.round(dy * inputHeight);
  59313. if (py < 0)
  59314. py = 0;
  59315. else if (py >= inputHeight)
  59316. py = inputHeight - 1;
  59317. var inputY = (inputHeight - py - 1);
  59318. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  59319. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  59320. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  59321. return {
  59322. r: r,
  59323. g: g,
  59324. b: b
  59325. };
  59326. };
  59327. PanoramaToCubeMapTools.FACE_FRONT = [
  59328. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  59329. new BABYLON.Vector3(1.0, -1.0, -1.0),
  59330. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  59331. new BABYLON.Vector3(1.0, 1.0, -1.0)
  59332. ];
  59333. PanoramaToCubeMapTools.FACE_BACK = [
  59334. new BABYLON.Vector3(1.0, -1.0, 1.0),
  59335. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  59336. new BABYLON.Vector3(1.0, 1.0, 1.0),
  59337. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  59338. ];
  59339. PanoramaToCubeMapTools.FACE_RIGHT = [
  59340. new BABYLON.Vector3(1.0, -1.0, -1.0),
  59341. new BABYLON.Vector3(1.0, -1.0, 1.0),
  59342. new BABYLON.Vector3(1.0, 1.0, -1.0),
  59343. new BABYLON.Vector3(1.0, 1.0, 1.0)
  59344. ];
  59345. PanoramaToCubeMapTools.FACE_LEFT = [
  59346. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  59347. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  59348. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  59349. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  59350. ];
  59351. PanoramaToCubeMapTools.FACE_DOWN = [
  59352. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  59353. new BABYLON.Vector3(1.0, 1.0, -1.0),
  59354. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  59355. new BABYLON.Vector3(1.0, 1.0, 1.0)
  59356. ];
  59357. PanoramaToCubeMapTools.FACE_UP = [
  59358. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  59359. new BABYLON.Vector3(1.0, -1.0, 1.0),
  59360. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  59361. new BABYLON.Vector3(1.0, -1.0, -1.0)
  59362. ];
  59363. return PanoramaToCubeMapTools;
  59364. }());
  59365. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  59366. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59367. })(BABYLON || (BABYLON = {}));
  59368. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  59369. var BABYLON;
  59370. (function (BABYLON) {
  59371. var Internals;
  59372. (function (Internals) {
  59373. ;
  59374. /**
  59375. * This groups tools to convert HDR texture to native colors array.
  59376. */
  59377. var HDRTools = (function () {
  59378. function HDRTools() {
  59379. }
  59380. HDRTools.Ldexp = function (mantissa, exponent) {
  59381. if (exponent > 1023) {
  59382. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  59383. }
  59384. if (exponent < -1074) {
  59385. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  59386. }
  59387. return mantissa * Math.pow(2, exponent);
  59388. };
  59389. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  59390. if (exponent > 0) {
  59391. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  59392. float32array[index + 0] = red * exponent;
  59393. float32array[index + 1] = green * exponent;
  59394. float32array[index + 2] = blue * exponent;
  59395. }
  59396. else {
  59397. float32array[index + 0] = 0;
  59398. float32array[index + 1] = 0;
  59399. float32array[index + 2] = 0;
  59400. }
  59401. };
  59402. HDRTools.readStringLine = function (uint8array, startIndex) {
  59403. var line = "";
  59404. var character = "";
  59405. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  59406. character = String.fromCharCode(uint8array[i]);
  59407. if (character == "\n") {
  59408. break;
  59409. }
  59410. line += character;
  59411. }
  59412. return line;
  59413. };
  59414. /**
  59415. * Reads header information from an RGBE texture stored in a native array.
  59416. * More information on this format are available here:
  59417. * https://en.wikipedia.org/wiki/RGBE_image_format
  59418. *
  59419. * @param uint8array The binary file stored in native array.
  59420. * @return The header information.
  59421. */
  59422. HDRTools.RGBE_ReadHeader = function (uint8array) {
  59423. var height = 0;
  59424. var width = 0;
  59425. var line = this.readStringLine(uint8array, 0);
  59426. if (line[0] != '#' || line[1] != '?') {
  59427. throw "Bad HDR Format.";
  59428. }
  59429. var endOfHeader = false;
  59430. var findFormat = false;
  59431. var lineIndex = 0;
  59432. do {
  59433. lineIndex += (line.length + 1);
  59434. line = this.readStringLine(uint8array, lineIndex);
  59435. if (line == "FORMAT=32-bit_rle_rgbe") {
  59436. findFormat = true;
  59437. }
  59438. else if (line.length == 0) {
  59439. endOfHeader = true;
  59440. }
  59441. } while (!endOfHeader);
  59442. if (!findFormat) {
  59443. throw "HDR Bad header format, unsupported FORMAT";
  59444. }
  59445. lineIndex += (line.length + 1);
  59446. line = this.readStringLine(uint8array, lineIndex);
  59447. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  59448. var match = sizeRegexp.exec(line);
  59449. // TODO. Support +Y and -X if needed.
  59450. if (match.length < 3) {
  59451. throw "HDR Bad header format, no size";
  59452. }
  59453. width = parseInt(match[2]);
  59454. height = parseInt(match[1]);
  59455. if (width < 8 || width > 0x7fff) {
  59456. throw "HDR Bad header format, unsupported size";
  59457. }
  59458. lineIndex += (line.length + 1);
  59459. return {
  59460. height: height,
  59461. width: width,
  59462. dataPosition: lineIndex
  59463. };
  59464. };
  59465. /**
  59466. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  59467. * This RGBE texture needs to store the information as a panorama.
  59468. *
  59469. * More information on this format are available here:
  59470. * https://en.wikipedia.org/wiki/RGBE_image_format
  59471. *
  59472. * @param buffer The binary file stored in an array buffer.
  59473. * @param size The expected size of the extracted cubemap.
  59474. * @return The Cube Map information.
  59475. */
  59476. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  59477. var uint8array = new Uint8Array(buffer);
  59478. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  59479. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  59480. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  59481. return cubeMapData;
  59482. };
  59483. /**
  59484. * Returns the pixels data extracted from an RGBE texture.
  59485. * This pixels will be stored left to right up to down in the R G B order in one array.
  59486. *
  59487. * More information on this format are available here:
  59488. * https://en.wikipedia.org/wiki/RGBE_image_format
  59489. *
  59490. * @param uint8array The binary file stored in an array buffer.
  59491. * @param hdrInfo The header information of the file.
  59492. * @return The pixels data in RGB right to left up to down order.
  59493. */
  59494. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  59495. // Keep for multi format supports.
  59496. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  59497. };
  59498. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  59499. var num_scanlines = hdrInfo.height;
  59500. var scanline_width = hdrInfo.width;
  59501. var a, b, c, d, count;
  59502. var dataIndex = hdrInfo.dataPosition;
  59503. var index = 0, endIndex = 0, i = 0;
  59504. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  59505. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  59506. // 3 channels of 4 bytes per pixel in float.
  59507. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  59508. var resultArray = new Float32Array(resultBuffer);
  59509. // read in each successive scanline
  59510. while (num_scanlines > 0) {
  59511. a = uint8array[dataIndex++];
  59512. b = uint8array[dataIndex++];
  59513. c = uint8array[dataIndex++];
  59514. d = uint8array[dataIndex++];
  59515. if (a != 2 || b != 2 || (c & 0x80)) {
  59516. // this file is not run length encoded
  59517. throw "HDR Bad header format, not RLE";
  59518. }
  59519. if (((c << 8) | d) != scanline_width) {
  59520. throw "HDR Bad header format, wrong scan line width";
  59521. }
  59522. index = 0;
  59523. // read each of the four channels for the scanline into the buffer
  59524. for (i = 0; i < 4; i++) {
  59525. endIndex = (i + 1) * scanline_width;
  59526. while (index < endIndex) {
  59527. a = uint8array[dataIndex++];
  59528. b = uint8array[dataIndex++];
  59529. if (a > 128) {
  59530. // a run of the same value
  59531. count = a - 128;
  59532. if ((count == 0) || (count > endIndex - index)) {
  59533. throw "HDR Bad Format, bad scanline data (run)";
  59534. }
  59535. while (count-- > 0) {
  59536. scanLineArray[index++] = b;
  59537. }
  59538. }
  59539. else {
  59540. // a non-run
  59541. count = a;
  59542. if ((count == 0) || (count > endIndex - index)) {
  59543. throw "HDR Bad Format, bad scanline data (non-run)";
  59544. }
  59545. scanLineArray[index++] = b;
  59546. if (--count > 0) {
  59547. for (var j = 0; j < count; j++) {
  59548. scanLineArray[index++] = uint8array[dataIndex++];
  59549. }
  59550. }
  59551. }
  59552. }
  59553. }
  59554. // now convert data from buffer into floats
  59555. for (i = 0; i < scanline_width; i++) {
  59556. a = scanLineArray[i];
  59557. b = scanLineArray[i + scanline_width];
  59558. c = scanLineArray[i + 2 * scanline_width];
  59559. d = scanLineArray[i + 3 * scanline_width];
  59560. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  59561. }
  59562. num_scanlines--;
  59563. }
  59564. return resultArray;
  59565. };
  59566. return HDRTools;
  59567. }());
  59568. Internals.HDRTools = HDRTools;
  59569. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59570. })(BABYLON || (BABYLON = {}));
  59571. //# sourceMappingURL=babylon.hdr.js.map
  59572. var BABYLON;
  59573. (function (BABYLON) {
  59574. /**
  59575. * This represents a texture coming from an HDR input.
  59576. *
  59577. * The only supported format is currently panorama picture stored in RGBE format.
  59578. * Example of such files can be found on HDRLib: http://hdrlib.com/
  59579. */
  59580. var HDRCubeTexture = (function (_super) {
  59581. __extends(HDRCubeTexture, _super);
  59582. /**
  59583. * Instantiates an HDRTexture from the following parameters.
  59584. *
  59585. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  59586. * @param scene The scene the texture will be used in
  59587. * @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.
  59588. * @param noMipmap Forces to not generate the mipmap if true
  59589. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  59590. * @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)
  59591. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  59592. */
  59593. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  59594. if (noMipmap === void 0) { noMipmap = false; }
  59595. if (generateHarmonics === void 0) { generateHarmonics = true; }
  59596. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  59597. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  59598. if (onLoad === void 0) { onLoad = null; }
  59599. if (onError === void 0) { onError = null; }
  59600. var _this = _super.call(this, scene) || this;
  59601. _this._useInGammaSpace = false;
  59602. _this._generateHarmonics = true;
  59603. _this._isBABYLONPreprocessed = false;
  59604. _this._onLoad = null;
  59605. _this._onError = null;
  59606. /**
  59607. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  59608. */
  59609. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59610. /**
  59611. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  59612. * This is usefull at run time to apply the good shader.
  59613. */
  59614. _this.isPMREM = false;
  59615. _this._isBlocking = true;
  59616. if (!url) {
  59617. return _this;
  59618. }
  59619. _this.name = url;
  59620. _this.url = url;
  59621. _this.hasAlpha = false;
  59622. _this.isCube = true;
  59623. _this._textureMatrix = BABYLON.Matrix.Identity();
  59624. _this._onLoad = onLoad;
  59625. _this._onError = onError;
  59626. _this.gammaSpace = false;
  59627. if (size) {
  59628. _this._isBABYLONPreprocessed = false;
  59629. _this._noMipmap = noMipmap;
  59630. _this._size = size;
  59631. _this._useInGammaSpace = useInGammaSpace;
  59632. _this._usePMREMGenerator = usePMREMGenerator &&
  59633. scene.getEngine().getCaps().textureLOD &&
  59634. _this.getScene().getEngine().getCaps().textureFloat &&
  59635. !_this._useInGammaSpace;
  59636. }
  59637. else {
  59638. _this._isBABYLONPreprocessed = true;
  59639. _this._noMipmap = false;
  59640. _this._useInGammaSpace = false;
  59641. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  59642. _this.getScene().getEngine().getCaps().textureFloat &&
  59643. !_this._useInGammaSpace;
  59644. }
  59645. _this.isPMREM = _this._usePMREMGenerator;
  59646. _this._texture = _this._getFromCache(url, _this._noMipmap);
  59647. if (!_this._texture) {
  59648. if (!scene.useDelayedTextureLoading) {
  59649. _this.loadTexture();
  59650. }
  59651. else {
  59652. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59653. }
  59654. }
  59655. return _this;
  59656. }
  59657. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  59658. /**
  59659. * Gets wether or not the texture is blocking during loading.
  59660. */
  59661. get: function () {
  59662. return this._isBlocking;
  59663. },
  59664. /**
  59665. * Sets wether or not the texture is blocking during loading.
  59666. */
  59667. set: function (value) {
  59668. this._isBlocking = value;
  59669. },
  59670. enumerable: true,
  59671. configurable: true
  59672. });
  59673. /**
  59674. * Occurs when the file is a preprocessed .babylon.hdr file.
  59675. */
  59676. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  59677. var _this = this;
  59678. var mipLevels = 0;
  59679. var floatArrayView = null;
  59680. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  59681. var mips = [];
  59682. var startIndex = 30;
  59683. for (var level = 0; level < mipLevels; level++) {
  59684. mips.push([]);
  59685. // Fill each pixel of the mip level.
  59686. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  59687. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59688. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  59689. mips[level].push(faceData);
  59690. startIndex += faceSize;
  59691. }
  59692. }
  59693. return mips;
  59694. } : null;
  59695. var callback = function (buffer) {
  59696. // Create Native Array Views
  59697. var intArrayView = new Int32Array(buffer);
  59698. floatArrayView = new Float32Array(buffer);
  59699. // Fill header.
  59700. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  59701. _this._size = intArrayView[1]; // CubeMap max mip face size.
  59702. // Update Texture Information.
  59703. _this._texture.updateSize(_this._size, _this._size);
  59704. // Fill polynomial information.
  59705. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59706. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59707. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59708. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59709. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59710. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59711. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59712. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59713. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59714. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59715. _this.sphericalPolynomial = sphericalPolynomial;
  59716. // Fill pixel data.
  59717. mipLevels = intArrayView[29]; // Number of mip levels.
  59718. var startIndex = 30;
  59719. var data = [];
  59720. var faceSize = Math.pow(_this._size, 2) * 3;
  59721. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59722. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59723. startIndex += faceSize;
  59724. }
  59725. var results = [];
  59726. var byteArray = null;
  59727. // Push each faces.
  59728. for (var k = 0; k < 6; k++) {
  59729. var dataFace = null;
  59730. // To be deprecated.
  59731. if (version === 1) {
  59732. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  59733. dataFace = data[j];
  59734. }
  59735. // If special cases.
  59736. if (!mipmapGenerator) {
  59737. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59738. // 3 channels of 1 bytes per pixel in bytes.
  59739. var byteBuffer = new ArrayBuffer(faceSize);
  59740. byteArray = new Uint8Array(byteBuffer);
  59741. }
  59742. for (var i = 0; i < _this._size * _this._size; i++) {
  59743. // Put in gamma space if requested.
  59744. if (_this._useInGammaSpace) {
  59745. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59746. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59747. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59748. }
  59749. // Convert to int texture for fallback.
  59750. if (byteArray) {
  59751. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59752. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59753. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59754. // May use luminance instead if the result is not accurate.
  59755. var max = Math.max(Math.max(r, g), b);
  59756. if (max > 255) {
  59757. var scale = 255 / max;
  59758. r *= scale;
  59759. g *= scale;
  59760. b *= scale;
  59761. }
  59762. byteArray[(i * 3) + 0] = r;
  59763. byteArray[(i * 3) + 1] = g;
  59764. byteArray[(i * 3) + 2] = b;
  59765. }
  59766. }
  59767. }
  59768. // Fill the array accordingly.
  59769. if (byteArray) {
  59770. results.push(byteArray);
  59771. }
  59772. else {
  59773. results.push(dataFace);
  59774. }
  59775. }
  59776. return results;
  59777. };
  59778. 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);
  59779. };
  59780. /**
  59781. * Occurs when the file is raw .hdr file.
  59782. */
  59783. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59784. var _this = this;
  59785. var callback = function (buffer) {
  59786. // Extract the raw linear data.
  59787. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59788. // Generate harmonics if needed.
  59789. if (_this._generateHarmonics) {
  59790. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59791. _this.sphericalPolynomial = sphericalPolynomial;
  59792. }
  59793. var results = [];
  59794. var byteArray = null;
  59795. // Push each faces.
  59796. for (var j = 0; j < 6; j++) {
  59797. // Create uintarray fallback.
  59798. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59799. // 3 channels of 1 bytes per pixel in bytes.
  59800. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59801. byteArray = new Uint8Array(byteBuffer);
  59802. }
  59803. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59804. // If special cases.
  59805. if (_this._useInGammaSpace || byteArray) {
  59806. for (var i = 0; i < _this._size * _this._size; i++) {
  59807. // Put in gamma space if requested.
  59808. if (_this._useInGammaSpace) {
  59809. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59810. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59811. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59812. }
  59813. // Convert to int texture for fallback.
  59814. if (byteArray) {
  59815. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59816. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59817. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59818. // May use luminance instead if the result is not accurate.
  59819. var max = Math.max(Math.max(r, g), b);
  59820. if (max > 255) {
  59821. var scale = 255 / max;
  59822. r *= scale;
  59823. g *= scale;
  59824. b *= scale;
  59825. }
  59826. byteArray[(i * 3) + 0] = r;
  59827. byteArray[(i * 3) + 1] = g;
  59828. byteArray[(i * 3) + 2] = b;
  59829. }
  59830. }
  59831. }
  59832. if (byteArray) {
  59833. results.push(byteArray);
  59834. }
  59835. else {
  59836. results.push(dataFace);
  59837. }
  59838. }
  59839. return results;
  59840. };
  59841. var mipmapGenerator = null;
  59842. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  59843. // if (!this._noMipmap &&
  59844. // this._usePMREMGenerator) {
  59845. // mipmapGenerator = (data: ArrayBufferView[]) => {
  59846. // // Custom setup of the generator matching with the PBR shader values.
  59847. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  59848. // this._size,
  59849. // this._size,
  59850. // 0,
  59851. // 3,
  59852. // this.getScene().getEngine().getCaps().textureFloat,
  59853. // 2048,
  59854. // 0.25,
  59855. // false,
  59856. // true);
  59857. // return generator.filterCubeMap();
  59858. // };
  59859. // }
  59860. 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);
  59861. };
  59862. /**
  59863. * Starts the loading process of the texture.
  59864. */
  59865. HDRCubeTexture.prototype.loadTexture = function () {
  59866. if (this._isBABYLONPreprocessed) {
  59867. this.loadBabylonTexture();
  59868. }
  59869. else {
  59870. this.loadHDRTexture();
  59871. }
  59872. };
  59873. HDRCubeTexture.prototype.clone = function () {
  59874. var size = this._isBABYLONPreprocessed ? null : this._size;
  59875. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59876. // Base texture
  59877. newTexture.level = this.level;
  59878. newTexture.wrapU = this.wrapU;
  59879. newTexture.wrapV = this.wrapV;
  59880. newTexture.coordinatesIndex = this.coordinatesIndex;
  59881. newTexture.coordinatesMode = this.coordinatesMode;
  59882. return newTexture;
  59883. };
  59884. // Methods
  59885. HDRCubeTexture.prototype.delayLoad = function () {
  59886. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59887. return;
  59888. }
  59889. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59890. this._texture = this._getFromCache(this.url, this._noMipmap);
  59891. if (!this._texture) {
  59892. this.loadTexture();
  59893. }
  59894. };
  59895. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59896. return this._textureMatrix;
  59897. };
  59898. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59899. this._textureMatrix = value;
  59900. };
  59901. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59902. var texture = null;
  59903. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59904. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59905. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  59906. texture.name = parsedTexture.name;
  59907. texture.hasAlpha = parsedTexture.hasAlpha;
  59908. texture.level = parsedTexture.level;
  59909. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59910. texture.isBlocking = parsedTexture.isBlocking;
  59911. }
  59912. return texture;
  59913. };
  59914. HDRCubeTexture.prototype.serialize = function () {
  59915. if (!this.name) {
  59916. return null;
  59917. }
  59918. var serializationObject = {};
  59919. serializationObject.name = this.name;
  59920. serializationObject.hasAlpha = this.hasAlpha;
  59921. serializationObject.isCube = true;
  59922. serializationObject.level = this.level;
  59923. serializationObject.size = this._size;
  59924. serializationObject.coordinatesMode = this.coordinatesMode;
  59925. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59926. serializationObject.generateHarmonics = this._generateHarmonics;
  59927. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59928. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59929. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59930. serializationObject.noMipmap = this._noMipmap;
  59931. serializationObject.isBlocking = this._isBlocking;
  59932. return serializationObject;
  59933. };
  59934. /**
  59935. * Saves as a file the data contained in the texture in a binary format.
  59936. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59937. * as the spherical used in the lighting.
  59938. * @param url The HDR file url.
  59939. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59940. * @param onError Method called if any error happens during download.
  59941. * @return The packed binary data.
  59942. */
  59943. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59944. if (onError === void 0) { onError = null; }
  59945. var callback = function (buffer) {
  59946. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59947. // Returns a URL you can use as a href.
  59948. var objUrl = window.URL.createObjectURL(data);
  59949. // Simulates a link to it and click to dowload.
  59950. var a = document.createElement("a");
  59951. document.body.appendChild(a);
  59952. a.style.display = "none";
  59953. a.href = objUrl;
  59954. a.download = "envmap.babylon.hdr";
  59955. a.click();
  59956. };
  59957. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59958. };
  59959. /**
  59960. * Serializes the data contained in the texture in a binary format.
  59961. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59962. * as the spherical used in the lighting.
  59963. * @param url The HDR file url.
  59964. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59965. * @param onError Method called if any error happens during download.
  59966. * @return The packed binary data.
  59967. */
  59968. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59969. if (onError === void 0) { onError = null; }
  59970. // Needs the url tho create the texture.
  59971. if (!url) {
  59972. return null;
  59973. }
  59974. // Check Power of two size.
  59975. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59976. return null;
  59977. }
  59978. // Coming Back in 3.1.
  59979. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  59980. return null;
  59981. };
  59982. HDRCubeTexture._facesMapping = [
  59983. "right",
  59984. "left",
  59985. "up",
  59986. "down",
  59987. "front",
  59988. "back"
  59989. ];
  59990. return HDRCubeTexture;
  59991. }(BABYLON.BaseTexture));
  59992. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59993. })(BABYLON || (BABYLON = {}));
  59994. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  59995. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  59996. // Huge respect for a such great lib.
  59997. // Earcut license:
  59998. // Copyright (c) 2016, Mapbox
  59999. //
  60000. // Permission to use, copy, modify, and/or distribute this software for any purpose
  60001. // with or without fee is hereby granted, provided that the above copyright notice
  60002. // and this permission notice appear in all copies.
  60003. //
  60004. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  60005. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  60006. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  60007. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  60008. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  60009. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  60010. // THIS SOFTWARE.
  60011. var Earcut;
  60012. (function (Earcut) {
  60013. /**
  60014. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  60015. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  60016. * @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).
  60017. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  60018. */
  60019. function earcut(data, holeIndices, dim) {
  60020. dim = dim || 2;
  60021. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  60022. if (!outerNode)
  60023. return triangles;
  60024. var minX, minY, maxX, maxY, x, y, size;
  60025. if (hasHoles)
  60026. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  60027. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  60028. if (data.length > 80 * dim) {
  60029. minX = maxX = data[0];
  60030. minY = maxY = data[1];
  60031. for (var i = dim; i < outerLen; i += dim) {
  60032. x = data[i];
  60033. y = data[i + 1];
  60034. if (x < minX)
  60035. minX = x;
  60036. if (y < minY)
  60037. minY = y;
  60038. if (x > maxX)
  60039. maxX = x;
  60040. if (y > maxY)
  60041. maxY = y;
  60042. }
  60043. // minX, minY and size are later used to transform coords into integers for z-order calculation
  60044. size = Math.max(maxX - minX, maxY - minY);
  60045. }
  60046. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  60047. return triangles;
  60048. }
  60049. Earcut.earcut = earcut;
  60050. // create a circular doubly linked list from polygon points in the specified winding order
  60051. function linkedList(data, start, end, dim, clockwise) {
  60052. var i, last;
  60053. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  60054. for (i = start; i < end; i += dim)
  60055. last = insertNode(i, data[i], data[i + 1], last);
  60056. }
  60057. else {
  60058. for (i = end - dim; i >= start; i -= dim)
  60059. last = insertNode(i, data[i], data[i + 1], last);
  60060. }
  60061. if (last && equals(last, last.next)) {
  60062. removeNode(last);
  60063. last = last.next;
  60064. }
  60065. return last;
  60066. }
  60067. // eliminate colinear or duplicate points
  60068. function filterPoints(start, end) {
  60069. if (!start)
  60070. return start;
  60071. if (!end)
  60072. end = start;
  60073. var p = start, again;
  60074. do {
  60075. again = false;
  60076. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  60077. removeNode(p);
  60078. p = end = p.prev;
  60079. if (p === p.next)
  60080. return null;
  60081. again = true;
  60082. }
  60083. else {
  60084. p = p.next;
  60085. }
  60086. } while (again || p !== end);
  60087. return end;
  60088. }
  60089. // main ear slicing loop which triangulates a polygon (given as a linked list)
  60090. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  60091. if (!ear)
  60092. return;
  60093. // interlink polygon nodes in z-order
  60094. if (!pass && size)
  60095. indexCurve(ear, minX, minY, size);
  60096. var stop = ear, prev, next;
  60097. // iterate through ears, slicing them one by one
  60098. while (ear.prev !== ear.next) {
  60099. prev = ear.prev;
  60100. next = ear.next;
  60101. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  60102. // cut off the triangle
  60103. triangles.push(prev.i / dim);
  60104. triangles.push(ear.i / dim);
  60105. triangles.push(next.i / dim);
  60106. removeNode(ear);
  60107. // skipping the next vertice leads to less sliver triangles
  60108. ear = next.next;
  60109. stop = next.next;
  60110. continue;
  60111. }
  60112. ear = next;
  60113. // if we looped through the whole remaining polygon and can't find any more ears
  60114. if (ear === stop) {
  60115. // try filtering points and slicing again
  60116. if (!pass) {
  60117. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  60118. // if this didn't work, try curing all small self-intersections locally
  60119. }
  60120. else if (pass === 1) {
  60121. ear = cureLocalIntersections(ear, triangles, dim);
  60122. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  60123. // as a last resort, try splitting the remaining polygon into two
  60124. }
  60125. else if (pass === 2) {
  60126. splitEarcut(ear, triangles, dim, minX, minY, size);
  60127. }
  60128. break;
  60129. }
  60130. }
  60131. }
  60132. // check whether a polygon node forms a valid ear with adjacent nodes
  60133. function isEar(ear) {
  60134. var a = ear.prev, b = ear, c = ear.next;
  60135. if (area(a, b, c) >= 0)
  60136. return false; // reflex, can't be an ear
  60137. // now make sure we don't have other points inside the potential ear
  60138. var p = ear.next.next;
  60139. while (p !== ear.prev) {
  60140. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  60141. area(p.prev, p, p.next) >= 0)
  60142. return false;
  60143. p = p.next;
  60144. }
  60145. return true;
  60146. }
  60147. function isEarHashed(ear, minX, minY, size) {
  60148. var a = ear.prev, b = ear, c = ear.next;
  60149. if (area(a, b, c) >= 0)
  60150. return false; // reflex, can't be an ear
  60151. // triangle bbox; min & max are calculated like this for speed
  60152. 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);
  60153. // z-order range for the current triangle bbox;
  60154. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  60155. // first look for points inside the triangle in increasing z-order
  60156. var p = ear.nextZ;
  60157. while (p && p.z <= maxZ) {
  60158. if (p !== ear.prev &&
  60159. p !== ear.next &&
  60160. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  60161. area(p.prev, p, p.next) >= 0)
  60162. return false;
  60163. p = p.nextZ;
  60164. }
  60165. // then look for points in decreasing z-order
  60166. p = ear.prevZ;
  60167. while (p && p.z >= minZ) {
  60168. if (p !== ear.prev &&
  60169. p !== ear.next &&
  60170. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  60171. area(p.prev, p, p.next) >= 0)
  60172. return false;
  60173. p = p.prevZ;
  60174. }
  60175. return true;
  60176. }
  60177. // go through all polygon nodes and cure small local self-intersections
  60178. function cureLocalIntersections(start, triangles, dim) {
  60179. var p = start;
  60180. do {
  60181. var a = p.prev, b = p.next.next;
  60182. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  60183. triangles.push(a.i / dim);
  60184. triangles.push(p.i / dim);
  60185. triangles.push(b.i / dim);
  60186. // remove two nodes involved
  60187. removeNode(p);
  60188. removeNode(p.next);
  60189. p = start = b;
  60190. }
  60191. p = p.next;
  60192. } while (p !== start);
  60193. return p;
  60194. }
  60195. // try splitting polygon into two and triangulate them independently
  60196. function splitEarcut(start, triangles, dim, minX, minY, size) {
  60197. // look for a valid diagonal that divides the polygon into two
  60198. var a = start;
  60199. do {
  60200. var b = a.next.next;
  60201. while (b !== a.prev) {
  60202. if (a.i !== b.i && isValidDiagonal(a, b)) {
  60203. // split the polygon in two by the diagonal
  60204. var c = splitPolygon(a, b);
  60205. // filter colinear points around the cuts
  60206. a = filterPoints(a, a.next);
  60207. c = filterPoints(c, c.next);
  60208. // run earcut on each half
  60209. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  60210. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  60211. return;
  60212. }
  60213. b = b.next;
  60214. }
  60215. a = a.next;
  60216. } while (a !== start);
  60217. }
  60218. // link every hole into the outer loop, producing a single-ring polygon without holes
  60219. function eliminateHoles(data, holeIndices, outerNode, dim) {
  60220. var queue = [], i, len, start, end, list;
  60221. for (i = 0, len = holeIndices.length; i < len; i++) {
  60222. start = holeIndices[i] * dim;
  60223. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  60224. list = linkedList(data, start, end, dim, false);
  60225. if (list === list.next)
  60226. list.steiner = true;
  60227. queue.push(getLeftmost(list));
  60228. }
  60229. queue.sort(compareX);
  60230. // process holes from left to right
  60231. for (i = 0; i < queue.length; i++) {
  60232. eliminateHole(queue[i], outerNode);
  60233. outerNode = filterPoints(outerNode, outerNode.next);
  60234. }
  60235. return outerNode;
  60236. }
  60237. function compareX(a, b) {
  60238. return a.x - b.x;
  60239. }
  60240. // find a bridge between vertices that connects hole with an outer ring and and link it
  60241. function eliminateHole(hole, outerNode) {
  60242. outerNode = findHoleBridge(hole, outerNode);
  60243. if (outerNode) {
  60244. var b = splitPolygon(outerNode, hole);
  60245. filterPoints(b, b.next);
  60246. }
  60247. }
  60248. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  60249. function findHoleBridge(hole, outerNode) {
  60250. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  60251. // find a segment intersected by a ray from the hole's leftmost point to the left;
  60252. // segment's endpoint with lesser x will be potential connection point
  60253. do {
  60254. if (hy <= p.y && hy >= p.next.y) {
  60255. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  60256. if (x <= hx && x > qx) {
  60257. qx = x;
  60258. if (x === hx) {
  60259. if (hy === p.y)
  60260. return p;
  60261. if (hy === p.next.y)
  60262. return p.next;
  60263. }
  60264. m = p.x < p.next.x ? p : p.next;
  60265. }
  60266. }
  60267. p = p.next;
  60268. } while (p !== outerNode);
  60269. if (!m)
  60270. return null;
  60271. if (hx === qx)
  60272. return m.prev; // hole touches outer segment; pick lower endpoint
  60273. // look for points inside the triangle of hole point, segment intersection and endpoint;
  60274. // if there are no points found, we have a valid connection;
  60275. // otherwise choose the point of the minimum angle with the ray as connection point
  60276. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  60277. p = m.next;
  60278. while (p !== stop) {
  60279. if (hx >= p.x &&
  60280. p.x >= mx &&
  60281. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  60282. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  60283. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  60284. m = p;
  60285. tanMin = tan;
  60286. }
  60287. }
  60288. p = p.next;
  60289. }
  60290. return m;
  60291. }
  60292. // interlink polygon nodes in z-order
  60293. function indexCurve(start, minX, minY, size) {
  60294. var p = start;
  60295. do {
  60296. if (p.z === null)
  60297. p.z = zOrder(p.x, p.y, minX, minY, size);
  60298. p.prevZ = p.prev;
  60299. p.nextZ = p.next;
  60300. p = p.next;
  60301. } while (p !== start);
  60302. p.prevZ.nextZ = null;
  60303. p.prevZ = null;
  60304. sortLinked(p);
  60305. }
  60306. // Simon Tatham's linked list merge sort algorithm
  60307. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  60308. function sortLinked(list) {
  60309. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  60310. do {
  60311. p = list;
  60312. list = null;
  60313. tail = null;
  60314. numMerges = 0;
  60315. while (p) {
  60316. numMerges++;
  60317. q = p;
  60318. pSize = 0;
  60319. for (i = 0; i < inSize; i++) {
  60320. pSize++;
  60321. q = q.nextZ;
  60322. if (!q)
  60323. break;
  60324. }
  60325. qSize = inSize;
  60326. while (pSize > 0 || (qSize > 0 && q)) {
  60327. if (pSize === 0) {
  60328. e = q;
  60329. q = q.nextZ;
  60330. qSize--;
  60331. }
  60332. else if (qSize === 0 || !q) {
  60333. e = p;
  60334. p = p.nextZ;
  60335. pSize--;
  60336. }
  60337. else if (p.z <= q.z) {
  60338. e = p;
  60339. p = p.nextZ;
  60340. pSize--;
  60341. }
  60342. else {
  60343. e = q;
  60344. q = q.nextZ;
  60345. qSize--;
  60346. }
  60347. if (tail)
  60348. tail.nextZ = e;
  60349. else
  60350. list = e;
  60351. e.prevZ = tail;
  60352. tail = e;
  60353. }
  60354. p = q;
  60355. }
  60356. tail.nextZ = null;
  60357. inSize *= 2;
  60358. } while (numMerges > 1);
  60359. return list;
  60360. }
  60361. // z-order of a point given coords and size of the data bounding box
  60362. function zOrder(x, y, minX, minY, size) {
  60363. // coords are transformed into non-negative 15-bit integer range
  60364. x = 32767 * (x - minX) / size;
  60365. y = 32767 * (y - minY) / size;
  60366. x = (x | (x << 8)) & 0x00FF00FF;
  60367. x = (x | (x << 4)) & 0x0F0F0F0F;
  60368. x = (x | (x << 2)) & 0x33333333;
  60369. x = (x | (x << 1)) & 0x55555555;
  60370. y = (y | (y << 8)) & 0x00FF00FF;
  60371. y = (y | (y << 4)) & 0x0F0F0F0F;
  60372. y = (y | (y << 2)) & 0x33333333;
  60373. y = (y | (y << 1)) & 0x55555555;
  60374. return x | (y << 1);
  60375. }
  60376. // find the leftmost node of a polygon ring
  60377. function getLeftmost(start) {
  60378. var p = start, leftmost = start;
  60379. do {
  60380. if (p.x < leftmost.x)
  60381. leftmost = p;
  60382. p = p.next;
  60383. } while (p !== start);
  60384. return leftmost;
  60385. }
  60386. // check if a point lies within a convex triangle
  60387. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  60388. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  60389. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  60390. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  60391. }
  60392. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  60393. function isValidDiagonal(a, b) {
  60394. return a.next.i !== b.i &&
  60395. a.prev.i !== b.i &&
  60396. !intersectsPolygon(a, b) &&
  60397. locallyInside(a, b) &&
  60398. locallyInside(b, a) &&
  60399. middleInside(a, b);
  60400. }
  60401. // signed area of a triangle
  60402. function area(p, q, r) {
  60403. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  60404. }
  60405. // check if two points are equal
  60406. function equals(p1, p2) {
  60407. return p1.x === p2.x && p1.y === p2.y;
  60408. }
  60409. // check if two segments intersect
  60410. function intersects(p1, q1, p2, q2) {
  60411. if ((equals(p1, q1) && equals(p2, q2)) ||
  60412. (equals(p1, q2) && equals(p2, q1)))
  60413. return true;
  60414. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  60415. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  60416. }
  60417. // check if a polygon diagonal intersects any polygon segments
  60418. function intersectsPolygon(a, b) {
  60419. var p = a;
  60420. do {
  60421. if (p.i !== a.i &&
  60422. p.next.i !== a.i &&
  60423. p.i !== b.i &&
  60424. p.next.i !== b.i &&
  60425. intersects(p, p.next, a, b))
  60426. return true;
  60427. p = p.next;
  60428. } while (p !== a);
  60429. return false;
  60430. }
  60431. // check if a polygon diagonal is locally inside the polygon
  60432. function locallyInside(a, b) {
  60433. return area(a.prev, a, a.next) < 0
  60434. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  60435. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  60436. }
  60437. // check if the middle point of a polygon diagonal is inside the polygon
  60438. function middleInside(a, b) {
  60439. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  60440. do {
  60441. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  60442. inside = !inside;
  60443. p = p.next;
  60444. } while (p !== a);
  60445. return inside;
  60446. }
  60447. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  60448. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  60449. function splitPolygon(a, b) {
  60450. 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;
  60451. a.next = b;
  60452. b.prev = a;
  60453. a2.next = an;
  60454. an.prev = a2;
  60455. b2.next = a2;
  60456. a2.prev = b2;
  60457. bp.next = b2;
  60458. b2.prev = bp;
  60459. return b2;
  60460. }
  60461. // create a node and optionally link it with previous one (in a circular doubly linked list)
  60462. function insertNode(i, x, y, last) {
  60463. var p = new Node(i, x, y);
  60464. if (!last) {
  60465. p.prev = p;
  60466. p.next = p;
  60467. }
  60468. else {
  60469. p.next = last.next;
  60470. p.prev = last;
  60471. last.next.prev = p;
  60472. last.next = p;
  60473. }
  60474. return p;
  60475. }
  60476. function removeNode(p) {
  60477. p.next.prev = p.prev;
  60478. p.prev.next = p.next;
  60479. if (p.prevZ)
  60480. p.prevZ.nextZ = p.nextZ;
  60481. if (p.nextZ)
  60482. p.nextZ.prevZ = p.prevZ;
  60483. }
  60484. function Node(i, x, y) {
  60485. // vertice index in coordinates array
  60486. this.i = i;
  60487. // vertex coordinates
  60488. this.x = x;
  60489. this.y = y;
  60490. // previous and next vertice nodes in a polygon ring
  60491. this.prev = null;
  60492. this.next = null;
  60493. // z-order curve value
  60494. this.z = null;
  60495. // previous and next nodes in z-order
  60496. this.prevZ = null;
  60497. this.nextZ = null;
  60498. // indicates whether this is a steiner point
  60499. this.steiner = false;
  60500. }
  60501. /**
  60502. * return a percentage difference between the polygon area and its triangulation area;
  60503. * used to verify correctness of triangulation
  60504. */
  60505. function deviation(data, holeIndices, dim, triangles) {
  60506. var hasHoles = holeIndices && holeIndices.length;
  60507. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  60508. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  60509. if (hasHoles) {
  60510. for (var i = 0, len = holeIndices.length; i < len; i++) {
  60511. var start = holeIndices[i] * dim;
  60512. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  60513. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  60514. }
  60515. }
  60516. var trianglesArea = 0;
  60517. for (i = 0; i < triangles.length; i += 3) {
  60518. var a = triangles[i] * dim;
  60519. var b = triangles[i + 1] * dim;
  60520. var c = triangles[i + 2] * dim;
  60521. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  60522. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  60523. }
  60524. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  60525. }
  60526. Earcut.deviation = deviation;
  60527. ;
  60528. function signedArea(data, start, end, dim) {
  60529. var sum = 0;
  60530. for (var i = start, j = end - dim; i < end; i += dim) {
  60531. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  60532. j = i;
  60533. }
  60534. return sum;
  60535. }
  60536. /**
  60537. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  60538. */
  60539. function flatten(data) {
  60540. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  60541. for (var i = 0; i < data.length; i++) {
  60542. for (var j = 0; j < data[i].length; j++) {
  60543. for (var d = 0; d < dim; d++)
  60544. result.vertices.push(data[i][j][d]);
  60545. }
  60546. if (i > 0) {
  60547. holeIndex += data[i - 1].length;
  60548. result.holes.push(holeIndex);
  60549. }
  60550. }
  60551. return result;
  60552. }
  60553. Earcut.flatten = flatten;
  60554. ;
  60555. })(Earcut || (Earcut = {}));
  60556. //# sourceMappingURL=babylon.earcut.js.map
  60557. /// <reference path="..\Math\babylon.math.ts" />
  60558. var BABYLON;
  60559. (function (BABYLON) {
  60560. var IndexedVector2 = (function (_super) {
  60561. __extends(IndexedVector2, _super);
  60562. function IndexedVector2(original, index) {
  60563. var _this = _super.call(this, original.x, original.y) || this;
  60564. _this.index = index;
  60565. return _this;
  60566. }
  60567. return IndexedVector2;
  60568. }(BABYLON.Vector2));
  60569. var PolygonPoints = (function () {
  60570. function PolygonPoints() {
  60571. this.elements = new Array();
  60572. }
  60573. PolygonPoints.prototype.add = function (originalPoints) {
  60574. var _this = this;
  60575. var result = new Array();
  60576. originalPoints.forEach(function (point) {
  60577. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  60578. var newPoint = new IndexedVector2(point, _this.elements.length);
  60579. result.push(newPoint);
  60580. _this.elements.push(newPoint);
  60581. }
  60582. });
  60583. return result;
  60584. };
  60585. PolygonPoints.prototype.computeBounds = function () {
  60586. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  60587. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  60588. this.elements.forEach(function (point) {
  60589. // x
  60590. if (point.x < lmin.x) {
  60591. lmin.x = point.x;
  60592. }
  60593. else if (point.x > lmax.x) {
  60594. lmax.x = point.x;
  60595. }
  60596. // y
  60597. if (point.y < lmin.y) {
  60598. lmin.y = point.y;
  60599. }
  60600. else if (point.y > lmax.y) {
  60601. lmax.y = point.y;
  60602. }
  60603. });
  60604. return {
  60605. min: lmin,
  60606. max: lmax,
  60607. width: lmax.x - lmin.x,
  60608. height: lmax.y - lmin.y
  60609. };
  60610. };
  60611. return PolygonPoints;
  60612. }());
  60613. var Polygon = (function () {
  60614. function Polygon() {
  60615. }
  60616. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  60617. return [
  60618. new BABYLON.Vector2(xmin, ymin),
  60619. new BABYLON.Vector2(xmax, ymin),
  60620. new BABYLON.Vector2(xmax, ymax),
  60621. new BABYLON.Vector2(xmin, ymax)
  60622. ];
  60623. };
  60624. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  60625. if (cx === void 0) { cx = 0; }
  60626. if (cy === void 0) { cy = 0; }
  60627. if (numberOfSides === void 0) { numberOfSides = 32; }
  60628. var result = new Array();
  60629. var angle = 0;
  60630. var increment = (Math.PI * 2) / numberOfSides;
  60631. for (var i = 0; i < numberOfSides; i++) {
  60632. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  60633. angle -= increment;
  60634. }
  60635. return result;
  60636. };
  60637. Polygon.Parse = function (input) {
  60638. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  60639. var i, result = [];
  60640. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  60641. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  60642. }
  60643. return result;
  60644. };
  60645. Polygon.StartingAt = function (x, y) {
  60646. return BABYLON.Path2.StartingAt(x, y);
  60647. };
  60648. return Polygon;
  60649. }());
  60650. BABYLON.Polygon = Polygon;
  60651. var PolygonMeshBuilder = (function () {
  60652. function PolygonMeshBuilder(name, contours, scene) {
  60653. this._points = new PolygonPoints();
  60654. this._outlinepoints = new PolygonPoints();
  60655. this._holes = [];
  60656. this._epoints = new Array();
  60657. this._eholes = new Array();
  60658. this._name = name;
  60659. this._scene = scene;
  60660. var points;
  60661. if (contours instanceof BABYLON.Path2) {
  60662. points = contours.getPoints();
  60663. }
  60664. else {
  60665. points = contours;
  60666. }
  60667. this._addToepoint(points);
  60668. this._points.add(points);
  60669. this._outlinepoints.add(points);
  60670. }
  60671. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  60672. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  60673. var p = points_1[_i];
  60674. this._epoints.push(p.x, p.y);
  60675. }
  60676. };
  60677. PolygonMeshBuilder.prototype.addHole = function (hole) {
  60678. this._points.add(hole);
  60679. var holepoints = new PolygonPoints();
  60680. holepoints.add(hole);
  60681. this._holes.push(holepoints);
  60682. this._eholes.push(this._epoints.length / 2);
  60683. this._addToepoint(hole);
  60684. return this;
  60685. };
  60686. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  60687. var _this = this;
  60688. if (updatable === void 0) { updatable = false; }
  60689. var result = new BABYLON.Mesh(this._name, this._scene);
  60690. var normals = [];
  60691. var positions = [];
  60692. var uvs = [];
  60693. var bounds = this._points.computeBounds();
  60694. this._points.elements.forEach(function (p) {
  60695. normals.push(0, 1.0, 0);
  60696. positions.push(p.x, 0, p.y);
  60697. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  60698. });
  60699. var indices = [];
  60700. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  60701. for (var i = 0; i < res.length; i++) {
  60702. indices.push(res[i]);
  60703. }
  60704. if (depth > 0) {
  60705. var positionscount = (positions.length / 3); //get the current pointcount
  60706. this._points.elements.forEach(function (p) {
  60707. normals.push(0, -1.0, 0);
  60708. positions.push(p.x, -depth, p.y);
  60709. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  60710. });
  60711. var totalCount = indices.length;
  60712. for (var i = 0; i < totalCount; i += 3) {
  60713. var i0 = indices[i + 0];
  60714. var i1 = indices[i + 1];
  60715. var i2 = indices[i + 2];
  60716. indices.push(i2 + positionscount);
  60717. indices.push(i1 + positionscount);
  60718. indices.push(i0 + positionscount);
  60719. }
  60720. //Add the sides
  60721. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  60722. this._holes.forEach(function (hole) {
  60723. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  60724. });
  60725. }
  60726. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  60727. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  60728. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  60729. result.setIndices(indices);
  60730. return result;
  60731. };
  60732. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  60733. var StartIndex = positions.length / 3;
  60734. var ulength = 0;
  60735. for (var i = 0; i < points.elements.length; i++) {
  60736. var p = points.elements[i];
  60737. var p1;
  60738. if ((i + 1) > points.elements.length - 1) {
  60739. p1 = points.elements[0];
  60740. }
  60741. else {
  60742. p1 = points.elements[i + 1];
  60743. }
  60744. positions.push(p.x, 0, p.y);
  60745. positions.push(p.x, -depth, p.y);
  60746. positions.push(p1.x, 0, p1.y);
  60747. positions.push(p1.x, -depth, p1.y);
  60748. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  60749. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  60750. var v3 = v2.subtract(v1);
  60751. var v4 = new BABYLON.Vector3(0, 1, 0);
  60752. var vn = BABYLON.Vector3.Cross(v3, v4);
  60753. vn = vn.normalize();
  60754. uvs.push(ulength / bounds.width, 0);
  60755. uvs.push(ulength / bounds.width, 1);
  60756. ulength += v3.length();
  60757. uvs.push((ulength / bounds.width), 0);
  60758. uvs.push((ulength / bounds.width), 1);
  60759. if (!flip) {
  60760. normals.push(-vn.x, -vn.y, -vn.z);
  60761. normals.push(-vn.x, -vn.y, -vn.z);
  60762. normals.push(-vn.x, -vn.y, -vn.z);
  60763. normals.push(-vn.x, -vn.y, -vn.z);
  60764. indices.push(StartIndex);
  60765. indices.push(StartIndex + 1);
  60766. indices.push(StartIndex + 2);
  60767. indices.push(StartIndex + 1);
  60768. indices.push(StartIndex + 3);
  60769. indices.push(StartIndex + 2);
  60770. }
  60771. else {
  60772. normals.push(vn.x, vn.y, vn.z);
  60773. normals.push(vn.x, vn.y, vn.z);
  60774. normals.push(vn.x, vn.y, vn.z);
  60775. normals.push(vn.x, vn.y, vn.z);
  60776. indices.push(StartIndex);
  60777. indices.push(StartIndex + 2);
  60778. indices.push(StartIndex + 1);
  60779. indices.push(StartIndex + 1);
  60780. indices.push(StartIndex + 2);
  60781. indices.push(StartIndex + 3);
  60782. }
  60783. StartIndex += 4;
  60784. }
  60785. ;
  60786. };
  60787. return PolygonMeshBuilder;
  60788. }());
  60789. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  60790. })(BABYLON || (BABYLON = {}));
  60791. //# sourceMappingURL=babylon.polygonMesh.js.map
  60792. var BABYLON;
  60793. (function (BABYLON) {
  60794. // Unique ID when we import meshes from Babylon to CSG
  60795. var currentCSGMeshId = 0;
  60796. // # class Vertex
  60797. // Represents a vertex of a polygon. Use your own vertex class instead of this
  60798. // one to provide additional features like texture coordinates and vertex
  60799. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  60800. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  60801. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  60802. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  60803. // is not used anywhere else.
  60804. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  60805. var Vertex = (function () {
  60806. function Vertex(pos, normal, uv) {
  60807. this.pos = pos;
  60808. this.normal = normal;
  60809. this.uv = uv;
  60810. }
  60811. Vertex.prototype.clone = function () {
  60812. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  60813. };
  60814. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  60815. // orientation of a polygon is flipped.
  60816. Vertex.prototype.flip = function () {
  60817. this.normal = this.normal.scale(-1);
  60818. };
  60819. // Create a new vertex between this vertex and `other` by linearly
  60820. // interpolating all properties using a parameter of `t`. Subclasses should
  60821. // override this to interpolate additional properties.
  60822. Vertex.prototype.interpolate = function (other, t) {
  60823. 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));
  60824. };
  60825. return Vertex;
  60826. }());
  60827. // # class Plane
  60828. // Represents a plane in 3D space.
  60829. var Plane = (function () {
  60830. function Plane(normal, w) {
  60831. this.normal = normal;
  60832. this.w = w;
  60833. }
  60834. Plane.FromPoints = function (a, b, c) {
  60835. var v0 = c.subtract(a);
  60836. var v1 = b.subtract(a);
  60837. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  60838. return null;
  60839. }
  60840. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  60841. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  60842. };
  60843. Plane.prototype.clone = function () {
  60844. return new Plane(this.normal.clone(), this.w);
  60845. };
  60846. Plane.prototype.flip = function () {
  60847. this.normal.scaleInPlace(-1);
  60848. this.w = -this.w;
  60849. };
  60850. // Split `polygon` by this plane if needed, then put the polygon or polygon
  60851. // fragments in the appropriate lists. Coplanar polygons go into either
  60852. // `coplanarFront` or `coplanarBack` depending on their orientation with
  60853. // respect to this plane. Polygons in front or in back of this plane go into
  60854. // either `front` or `back`.
  60855. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  60856. var COPLANAR = 0;
  60857. var FRONT = 1;
  60858. var BACK = 2;
  60859. var SPANNING = 3;
  60860. // Classify each point as well as the entire polygon into one of the above
  60861. // four classes.
  60862. var polygonType = 0;
  60863. var types = [];
  60864. var i;
  60865. var t;
  60866. for (i = 0; i < polygon.vertices.length; i++) {
  60867. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  60868. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  60869. polygonType |= type;
  60870. types.push(type);
  60871. }
  60872. // Put the polygon in the correct list, splitting it when necessary.
  60873. switch (polygonType) {
  60874. case COPLANAR:
  60875. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  60876. break;
  60877. case FRONT:
  60878. front.push(polygon);
  60879. break;
  60880. case BACK:
  60881. back.push(polygon);
  60882. break;
  60883. case SPANNING:
  60884. var f = [], b = [];
  60885. for (i = 0; i < polygon.vertices.length; i++) {
  60886. var j = (i + 1) % polygon.vertices.length;
  60887. var ti = types[i], tj = types[j];
  60888. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  60889. if (ti !== BACK)
  60890. f.push(vi);
  60891. if (ti !== FRONT)
  60892. b.push(ti !== BACK ? vi.clone() : vi);
  60893. if ((ti | tj) === SPANNING) {
  60894. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  60895. var v = vi.interpolate(vj, t);
  60896. f.push(v);
  60897. b.push(v.clone());
  60898. }
  60899. }
  60900. var poly;
  60901. if (f.length >= 3) {
  60902. poly = new Polygon(f, polygon.shared);
  60903. if (poly.plane)
  60904. front.push(poly);
  60905. }
  60906. if (b.length >= 3) {
  60907. poly = new Polygon(b, polygon.shared);
  60908. if (poly.plane)
  60909. back.push(poly);
  60910. }
  60911. break;
  60912. }
  60913. };
  60914. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  60915. // point is on the plane.
  60916. Plane.EPSILON = 1e-5;
  60917. return Plane;
  60918. }());
  60919. // # class Polygon
  60920. // Represents a convex polygon. The vertices used to initialize a polygon must
  60921. // be coplanar and form a convex loop.
  60922. //
  60923. // Each convex polygon has a `shared` property, which is shared between all
  60924. // polygons that are clones of each other or were split from the same polygon.
  60925. // This can be used to define per-polygon properties (such as surface color).
  60926. var Polygon = (function () {
  60927. function Polygon(vertices, shared) {
  60928. this.vertices = vertices;
  60929. this.shared = shared;
  60930. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  60931. }
  60932. Polygon.prototype.clone = function () {
  60933. var vertices = this.vertices.map(function (v) { return v.clone(); });
  60934. return new Polygon(vertices, this.shared);
  60935. };
  60936. Polygon.prototype.flip = function () {
  60937. this.vertices.reverse().map(function (v) { v.flip(); });
  60938. this.plane.flip();
  60939. };
  60940. return Polygon;
  60941. }());
  60942. // # class Node
  60943. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  60944. // by picking a polygon to split along. That polygon (and all other coplanar
  60945. // polygons) are added directly to that node and the other polygons are added to
  60946. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  60947. // no distinction between internal and leaf nodes.
  60948. var Node = (function () {
  60949. function Node(polygons) {
  60950. this.plane = null;
  60951. this.front = null;
  60952. this.back = null;
  60953. this.polygons = [];
  60954. if (polygons) {
  60955. this.build(polygons);
  60956. }
  60957. }
  60958. Node.prototype.clone = function () {
  60959. var node = new Node();
  60960. node.plane = this.plane && this.plane.clone();
  60961. node.front = this.front && this.front.clone();
  60962. node.back = this.back && this.back.clone();
  60963. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  60964. return node;
  60965. };
  60966. // Convert solid space to empty space and empty space to solid space.
  60967. Node.prototype.invert = function () {
  60968. for (var i = 0; i < this.polygons.length; i++) {
  60969. this.polygons[i].flip();
  60970. }
  60971. if (this.plane) {
  60972. this.plane.flip();
  60973. }
  60974. if (this.front) {
  60975. this.front.invert();
  60976. }
  60977. if (this.back) {
  60978. this.back.invert();
  60979. }
  60980. var temp = this.front;
  60981. this.front = this.back;
  60982. this.back = temp;
  60983. };
  60984. // Recursively remove all polygons in `polygons` that are inside this BSP
  60985. // tree.
  60986. Node.prototype.clipPolygons = function (polygons) {
  60987. if (!this.plane)
  60988. return polygons.slice();
  60989. var front = [], back = [];
  60990. for (var i = 0; i < polygons.length; i++) {
  60991. this.plane.splitPolygon(polygons[i], front, back, front, back);
  60992. }
  60993. if (this.front) {
  60994. front = this.front.clipPolygons(front);
  60995. }
  60996. if (this.back) {
  60997. back = this.back.clipPolygons(back);
  60998. }
  60999. else {
  61000. back = [];
  61001. }
  61002. return front.concat(back);
  61003. };
  61004. // Remove all polygons in this BSP tree that are inside the other BSP tree
  61005. // `bsp`.
  61006. Node.prototype.clipTo = function (bsp) {
  61007. this.polygons = bsp.clipPolygons(this.polygons);
  61008. if (this.front)
  61009. this.front.clipTo(bsp);
  61010. if (this.back)
  61011. this.back.clipTo(bsp);
  61012. };
  61013. // Return a list of all polygons in this BSP tree.
  61014. Node.prototype.allPolygons = function () {
  61015. var polygons = this.polygons.slice();
  61016. if (this.front)
  61017. polygons = polygons.concat(this.front.allPolygons());
  61018. if (this.back)
  61019. polygons = polygons.concat(this.back.allPolygons());
  61020. return polygons;
  61021. };
  61022. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  61023. // new polygons are filtered down to the bottom of the tree and become new
  61024. // nodes there. Each set of polygons is partitioned using the first polygon
  61025. // (no heuristic is used to pick a good split).
  61026. Node.prototype.build = function (polygons) {
  61027. if (!polygons.length)
  61028. return;
  61029. if (!this.plane)
  61030. this.plane = polygons[0].plane.clone();
  61031. var front = [], back = [];
  61032. for (var i = 0; i < polygons.length; i++) {
  61033. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  61034. }
  61035. if (front.length) {
  61036. if (!this.front)
  61037. this.front = new Node();
  61038. this.front.build(front);
  61039. }
  61040. if (back.length) {
  61041. if (!this.back)
  61042. this.back = new Node();
  61043. this.back.build(back);
  61044. }
  61045. };
  61046. return Node;
  61047. }());
  61048. var CSG = (function () {
  61049. function CSG() {
  61050. this.polygons = new Array();
  61051. }
  61052. // Convert BABYLON.Mesh to BABYLON.CSG
  61053. CSG.FromMesh = function (mesh) {
  61054. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  61055. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  61056. if (mesh instanceof BABYLON.Mesh) {
  61057. mesh.computeWorldMatrix(true);
  61058. matrix = mesh.getWorldMatrix();
  61059. meshPosition = mesh.position.clone();
  61060. meshRotation = mesh.rotation.clone();
  61061. if (mesh.rotationQuaternion) {
  61062. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  61063. }
  61064. meshScaling = mesh.scaling.clone();
  61065. }
  61066. else {
  61067. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  61068. }
  61069. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61070. var subMeshes = mesh.subMeshes;
  61071. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  61072. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  61073. vertices = [];
  61074. for (var j = 0; j < 3; j++) {
  61075. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  61076. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  61077. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  61078. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  61079. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  61080. vertex = new Vertex(position, normal, uv);
  61081. vertices.push(vertex);
  61082. }
  61083. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  61084. // To handle the case of degenerated triangle
  61085. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  61086. if (polygon.plane)
  61087. polygons.push(polygon);
  61088. }
  61089. }
  61090. var csg = CSG.FromPolygons(polygons);
  61091. csg.matrix = matrix;
  61092. csg.position = meshPosition;
  61093. csg.rotation = meshRotation;
  61094. csg.scaling = meshScaling;
  61095. csg.rotationQuaternion = meshRotationQuaternion;
  61096. currentCSGMeshId++;
  61097. return csg;
  61098. };
  61099. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  61100. CSG.FromPolygons = function (polygons) {
  61101. var csg = new CSG();
  61102. csg.polygons = polygons;
  61103. return csg;
  61104. };
  61105. CSG.prototype.clone = function () {
  61106. var csg = new CSG();
  61107. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  61108. csg.copyTransformAttributes(this);
  61109. return csg;
  61110. };
  61111. CSG.prototype.toPolygons = function () {
  61112. return this.polygons;
  61113. };
  61114. CSG.prototype.union = function (csg) {
  61115. var a = new Node(this.clone().polygons);
  61116. var b = new Node(csg.clone().polygons);
  61117. a.clipTo(b);
  61118. b.clipTo(a);
  61119. b.invert();
  61120. b.clipTo(a);
  61121. b.invert();
  61122. a.build(b.allPolygons());
  61123. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  61124. };
  61125. CSG.prototype.unionInPlace = function (csg) {
  61126. var a = new Node(this.polygons);
  61127. var b = new Node(csg.polygons);
  61128. a.clipTo(b);
  61129. b.clipTo(a);
  61130. b.invert();
  61131. b.clipTo(a);
  61132. b.invert();
  61133. a.build(b.allPolygons());
  61134. this.polygons = a.allPolygons();
  61135. };
  61136. CSG.prototype.subtract = function (csg) {
  61137. var a = new Node(this.clone().polygons);
  61138. var b = new Node(csg.clone().polygons);
  61139. a.invert();
  61140. a.clipTo(b);
  61141. b.clipTo(a);
  61142. b.invert();
  61143. b.clipTo(a);
  61144. b.invert();
  61145. a.build(b.allPolygons());
  61146. a.invert();
  61147. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  61148. };
  61149. CSG.prototype.subtractInPlace = function (csg) {
  61150. var a = new Node(this.polygons);
  61151. var b = new Node(csg.polygons);
  61152. a.invert();
  61153. a.clipTo(b);
  61154. b.clipTo(a);
  61155. b.invert();
  61156. b.clipTo(a);
  61157. b.invert();
  61158. a.build(b.allPolygons());
  61159. a.invert();
  61160. this.polygons = a.allPolygons();
  61161. };
  61162. CSG.prototype.intersect = function (csg) {
  61163. var a = new Node(this.clone().polygons);
  61164. var b = new Node(csg.clone().polygons);
  61165. a.invert();
  61166. b.clipTo(a);
  61167. b.invert();
  61168. a.clipTo(b);
  61169. b.clipTo(a);
  61170. a.build(b.allPolygons());
  61171. a.invert();
  61172. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  61173. };
  61174. CSG.prototype.intersectInPlace = function (csg) {
  61175. var a = new Node(this.polygons);
  61176. var b = new Node(csg.polygons);
  61177. a.invert();
  61178. b.clipTo(a);
  61179. b.invert();
  61180. a.clipTo(b);
  61181. b.clipTo(a);
  61182. a.build(b.allPolygons());
  61183. a.invert();
  61184. this.polygons = a.allPolygons();
  61185. };
  61186. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  61187. // not modified.
  61188. CSG.prototype.inverse = function () {
  61189. var csg = this.clone();
  61190. csg.inverseInPlace();
  61191. return csg;
  61192. };
  61193. CSG.prototype.inverseInPlace = function () {
  61194. this.polygons.map(function (p) { p.flip(); });
  61195. };
  61196. // This is used to keep meshes transformations so they can be restored
  61197. // when we build back a Babylon Mesh
  61198. // NB : All CSG operations are performed in world coordinates
  61199. CSG.prototype.copyTransformAttributes = function (csg) {
  61200. this.matrix = csg.matrix;
  61201. this.position = csg.position;
  61202. this.rotation = csg.rotation;
  61203. this.scaling = csg.scaling;
  61204. this.rotationQuaternion = csg.rotationQuaternion;
  61205. return this;
  61206. };
  61207. // Build Raw mesh from CSG
  61208. // Coordinates here are in world space
  61209. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  61210. var matrix = this.matrix.clone();
  61211. matrix.invert();
  61212. 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;
  61213. if (keepSubMeshes) {
  61214. // Sort Polygons, since subMeshes are indices range
  61215. polygons.sort(function (a, b) {
  61216. if (a.shared.meshId === b.shared.meshId) {
  61217. return a.shared.subMeshId - b.shared.subMeshId;
  61218. }
  61219. else {
  61220. return a.shared.meshId - b.shared.meshId;
  61221. }
  61222. });
  61223. }
  61224. for (var i = 0, il = polygons.length; i < il; i++) {
  61225. polygon = polygons[i];
  61226. // Building SubMeshes
  61227. if (!subMesh_dict[polygon.shared.meshId]) {
  61228. subMesh_dict[polygon.shared.meshId] = {};
  61229. }
  61230. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  61231. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  61232. indexStart: +Infinity,
  61233. indexEnd: -Infinity,
  61234. materialIndex: polygon.shared.materialIndex
  61235. };
  61236. }
  61237. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  61238. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  61239. polygonIndices[0] = 0;
  61240. polygonIndices[1] = j - 1;
  61241. polygonIndices[2] = j;
  61242. for (var k = 0; k < 3; k++) {
  61243. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  61244. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  61245. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  61246. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  61247. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  61248. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  61249. // Check if 2 points can be merged
  61250. if (!(typeof vertex_idx !== 'undefined' &&
  61251. normals[vertex_idx * 3] === localNormal.x &&
  61252. normals[vertex_idx * 3 + 1] === localNormal.y &&
  61253. normals[vertex_idx * 3 + 2] === localNormal.z &&
  61254. uvs[vertex_idx * 2] === uv.x &&
  61255. uvs[vertex_idx * 2 + 1] === uv.y)) {
  61256. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  61257. uvs.push(uv.x, uv.y);
  61258. normals.push(normal.x, normal.y, normal.z);
  61259. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  61260. }
  61261. indices.push(vertex_idx);
  61262. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  61263. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  61264. currentIndex++;
  61265. }
  61266. }
  61267. }
  61268. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  61269. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  61270. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  61271. mesh.setIndices(indices);
  61272. if (keepSubMeshes) {
  61273. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  61274. var materialIndexOffset = 0, materialMaxIndex;
  61275. mesh.subMeshes = new Array();
  61276. for (var m in subMesh_dict) {
  61277. materialMaxIndex = -1;
  61278. for (var sm in subMesh_dict[m]) {
  61279. subMesh_obj = subMesh_dict[m][sm];
  61280. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  61281. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  61282. }
  61283. materialIndexOffset += ++materialMaxIndex;
  61284. }
  61285. }
  61286. return mesh;
  61287. };
  61288. // Build Mesh from CSG taking material and transforms into account
  61289. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  61290. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  61291. mesh.material = material;
  61292. mesh.position.copyFrom(this.position);
  61293. mesh.rotation.copyFrom(this.rotation);
  61294. if (this.rotationQuaternion) {
  61295. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  61296. }
  61297. mesh.scaling.copyFrom(this.scaling);
  61298. mesh.computeWorldMatrix(true);
  61299. return mesh;
  61300. };
  61301. return CSG;
  61302. }());
  61303. BABYLON.CSG = CSG;
  61304. })(BABYLON || (BABYLON = {}));
  61305. //# sourceMappingURL=babylon.csg.js.map
  61306. var BABYLON;
  61307. (function (BABYLON) {
  61308. var LensFlare = (function () {
  61309. function LensFlare(size, position, color, imgUrl, system) {
  61310. this.size = size;
  61311. this.position = position;
  61312. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  61313. this.dispose = function () {
  61314. if (this.texture) {
  61315. this.texture.dispose();
  61316. }
  61317. // Remove from scene
  61318. var index = this._system.lensFlares.indexOf(this);
  61319. this._system.lensFlares.splice(index, 1);
  61320. };
  61321. this.color = color || new BABYLON.Color3(1, 1, 1);
  61322. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  61323. this._system = system;
  61324. system.lensFlares.push(this);
  61325. }
  61326. return LensFlare;
  61327. }());
  61328. BABYLON.LensFlare = LensFlare;
  61329. })(BABYLON || (BABYLON = {}));
  61330. //# sourceMappingURL=babylon.lensFlare.js.map
  61331. var BABYLON;
  61332. (function (BABYLON) {
  61333. var LensFlareSystem = (function () {
  61334. function LensFlareSystem(name, emitter, scene) {
  61335. this.name = name;
  61336. this.lensFlares = new Array();
  61337. this.borderLimit = 300;
  61338. this.viewportBorder = 0;
  61339. this.layerMask = 0x0FFFFFFF;
  61340. this._vertexBuffers = {};
  61341. this._isEnabled = true;
  61342. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61343. this._emitter = emitter;
  61344. this.id = name;
  61345. scene.lensFlareSystems.push(this);
  61346. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  61347. var engine = scene.getEngine();
  61348. // VBO
  61349. var vertices = [];
  61350. vertices.push(1, 1);
  61351. vertices.push(-1, 1);
  61352. vertices.push(-1, -1);
  61353. vertices.push(1, -1);
  61354. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61355. // Indices
  61356. var indices = [];
  61357. indices.push(0);
  61358. indices.push(1);
  61359. indices.push(2);
  61360. indices.push(0);
  61361. indices.push(2);
  61362. indices.push(3);
  61363. this._indexBuffer = engine.createIndexBuffer(indices);
  61364. // Effects
  61365. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  61366. }
  61367. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  61368. get: function () {
  61369. return this._isEnabled;
  61370. },
  61371. set: function (value) {
  61372. this._isEnabled = value;
  61373. },
  61374. enumerable: true,
  61375. configurable: true
  61376. });
  61377. LensFlareSystem.prototype.getScene = function () {
  61378. return this._scene;
  61379. };
  61380. LensFlareSystem.prototype.getEmitter = function () {
  61381. return this._emitter;
  61382. };
  61383. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  61384. this._emitter = newEmitter;
  61385. };
  61386. LensFlareSystem.prototype.getEmitterPosition = function () {
  61387. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  61388. };
  61389. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  61390. var position = this.getEmitterPosition();
  61391. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  61392. this._positionX = position.x;
  61393. this._positionY = position.y;
  61394. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  61395. if (this.viewportBorder > 0) {
  61396. globalViewport.x -= this.viewportBorder;
  61397. globalViewport.y -= this.viewportBorder;
  61398. globalViewport.width += this.viewportBorder * 2;
  61399. globalViewport.height += this.viewportBorder * 2;
  61400. position.x += this.viewportBorder;
  61401. position.y += this.viewportBorder;
  61402. this._positionX += this.viewportBorder;
  61403. this._positionY += this.viewportBorder;
  61404. }
  61405. if (position.z > 0) {
  61406. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  61407. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  61408. return true;
  61409. }
  61410. return true;
  61411. }
  61412. return false;
  61413. };
  61414. LensFlareSystem.prototype._isVisible = function () {
  61415. if (!this._isEnabled) {
  61416. return false;
  61417. }
  61418. var emitterPosition = this.getEmitterPosition();
  61419. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  61420. var distance = direction.length();
  61421. direction.normalize();
  61422. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  61423. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  61424. return !pickInfo.hit || pickInfo.distance > distance;
  61425. };
  61426. LensFlareSystem.prototype.render = function () {
  61427. if (!this._effect.isReady())
  61428. return false;
  61429. var engine = this._scene.getEngine();
  61430. var viewport = this._scene.activeCamera.viewport;
  61431. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  61432. // Position
  61433. if (!this.computeEffectivePosition(globalViewport)) {
  61434. return false;
  61435. }
  61436. // Visibility
  61437. if (!this._isVisible()) {
  61438. return false;
  61439. }
  61440. // Intensity
  61441. var awayX;
  61442. var awayY;
  61443. if (this._positionX < this.borderLimit + globalViewport.x) {
  61444. awayX = this.borderLimit + globalViewport.x - this._positionX;
  61445. }
  61446. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  61447. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  61448. }
  61449. else {
  61450. awayX = 0;
  61451. }
  61452. if (this._positionY < this.borderLimit + globalViewport.y) {
  61453. awayY = this.borderLimit + globalViewport.y - this._positionY;
  61454. }
  61455. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  61456. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  61457. }
  61458. else {
  61459. awayY = 0;
  61460. }
  61461. var away = (awayX > awayY) ? awayX : awayY;
  61462. away -= this.viewportBorder;
  61463. if (away > this.borderLimit) {
  61464. away = this.borderLimit;
  61465. }
  61466. var intensity = 1.0 - (away / this.borderLimit);
  61467. if (intensity < 0) {
  61468. return false;
  61469. }
  61470. if (intensity > 1.0) {
  61471. intensity = 1.0;
  61472. }
  61473. if (this.viewportBorder > 0) {
  61474. globalViewport.x += this.viewportBorder;
  61475. globalViewport.y += this.viewportBorder;
  61476. globalViewport.width -= this.viewportBorder * 2;
  61477. globalViewport.height -= this.viewportBorder * 2;
  61478. this._positionX -= this.viewportBorder;
  61479. this._positionY -= this.viewportBorder;
  61480. }
  61481. // Position
  61482. var centerX = globalViewport.x + globalViewport.width / 2;
  61483. var centerY = globalViewport.y + globalViewport.height / 2;
  61484. var distX = centerX - this._positionX;
  61485. var distY = centerY - this._positionY;
  61486. // Effects
  61487. engine.enableEffect(this._effect);
  61488. engine.setState(false);
  61489. engine.setDepthBuffer(false);
  61490. // VBOs
  61491. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  61492. // Flares
  61493. for (var index = 0; index < this.lensFlares.length; index++) {
  61494. var flare = this.lensFlares[index];
  61495. engine.setAlphaMode(flare.alphaMode);
  61496. var x = centerX - (distX * flare.position);
  61497. var y = centerY - (distY * flare.position);
  61498. var cw = flare.size;
  61499. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  61500. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  61501. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  61502. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  61503. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  61504. // Texture
  61505. this._effect.setTexture("textureSampler", flare.texture);
  61506. // Color
  61507. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  61508. // Draw order
  61509. engine.draw(true, 0, 6);
  61510. }
  61511. engine.setDepthBuffer(true);
  61512. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61513. return true;
  61514. };
  61515. LensFlareSystem.prototype.dispose = function () {
  61516. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61517. if (vertexBuffer) {
  61518. vertexBuffer.dispose();
  61519. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61520. }
  61521. if (this._indexBuffer) {
  61522. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61523. this._indexBuffer = null;
  61524. }
  61525. while (this.lensFlares.length) {
  61526. this.lensFlares[0].dispose();
  61527. }
  61528. // Remove from scene
  61529. var index = this._scene.lensFlareSystems.indexOf(this);
  61530. this._scene.lensFlareSystems.splice(index, 1);
  61531. };
  61532. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  61533. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  61534. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  61535. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  61536. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  61537. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  61538. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  61539. var parsedFlare = parsedLensFlareSystem.flares[index];
  61540. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  61541. }
  61542. return lensFlareSystem;
  61543. };
  61544. LensFlareSystem.prototype.serialize = function () {
  61545. var serializationObject = {};
  61546. serializationObject.id = this.id;
  61547. serializationObject.name = this.name;
  61548. serializationObject.emitterId = this.getEmitter().id;
  61549. serializationObject.borderLimit = this.borderLimit;
  61550. serializationObject.flares = [];
  61551. for (var index = 0; index < this.lensFlares.length; index++) {
  61552. var flare = this.lensFlares[index];
  61553. serializationObject.flares.push({
  61554. size: flare.size,
  61555. position: flare.position,
  61556. color: flare.color.asArray(),
  61557. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  61558. });
  61559. }
  61560. return serializationObject;
  61561. };
  61562. return LensFlareSystem;
  61563. }());
  61564. BABYLON.LensFlareSystem = LensFlareSystem;
  61565. })(BABYLON || (BABYLON = {}));
  61566. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  61567. var BABYLON;
  61568. (function (BABYLON) {
  61569. /**
  61570. * This is a holder class for the physics joint created by the physics plugin.
  61571. * It holds a set of functions to control the underlying joint.
  61572. */
  61573. var PhysicsJoint = (function () {
  61574. function PhysicsJoint(type, jointData) {
  61575. this.type = type;
  61576. this.jointData = jointData;
  61577. jointData.nativeParams = jointData.nativeParams || {};
  61578. }
  61579. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  61580. get: function () {
  61581. return this._physicsJoint;
  61582. },
  61583. set: function (newJoint) {
  61584. if (this._physicsJoint) {
  61585. //remove from the wolrd
  61586. }
  61587. this._physicsJoint = newJoint;
  61588. },
  61589. enumerable: true,
  61590. configurable: true
  61591. });
  61592. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  61593. set: function (physicsPlugin) {
  61594. this._physicsPlugin = physicsPlugin;
  61595. },
  61596. enumerable: true,
  61597. configurable: true
  61598. });
  61599. /**
  61600. * Execute a function that is physics-plugin specific.
  61601. * @param {Function} func the function that will be executed.
  61602. * It accepts two parameters: the physics world and the physics joint.
  61603. */
  61604. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  61605. func(this._physicsPlugin.world, this._physicsJoint);
  61606. };
  61607. //TODO check if the native joints are the same
  61608. //Joint Types
  61609. PhysicsJoint.DistanceJoint = 0;
  61610. PhysicsJoint.HingeJoint = 1;
  61611. PhysicsJoint.BallAndSocketJoint = 2;
  61612. PhysicsJoint.WheelJoint = 3;
  61613. PhysicsJoint.SliderJoint = 4;
  61614. //OIMO
  61615. PhysicsJoint.PrismaticJoint = 5;
  61616. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  61617. PhysicsJoint.UniversalJoint = 6;
  61618. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  61619. //Cannon
  61620. //Similar to a Ball-Joint. Different in params
  61621. PhysicsJoint.PointToPointJoint = 8;
  61622. //Cannon only at the moment
  61623. PhysicsJoint.SpringJoint = 9;
  61624. PhysicsJoint.LockJoint = 10;
  61625. return PhysicsJoint;
  61626. }());
  61627. BABYLON.PhysicsJoint = PhysicsJoint;
  61628. /**
  61629. * A class representing a physics distance joint.
  61630. */
  61631. var DistanceJoint = (function (_super) {
  61632. __extends(DistanceJoint, _super);
  61633. function DistanceJoint(jointData) {
  61634. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  61635. }
  61636. /**
  61637. * Update the predefined distance.
  61638. */
  61639. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  61640. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  61641. };
  61642. return DistanceJoint;
  61643. }(PhysicsJoint));
  61644. BABYLON.DistanceJoint = DistanceJoint;
  61645. var MotorEnabledJoint = (function (_super) {
  61646. __extends(MotorEnabledJoint, _super);
  61647. function MotorEnabledJoint(type, jointData) {
  61648. return _super.call(this, type, jointData) || this;
  61649. }
  61650. /**
  61651. * Set the motor values.
  61652. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61653. * @param {number} force the force to apply
  61654. * @param {number} maxForce max force for this motor.
  61655. */
  61656. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  61657. this._physicsPlugin.setMotor(this, force, maxForce);
  61658. };
  61659. /**
  61660. * Set the motor's limits.
  61661. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61662. */
  61663. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61664. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61665. };
  61666. return MotorEnabledJoint;
  61667. }(PhysicsJoint));
  61668. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  61669. /**
  61670. * This class represents a single hinge physics joint
  61671. */
  61672. var HingeJoint = (function (_super) {
  61673. __extends(HingeJoint, _super);
  61674. function HingeJoint(jointData) {
  61675. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  61676. }
  61677. /**
  61678. * Set the motor values.
  61679. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61680. * @param {number} force the force to apply
  61681. * @param {number} maxForce max force for this motor.
  61682. */
  61683. HingeJoint.prototype.setMotor = function (force, maxForce) {
  61684. this._physicsPlugin.setMotor(this, force, maxForce);
  61685. };
  61686. /**
  61687. * Set the motor's limits.
  61688. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61689. */
  61690. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  61691. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  61692. };
  61693. return HingeJoint;
  61694. }(MotorEnabledJoint));
  61695. BABYLON.HingeJoint = HingeJoint;
  61696. /**
  61697. * This class represents a dual hinge physics joint (same as wheel joint)
  61698. */
  61699. var Hinge2Joint = (function (_super) {
  61700. __extends(Hinge2Joint, _super);
  61701. function Hinge2Joint(jointData) {
  61702. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  61703. }
  61704. /**
  61705. * Set the motor values.
  61706. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61707. * @param {number} force the force to apply
  61708. * @param {number} maxForce max force for this motor.
  61709. * @param {motorIndex} the motor's index, 0 or 1.
  61710. */
  61711. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  61712. if (motorIndex === void 0) { motorIndex = 0; }
  61713. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  61714. };
  61715. /**
  61716. * Set the motor limits.
  61717. * Attention, this function is plugin specific. Engines won't react 100% the same.
  61718. * @param {number} upperLimit the upper limit
  61719. * @param {number} lowerLimit lower limit
  61720. * @param {motorIndex} the motor's index, 0 or 1.
  61721. */
  61722. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  61723. if (motorIndex === void 0) { motorIndex = 0; }
  61724. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  61725. };
  61726. return Hinge2Joint;
  61727. }(MotorEnabledJoint));
  61728. BABYLON.Hinge2Joint = Hinge2Joint;
  61729. })(BABYLON || (BABYLON = {}));
  61730. //# sourceMappingURL=babylon.physicsJoint.js.map
  61731. var BABYLON;
  61732. (function (BABYLON) {
  61733. var PhysicsImpostor = (function () {
  61734. function PhysicsImpostor(object, type, _options, _scene) {
  61735. if (_options === void 0) { _options = { mass: 0 }; }
  61736. var _this = this;
  61737. this.object = object;
  61738. this.type = type;
  61739. this._options = _options;
  61740. this._scene = _scene;
  61741. this._bodyUpdateRequired = false;
  61742. this._onBeforePhysicsStepCallbacks = new Array();
  61743. this._onAfterPhysicsStepCallbacks = new Array();
  61744. this._onPhysicsCollideCallbacks = [];
  61745. this._deltaPosition = BABYLON.Vector3.Zero();
  61746. this._isDisposed = false;
  61747. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  61748. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  61749. /**
  61750. * this function is executed by the physics engine.
  61751. */
  61752. this.beforeStep = function () {
  61753. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  61754. //conjugate deltaRotation
  61755. if (_this._deltaRotationConjugated) {
  61756. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  61757. }
  61758. else {
  61759. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  61760. }
  61761. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  61762. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  61763. func(_this);
  61764. });
  61765. };
  61766. /**
  61767. * this function is executed by the physics engine.
  61768. */
  61769. this.afterStep = function () {
  61770. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  61771. func(_this);
  61772. });
  61773. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  61774. _this.object.position.addInPlace(_this._deltaPosition);
  61775. if (_this._deltaRotation) {
  61776. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  61777. }
  61778. };
  61779. /**
  61780. * Legacy collision detection event support
  61781. */
  61782. this.onCollideEvent = null;
  61783. //event and body object due to cannon's event-based architecture.
  61784. this.onCollide = function (e) {
  61785. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  61786. return;
  61787. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  61788. if (otherImpostor) {
  61789. // Legacy collision detection event support
  61790. if (_this.onCollideEvent) {
  61791. _this.onCollideEvent(_this, otherImpostor);
  61792. }
  61793. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  61794. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  61795. }).forEach(function (obj) {
  61796. obj.callback(_this, otherImpostor);
  61797. });
  61798. }
  61799. };
  61800. //sanity check!
  61801. if (!this.object) {
  61802. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  61803. return;
  61804. }
  61805. //legacy support for old syntax.
  61806. if (!this._scene && object.getScene) {
  61807. this._scene = object.getScene();
  61808. }
  61809. this._physicsEngine = this._scene.getPhysicsEngine();
  61810. if (!this._physicsEngine) {
  61811. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  61812. }
  61813. else {
  61814. //set the object's quaternion, if not set
  61815. if (!this.object.rotationQuaternion) {
  61816. if (this.object.rotation) {
  61817. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  61818. }
  61819. else {
  61820. this.object.rotationQuaternion = new BABYLON.Quaternion();
  61821. }
  61822. }
  61823. //default options params
  61824. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  61825. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  61826. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  61827. this._joints = [];
  61828. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  61829. if (!this.object.parent) {
  61830. this._init();
  61831. }
  61832. else if (this.object.parent.physicsImpostor) {
  61833. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  61834. }
  61835. }
  61836. }
  61837. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  61838. get: function () {
  61839. return this._isDisposed;
  61840. },
  61841. enumerable: true,
  61842. configurable: true
  61843. });
  61844. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  61845. get: function () {
  61846. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  61847. },
  61848. set: function (value) {
  61849. this.setMass(value);
  61850. },
  61851. enumerable: true,
  61852. configurable: true
  61853. });
  61854. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  61855. get: function () {
  61856. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  61857. },
  61858. set: function (value) {
  61859. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  61860. },
  61861. enumerable: true,
  61862. configurable: true
  61863. });
  61864. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  61865. get: function () {
  61866. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  61867. },
  61868. set: function (value) {
  61869. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  61870. },
  61871. enumerable: true,
  61872. configurable: true
  61873. });
  61874. /**
  61875. * This function will completly initialize this impostor.
  61876. * It will create a new body - but only if this mesh has no parent.
  61877. * If it has, this impostor will not be used other than to define the impostor
  61878. * of the child mesh.
  61879. */
  61880. PhysicsImpostor.prototype._init = function () {
  61881. this._physicsEngine.removeImpostor(this);
  61882. this.physicsBody = null;
  61883. this._parent = this._parent || this._getPhysicsParent();
  61884. if (!this.parent) {
  61885. this._physicsEngine.addImpostor(this);
  61886. }
  61887. };
  61888. PhysicsImpostor.prototype._getPhysicsParent = function () {
  61889. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  61890. var parentMesh = this.object.parent;
  61891. return parentMesh.physicsImpostor;
  61892. }
  61893. return;
  61894. };
  61895. /**
  61896. * Should a new body be generated.
  61897. */
  61898. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  61899. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  61900. };
  61901. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  61902. this.forceUpdate();
  61903. };
  61904. /**
  61905. * Force a regeneration of this or the parent's impostor's body.
  61906. * Use under cautious - This will remove all joints already implemented.
  61907. */
  61908. PhysicsImpostor.prototype.forceUpdate = function () {
  61909. this._init();
  61910. if (this.parent) {
  61911. this.parent.forceUpdate();
  61912. }
  61913. };
  61914. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  61915. /*public get mesh(): AbstractMesh {
  61916. return this._mesh;
  61917. }*/
  61918. /**
  61919. * Gets the body that holds this impostor. Either its own, or its parent.
  61920. */
  61921. get: function () {
  61922. return this._parent ? this._parent.physicsBody : this._physicsBody;
  61923. },
  61924. /**
  61925. * Set the physics body. Used mainly by the physics engine/plugin
  61926. */
  61927. set: function (physicsBody) {
  61928. if (this._physicsBody) {
  61929. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  61930. }
  61931. this._physicsBody = physicsBody;
  61932. this.resetUpdateFlags();
  61933. },
  61934. enumerable: true,
  61935. configurable: true
  61936. });
  61937. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  61938. get: function () {
  61939. return this._parent;
  61940. },
  61941. set: function (value) {
  61942. this._parent = value;
  61943. },
  61944. enumerable: true,
  61945. configurable: true
  61946. });
  61947. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  61948. this._bodyUpdateRequired = false;
  61949. };
  61950. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  61951. if (this.object.getBoundingInfo) {
  61952. var q = this.object.rotationQuaternion;
  61953. //reset rotation
  61954. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  61955. //calculate the world matrix with no rotation
  61956. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61957. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  61958. //bring back the rotation
  61959. this.object.rotationQuaternion = q;
  61960. //calculate the world matrix with the new rotation
  61961. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61962. return size;
  61963. }
  61964. else {
  61965. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  61966. }
  61967. };
  61968. PhysicsImpostor.prototype.getObjectCenter = function () {
  61969. if (this.object.getBoundingInfo) {
  61970. return this.object.getBoundingInfo().boundingBox.centerWorld;
  61971. }
  61972. else {
  61973. return this.object.position;
  61974. }
  61975. };
  61976. /**
  61977. * Get a specific parametes from the options parameter.
  61978. */
  61979. PhysicsImpostor.prototype.getParam = function (paramName) {
  61980. return this._options[paramName];
  61981. };
  61982. /**
  61983. * Sets a specific parameter in the options given to the physics plugin
  61984. */
  61985. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  61986. this._options[paramName] = value;
  61987. this._bodyUpdateRequired = true;
  61988. };
  61989. /**
  61990. * Specifically change the body's mass option. Won't recreate the physics body object
  61991. */
  61992. PhysicsImpostor.prototype.setMass = function (mass) {
  61993. if (this.getParam("mass") !== mass) {
  61994. this.setParam("mass", mass);
  61995. }
  61996. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  61997. };
  61998. PhysicsImpostor.prototype.getLinearVelocity = function () {
  61999. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  62000. };
  62001. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  62002. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  62003. };
  62004. PhysicsImpostor.prototype.getAngularVelocity = function () {
  62005. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  62006. };
  62007. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  62008. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  62009. };
  62010. /**
  62011. * Execute a function with the physics plugin native code.
  62012. * Provide a function the will have two variables - the world object and the physics body object.
  62013. */
  62014. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  62015. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  62016. };
  62017. /**
  62018. * Register a function that will be executed before the physics world is stepping forward.
  62019. */
  62020. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  62021. this._onBeforePhysicsStepCallbacks.push(func);
  62022. };
  62023. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  62024. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  62025. if (index > -1) {
  62026. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  62027. }
  62028. else {
  62029. BABYLON.Tools.Warn("Function to remove was not found");
  62030. }
  62031. };
  62032. /**
  62033. * Register a function that will be executed after the physics step
  62034. */
  62035. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  62036. this._onAfterPhysicsStepCallbacks.push(func);
  62037. };
  62038. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  62039. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  62040. if (index > -1) {
  62041. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  62042. }
  62043. else {
  62044. BABYLON.Tools.Warn("Function to remove was not found");
  62045. }
  62046. };
  62047. /**
  62048. * register a function that will be executed when this impostor collides against a different body.
  62049. */
  62050. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  62051. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  62052. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  62053. };
  62054. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  62055. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  62056. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  62057. if (index > -1) {
  62058. this._onPhysicsCollideCallbacks.splice(index, 1);
  62059. }
  62060. else {
  62061. BABYLON.Tools.Warn("Function to remove was not found");
  62062. }
  62063. };
  62064. /**
  62065. * Apply a force
  62066. */
  62067. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  62068. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  62069. };
  62070. /**
  62071. * Apply an impulse
  62072. */
  62073. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  62074. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  62075. };
  62076. /**
  62077. * A help function to create a joint.
  62078. */
  62079. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  62080. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  62081. this.addJoint(otherImpostor, joint);
  62082. };
  62083. /**
  62084. * Add a joint to this impostor with a different impostor.
  62085. */
  62086. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  62087. this._joints.push({
  62088. otherImpostor: otherImpostor,
  62089. joint: joint
  62090. });
  62091. this._physicsEngine.addJoint(this, otherImpostor, joint);
  62092. };
  62093. /**
  62094. * Will keep this body still, in a sleep mode.
  62095. */
  62096. PhysicsImpostor.prototype.sleep = function () {
  62097. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  62098. };
  62099. /**
  62100. * Wake the body up.
  62101. */
  62102. PhysicsImpostor.prototype.wakeUp = function () {
  62103. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  62104. };
  62105. PhysicsImpostor.prototype.clone = function (newObject) {
  62106. if (!newObject)
  62107. return null;
  62108. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  62109. };
  62110. PhysicsImpostor.prototype.dispose = function () {
  62111. var _this = this;
  62112. //no dispose if no physics engine is available.
  62113. if (!this._physicsEngine) {
  62114. return;
  62115. }
  62116. this._joints.forEach(function (j) {
  62117. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  62118. });
  62119. //dispose the physics body
  62120. this._physicsEngine.removeImpostor(this);
  62121. if (this.parent) {
  62122. this.parent.forceUpdate();
  62123. }
  62124. else {
  62125. /*this._object.getChildMeshes().forEach(function(mesh) {
  62126. if (mesh.physicsImpostor) {
  62127. if (disposeChildren) {
  62128. mesh.physicsImpostor.dispose();
  62129. mesh.physicsImpostor = null;
  62130. }
  62131. }
  62132. })*/
  62133. }
  62134. this._isDisposed = true;
  62135. };
  62136. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  62137. this._deltaPosition.copyFrom(position);
  62138. };
  62139. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  62140. if (!this._deltaRotation) {
  62141. this._deltaRotation = new BABYLON.Quaternion();
  62142. }
  62143. this._deltaRotation.copyFrom(rotation);
  62144. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  62145. };
  62146. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  62147. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  62148. };
  62149. PhysicsImpostor.prototype.getRadius = function () {
  62150. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  62151. };
  62152. /**
  62153. * Sync a bone with this impostor
  62154. * @param bone The bone to sync to the impostor.
  62155. * @param boneMesh The mesh that the bone is influencing.
  62156. * @param jointPivot The pivot of the joint / bone in local space.
  62157. * @param distToJoint Optional distance from the impostor to the joint.
  62158. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  62159. */
  62160. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  62161. var tempVec = PhysicsImpostor._tmpVecs[0];
  62162. var mesh = this.object;
  62163. if (adjustRotation) {
  62164. var tempQuat = PhysicsImpostor._tmpQuat;
  62165. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  62166. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  62167. }
  62168. else {
  62169. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  62170. }
  62171. tempVec.x = 0;
  62172. tempVec.y = 0;
  62173. tempVec.z = 0;
  62174. if (jointPivot) {
  62175. tempVec.x = jointPivot.x;
  62176. tempVec.y = jointPivot.y;
  62177. tempVec.z = jointPivot.z;
  62178. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  62179. if (distToJoint === undefined || distToJoint === null) {
  62180. distToJoint = jointPivot.length();
  62181. }
  62182. tempVec.x *= distToJoint;
  62183. tempVec.y *= distToJoint;
  62184. tempVec.z *= distToJoint;
  62185. }
  62186. if (bone.getParent()) {
  62187. tempVec.addInPlace(mesh.getAbsolutePosition());
  62188. bone.setAbsolutePosition(tempVec, boneMesh);
  62189. }
  62190. else {
  62191. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  62192. boneMesh.position.x -= tempVec.x;
  62193. boneMesh.position.y -= tempVec.y;
  62194. boneMesh.position.z -= tempVec.z;
  62195. }
  62196. };
  62197. /**
  62198. * Sync impostor to a bone
  62199. * @param bone The bone that the impostor will be synced to.
  62200. * @param boneMesh The mesh that the bone is influencing.
  62201. * @param jointPivot The pivot of the joint / bone in local space.
  62202. * @param distToJoint Optional distance from the impostor to the joint.
  62203. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  62204. * @param boneAxis Optional vector3 axis the bone is aligned with
  62205. */
  62206. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  62207. var mesh = this.object;
  62208. if (adjustRotation) {
  62209. var tempQuat = PhysicsImpostor._tmpQuat;
  62210. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  62211. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  62212. }
  62213. else {
  62214. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  62215. }
  62216. var pos = PhysicsImpostor._tmpVecs[0];
  62217. var boneDir = PhysicsImpostor._tmpVecs[1];
  62218. if (!boneAxis) {
  62219. boneAxis = PhysicsImpostor._tmpVecs[2];
  62220. boneAxis.x = 0;
  62221. boneAxis.y = 1;
  62222. boneAxis.z = 0;
  62223. }
  62224. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  62225. bone.getAbsolutePositionToRef(boneMesh, pos);
  62226. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  62227. distToJoint = jointPivot.length();
  62228. }
  62229. if (distToJoint !== undefined && distToJoint !== null) {
  62230. pos.x += boneDir.x * distToJoint;
  62231. pos.y += boneDir.y * distToJoint;
  62232. pos.z += boneDir.z * distToJoint;
  62233. }
  62234. mesh.setAbsolutePosition(pos);
  62235. };
  62236. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  62237. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  62238. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62239. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  62240. //Impostor types
  62241. PhysicsImpostor.NoImpostor = 0;
  62242. PhysicsImpostor.SphereImpostor = 1;
  62243. PhysicsImpostor.BoxImpostor = 2;
  62244. PhysicsImpostor.PlaneImpostor = 3;
  62245. PhysicsImpostor.MeshImpostor = 4;
  62246. PhysicsImpostor.CylinderImpostor = 7;
  62247. PhysicsImpostor.ParticleImpostor = 8;
  62248. PhysicsImpostor.HeightmapImpostor = 9;
  62249. return PhysicsImpostor;
  62250. }());
  62251. BABYLON.PhysicsImpostor = PhysicsImpostor;
  62252. })(BABYLON || (BABYLON = {}));
  62253. //# sourceMappingURL=babylon.physicsImpostor.js.map
  62254. var BABYLON;
  62255. (function (BABYLON) {
  62256. var PhysicsEngine = (function () {
  62257. function PhysicsEngine(gravity, _physicsPlugin) {
  62258. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  62259. this._physicsPlugin = _physicsPlugin;
  62260. //new methods and parameters
  62261. this._impostors = [];
  62262. this._joints = [];
  62263. if (!this._physicsPlugin.isSupported()) {
  62264. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  62265. + "Please make sure it is included.");
  62266. }
  62267. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  62268. this.setGravity(gravity);
  62269. this.setTimeStep();
  62270. }
  62271. PhysicsEngine.prototype.setGravity = function (gravity) {
  62272. this.gravity = gravity;
  62273. this._physicsPlugin.setGravity(this.gravity);
  62274. };
  62275. /**
  62276. * Set the time step of the physics engine.
  62277. * default is 1/60.
  62278. * To slow it down, enter 1/600 for example.
  62279. * To speed it up, 1/30
  62280. * @param {number} newTimeStep the new timestep to apply to this world.
  62281. */
  62282. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  62283. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  62284. this._physicsPlugin.setTimeStep(newTimeStep);
  62285. };
  62286. /**
  62287. * Get the time step of the physics engine.
  62288. */
  62289. PhysicsEngine.prototype.getTimeStep = function () {
  62290. return this._physicsPlugin.getTimeStep();
  62291. };
  62292. PhysicsEngine.prototype.dispose = function () {
  62293. this._impostors.forEach(function (impostor) {
  62294. impostor.dispose();
  62295. });
  62296. this._physicsPlugin.dispose();
  62297. };
  62298. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  62299. return this._physicsPlugin.name;
  62300. };
  62301. /**
  62302. * Adding a new impostor for the impostor tracking.
  62303. * This will be done by the impostor itself.
  62304. * @param {PhysicsImpostor} impostor the impostor to add
  62305. */
  62306. PhysicsEngine.prototype.addImpostor = function (impostor) {
  62307. impostor.uniqueId = this._impostors.push(impostor);
  62308. //if no parent, generate the body
  62309. if (!impostor.parent) {
  62310. this._physicsPlugin.generatePhysicsBody(impostor);
  62311. }
  62312. };
  62313. /**
  62314. * Remove an impostor from the engine.
  62315. * This impostor and its mesh will not longer be updated by the physics engine.
  62316. * @param {PhysicsImpostor} impostor the impostor to remove
  62317. */
  62318. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  62319. var index = this._impostors.indexOf(impostor);
  62320. if (index > -1) {
  62321. var removed = this._impostors.splice(index, 1);
  62322. //Is it needed?
  62323. if (removed.length) {
  62324. //this will also remove it from the world.
  62325. removed[0].physicsBody = null;
  62326. }
  62327. }
  62328. };
  62329. /**
  62330. * Add a joint to the physics engine
  62331. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  62332. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  62333. * @param {PhysicsJoint} the joint that will connect both impostors.
  62334. */
  62335. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  62336. var impostorJoint = {
  62337. mainImpostor: mainImpostor,
  62338. connectedImpostor: connectedImpostor,
  62339. joint: joint
  62340. };
  62341. joint.physicsPlugin = this._physicsPlugin;
  62342. this._joints.push(impostorJoint);
  62343. this._physicsPlugin.generateJoint(impostorJoint);
  62344. };
  62345. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  62346. var matchingJoints = this._joints.filter(function (impostorJoint) {
  62347. return (impostorJoint.connectedImpostor === connectedImpostor
  62348. && impostorJoint.joint === joint
  62349. && impostorJoint.mainImpostor === mainImpostor);
  62350. });
  62351. if (matchingJoints.length) {
  62352. this._physicsPlugin.removeJoint(matchingJoints[0]);
  62353. //TODO remove it from the list as well
  62354. }
  62355. };
  62356. /**
  62357. * Called by the scene. no need to call it.
  62358. */
  62359. PhysicsEngine.prototype._step = function (delta) {
  62360. var _this = this;
  62361. //check if any mesh has no body / requires an update
  62362. this._impostors.forEach(function (impostor) {
  62363. if (impostor.isBodyInitRequired()) {
  62364. _this._physicsPlugin.generatePhysicsBody(impostor);
  62365. }
  62366. });
  62367. if (delta > 0.1) {
  62368. delta = 0.1;
  62369. }
  62370. else if (delta <= 0) {
  62371. delta = 1.0 / 60.0;
  62372. }
  62373. this._physicsPlugin.executeStep(delta, this._impostors);
  62374. };
  62375. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  62376. return this._physicsPlugin;
  62377. };
  62378. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  62379. for (var i = 0; i < this._impostors.length; ++i) {
  62380. if (this._impostors[i].object === object) {
  62381. return this._impostors[i];
  62382. }
  62383. }
  62384. };
  62385. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  62386. for (var i = 0; i < this._impostors.length; ++i) {
  62387. if (this._impostors[i].physicsBody === body) {
  62388. return this._impostors[i];
  62389. }
  62390. }
  62391. };
  62392. // Statics
  62393. PhysicsEngine.Epsilon = 0.001;
  62394. return PhysicsEngine;
  62395. }());
  62396. BABYLON.PhysicsEngine = PhysicsEngine;
  62397. })(BABYLON || (BABYLON = {}));
  62398. //# sourceMappingURL=babylon.physicsEngine.js.map
  62399. var BABYLON;
  62400. (function (BABYLON) {
  62401. var CannonJSPlugin = (function () {
  62402. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  62403. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  62404. if (iterations === void 0) { iterations = 10; }
  62405. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  62406. this.name = "CannonJSPlugin";
  62407. this._physicsMaterials = [];
  62408. this._fixedTimeStep = 1 / 60;
  62409. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  62410. this._currentCollisionGroup = 2;
  62411. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  62412. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  62413. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  62414. this._tmpPosition = BABYLON.Vector3.Zero();
  62415. this._tmpQuaternion = new BABYLON.Quaternion();
  62416. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  62417. this._tmpDeltaRotation = new BABYLON.Quaternion();
  62418. this._tmpUnityRotation = new BABYLON.Quaternion();
  62419. if (!this.isSupported()) {
  62420. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  62421. return;
  62422. }
  62423. this.world = new this.BJSCANNON.World();
  62424. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  62425. this.world.solver.iterations = iterations;
  62426. }
  62427. CannonJSPlugin.prototype.setGravity = function (gravity) {
  62428. this.world.gravity.copy(gravity);
  62429. };
  62430. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  62431. this._fixedTimeStep = timeStep;
  62432. };
  62433. CannonJSPlugin.prototype.getTimeStep = function () {
  62434. return this._fixedTimeStep;
  62435. };
  62436. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  62437. // Delta is in seconds, should be provided in milliseconds
  62438. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  62439. };
  62440. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  62441. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  62442. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  62443. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  62444. };
  62445. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  62446. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  62447. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  62448. impostor.physicsBody.applyForce(impulse, worldPoint);
  62449. };
  62450. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  62451. //parent-child relationship. Does this impostor has a parent impostor?
  62452. if (impostor.parent) {
  62453. if (impostor.physicsBody) {
  62454. this.removePhysicsBody(impostor);
  62455. //TODO is that needed?
  62456. impostor.forceUpdate();
  62457. }
  62458. return;
  62459. }
  62460. //should a new body be created for this impostor?
  62461. if (impostor.isBodyInitRequired()) {
  62462. var shape = this._createShape(impostor);
  62463. //unregister events, if body is being changed
  62464. var oldBody = impostor.physicsBody;
  62465. if (oldBody) {
  62466. this.removePhysicsBody(impostor);
  62467. }
  62468. //create the body and material
  62469. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  62470. var bodyCreationObject = {
  62471. mass: impostor.getParam("mass"),
  62472. material: material
  62473. };
  62474. // A simple extend, in case native options were used.
  62475. var nativeOptions = impostor.getParam("nativeOptions");
  62476. for (var key in nativeOptions) {
  62477. if (nativeOptions.hasOwnProperty(key)) {
  62478. bodyCreationObject[key] = nativeOptions[key];
  62479. }
  62480. }
  62481. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  62482. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  62483. this.world.addEventListener("preStep", impostor.beforeStep);
  62484. this.world.addEventListener("postStep", impostor.afterStep);
  62485. impostor.physicsBody.addShape(shape);
  62486. this.world.add(impostor.physicsBody);
  62487. //try to keep the body moving in the right direction by taking old properties.
  62488. //Should be tested!
  62489. if (oldBody) {
  62490. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  62491. impostor.physicsBody[param].copy(oldBody[param]);
  62492. });
  62493. }
  62494. this._processChildMeshes(impostor);
  62495. }
  62496. //now update the body's transformation
  62497. this._updatePhysicsBodyTransformation(impostor);
  62498. };
  62499. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  62500. var _this = this;
  62501. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  62502. var currentRotation = mainImpostor.object.rotationQuaternion;
  62503. if (meshChildren.length) {
  62504. var processMesh = function (localPosition, mesh) {
  62505. var childImpostor = mesh.getPhysicsImpostor();
  62506. if (childImpostor) {
  62507. var parent = childImpostor.parent;
  62508. if (parent !== mainImpostor) {
  62509. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  62510. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  62511. if (childImpostor.physicsBody) {
  62512. _this.removePhysicsBody(childImpostor);
  62513. childImpostor.physicsBody = null;
  62514. }
  62515. childImpostor.parent = mainImpostor;
  62516. childImpostor.resetUpdateFlags();
  62517. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  62518. //Add the mass of the children.
  62519. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  62520. }
  62521. }
  62522. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  62523. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  62524. };
  62525. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  62526. }
  62527. };
  62528. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  62529. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  62530. this.world.removeEventListener("preStep", impostor.beforeStep);
  62531. this.world.removeEventListener("postStep", impostor.afterStep);
  62532. this.world.remove(impostor.physicsBody);
  62533. };
  62534. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  62535. var mainBody = impostorJoint.mainImpostor.physicsBody;
  62536. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  62537. if (!mainBody || !connectedBody) {
  62538. return;
  62539. }
  62540. var constraint;
  62541. var jointData = impostorJoint.joint.jointData;
  62542. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  62543. var constraintData = {
  62544. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  62545. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  62546. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  62547. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  62548. maxForce: jointData.nativeParams.maxForce,
  62549. collideConnected: !!jointData.collision
  62550. };
  62551. switch (impostorJoint.joint.type) {
  62552. case BABYLON.PhysicsJoint.HingeJoint:
  62553. case BABYLON.PhysicsJoint.Hinge2Joint:
  62554. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  62555. break;
  62556. case BABYLON.PhysicsJoint.DistanceJoint:
  62557. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  62558. break;
  62559. case BABYLON.PhysicsJoint.SpringJoint:
  62560. var springData = jointData;
  62561. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  62562. restLength: springData.length,
  62563. stiffness: springData.stiffness,
  62564. damping: springData.damping,
  62565. localAnchorA: constraintData.pivotA,
  62566. localAnchorB: constraintData.pivotB
  62567. });
  62568. break;
  62569. case BABYLON.PhysicsJoint.LockJoint:
  62570. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  62571. break;
  62572. case BABYLON.PhysicsJoint.PointToPointJoint:
  62573. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  62574. default:
  62575. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  62576. break;
  62577. }
  62578. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  62579. constraint.collideConnected = !!jointData.collision;
  62580. impostorJoint.joint.physicsJoint = constraint;
  62581. //don't add spring as constraint, as it is not one.
  62582. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  62583. this.world.addConstraint(constraint);
  62584. }
  62585. else {
  62586. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  62587. constraint.applyForce();
  62588. });
  62589. }
  62590. };
  62591. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  62592. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  62593. };
  62594. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  62595. var index;
  62596. var mat;
  62597. for (index = 0; index < this._physicsMaterials.length; index++) {
  62598. mat = this._physicsMaterials[index];
  62599. if (mat.friction === friction && mat.restitution === restitution) {
  62600. return mat;
  62601. }
  62602. }
  62603. var currentMat = new this.BJSCANNON.Material(name);
  62604. currentMat.friction = friction;
  62605. currentMat.restitution = restitution;
  62606. this._physicsMaterials.push(currentMat);
  62607. return currentMat;
  62608. };
  62609. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  62610. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  62611. };
  62612. CannonJSPlugin.prototype._createShape = function (impostor) {
  62613. var object = impostor.object;
  62614. var returnValue;
  62615. var extendSize = impostor.getObjectExtendSize();
  62616. switch (impostor.type) {
  62617. case BABYLON.PhysicsImpostor.SphereImpostor:
  62618. var radiusX = extendSize.x;
  62619. var radiusY = extendSize.y;
  62620. var radiusZ = extendSize.z;
  62621. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  62622. break;
  62623. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  62624. case BABYLON.PhysicsImpostor.CylinderImpostor:
  62625. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  62626. break;
  62627. case BABYLON.PhysicsImpostor.BoxImpostor:
  62628. var box = extendSize.scale(0.5);
  62629. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  62630. break;
  62631. case BABYLON.PhysicsImpostor.PlaneImpostor:
  62632. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  62633. returnValue = new this.BJSCANNON.Plane();
  62634. break;
  62635. case BABYLON.PhysicsImpostor.MeshImpostor:
  62636. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  62637. var rawFaces = object.getIndices ? object.getIndices() : [];
  62638. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  62639. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  62640. break;
  62641. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  62642. returnValue = this._createHeightmap(object);
  62643. break;
  62644. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62645. returnValue = new this.BJSCANNON.Particle();
  62646. break;
  62647. }
  62648. return returnValue;
  62649. };
  62650. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  62651. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62652. var matrix = [];
  62653. //For now pointDepth will not be used and will be automatically calculated.
  62654. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  62655. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  62656. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62657. var elementSize = dim * 2 / arraySize;
  62658. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62659. for (var i = 0; i < pos.length; i = i + 3) {
  62660. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  62661. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  62662. var y = pos[i + 1] + minY;
  62663. if (!matrix[x]) {
  62664. matrix[x] = [];
  62665. }
  62666. if (!matrix[x][z]) {
  62667. matrix[x][z] = y;
  62668. }
  62669. matrix[x][z] = Math.max(y, matrix[x][z]);
  62670. }
  62671. for (var x = 0; x <= arraySize; ++x) {
  62672. if (!matrix[x]) {
  62673. var loc = 1;
  62674. while (!matrix[(x + loc) % arraySize]) {
  62675. loc++;
  62676. }
  62677. matrix[x] = matrix[(x + loc) % arraySize].slice();
  62678. //console.log("missing x", x);
  62679. }
  62680. for (var z = 0; z <= arraySize; ++z) {
  62681. if (!matrix[x][z]) {
  62682. var loc = 1;
  62683. var newValue;
  62684. while (newValue === undefined) {
  62685. newValue = matrix[x][(z + loc++) % arraySize];
  62686. }
  62687. matrix[x][z] = newValue;
  62688. }
  62689. }
  62690. }
  62691. var shape = new this.BJSCANNON.Heightfield(matrix, {
  62692. elementSize: elementSize
  62693. });
  62694. //For future reference, needed for body transformation
  62695. shape.minY = minY;
  62696. return shape;
  62697. };
  62698. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  62699. var object = impostor.object;
  62700. //make sure it is updated...
  62701. object.computeWorldMatrix && object.computeWorldMatrix(true);
  62702. // The delta between the mesh position and the mesh bounding box center
  62703. var center = impostor.getObjectCenter();
  62704. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  62705. this._tmpPosition.copyFrom(center);
  62706. var quaternion = object.rotationQuaternion;
  62707. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  62708. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  62709. //-90 DEG in X, precalculated
  62710. quaternion = quaternion.multiply(this._minus90X);
  62711. //Invert! (Precalculated, 90 deg in X)
  62712. //No need to clone. this will never change.
  62713. impostor.setDeltaRotation(this._plus90X);
  62714. }
  62715. //If it is a heightfield, if should be centered.
  62716. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  62717. var mesh = object;
  62718. //calculate the correct body position:
  62719. var rotationQuaternion = mesh.rotationQuaternion;
  62720. mesh.rotationQuaternion = this._tmpUnityRotation;
  62721. mesh.computeWorldMatrix(true);
  62722. //get original center with no rotation
  62723. var c = center.clone();
  62724. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  62725. //rotation is back
  62726. mesh.rotationQuaternion = rotationQuaternion;
  62727. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  62728. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  62729. mesh.setPivotMatrix(p);
  62730. mesh.computeWorldMatrix(true);
  62731. //calculate the translation
  62732. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  62733. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  62734. //add it inverted to the delta
  62735. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  62736. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  62737. mesh.setPivotMatrix(oldPivot);
  62738. mesh.computeWorldMatrix(true);
  62739. }
  62740. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  62741. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  62742. this._tmpPosition.copyFrom(object.position);
  62743. }
  62744. impostor.setDeltaPosition(this._tmpDeltaPosition);
  62745. //Now update the impostor object
  62746. impostor.physicsBody.position.copy(this._tmpPosition);
  62747. impostor.physicsBody.quaternion.copy(quaternion);
  62748. };
  62749. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  62750. impostor.object.position.copyFrom(impostor.physicsBody.position);
  62751. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  62752. };
  62753. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  62754. impostor.physicsBody.position.copy(newPosition);
  62755. impostor.physicsBody.quaternion.copy(newRotation);
  62756. };
  62757. CannonJSPlugin.prototype.isSupported = function () {
  62758. return this.BJSCANNON !== undefined;
  62759. };
  62760. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  62761. impostor.physicsBody.velocity.copy(velocity);
  62762. };
  62763. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  62764. impostor.physicsBody.angularVelocity.copy(velocity);
  62765. };
  62766. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  62767. var v = impostor.physicsBody.velocity;
  62768. if (!v)
  62769. return null;
  62770. return new BABYLON.Vector3(v.x, v.y, v.z);
  62771. };
  62772. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  62773. var v = impostor.physicsBody.angularVelocity;
  62774. if (!v)
  62775. return null;
  62776. return new BABYLON.Vector3(v.x, v.y, v.z);
  62777. };
  62778. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62779. impostor.physicsBody.mass = mass;
  62780. impostor.physicsBody.updateMassProperties();
  62781. };
  62782. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  62783. return impostor.physicsBody.mass;
  62784. };
  62785. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  62786. return impostor.physicsBody.material.friction;
  62787. };
  62788. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62789. impostor.physicsBody.material.friction = friction;
  62790. };
  62791. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62792. return impostor.physicsBody.material.restitution;
  62793. };
  62794. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62795. impostor.physicsBody.material.restitution = restitution;
  62796. };
  62797. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  62798. impostor.physicsBody.sleep();
  62799. };
  62800. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  62801. impostor.physicsBody.wakeUp();
  62802. };
  62803. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62804. joint.physicsJoint.distance = maxDistance;
  62805. };
  62806. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  62807. if (!motorIndex) {
  62808. joint.physicsJoint.enableMotor();
  62809. }
  62810. };
  62811. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  62812. if (!motorIndex) {
  62813. joint.physicsJoint.disableMotor();
  62814. }
  62815. };
  62816. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62817. if (!motorIndex) {
  62818. joint.physicsJoint.enableMotor();
  62819. joint.physicsJoint.setMotorSpeed(speed);
  62820. if (maxForce) {
  62821. this.setLimit(joint, maxForce);
  62822. }
  62823. }
  62824. };
  62825. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  62826. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  62827. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  62828. };
  62829. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62830. var body = impostor.physicsBody;
  62831. mesh.position.x = body.position.x;
  62832. mesh.position.y = body.position.y;
  62833. mesh.position.z = body.position.z;
  62834. mesh.rotationQuaternion.x = body.quaternion.x;
  62835. mesh.rotationQuaternion.y = body.quaternion.y;
  62836. mesh.rotationQuaternion.z = body.quaternion.z;
  62837. mesh.rotationQuaternion.w = body.quaternion.w;
  62838. };
  62839. CannonJSPlugin.prototype.getRadius = function (impostor) {
  62840. var shape = impostor.physicsBody.shapes[0];
  62841. return shape.boundingSphereRadius;
  62842. };
  62843. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62844. var shape = impostor.physicsBody.shapes[0];
  62845. result.x = shape.halfExtents.x * 2;
  62846. result.y = shape.halfExtents.y * 2;
  62847. result.z = shape.halfExtents.z * 2;
  62848. };
  62849. CannonJSPlugin.prototype.dispose = function () {
  62850. };
  62851. return CannonJSPlugin;
  62852. }());
  62853. BABYLON.CannonJSPlugin = CannonJSPlugin;
  62854. })(BABYLON || (BABYLON = {}));
  62855. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  62856. var BABYLON;
  62857. (function (BABYLON) {
  62858. var OimoJSPlugin = (function () {
  62859. function OimoJSPlugin(iterations) {
  62860. this.name = "OimoJSPlugin";
  62861. this._tmpImpostorsArray = [];
  62862. this._tmpPositionVector = BABYLON.Vector3.Zero();
  62863. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  62864. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  62865. this.world.worldscale(1);
  62866. this.world.clear();
  62867. //making sure no stats are calculated
  62868. this.world.isNoStat = true;
  62869. }
  62870. OimoJSPlugin.prototype.setGravity = function (gravity) {
  62871. this.world.gravity.copy(gravity);
  62872. };
  62873. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  62874. this.world.timeStep = timeStep;
  62875. };
  62876. OimoJSPlugin.prototype.getTimeStep = function () {
  62877. return this.world.timeStep;
  62878. };
  62879. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  62880. var _this = this;
  62881. impostors.forEach(function (impostor) {
  62882. impostor.beforeStep();
  62883. });
  62884. this.world.step();
  62885. impostors.forEach(function (impostor) {
  62886. impostor.afterStep();
  62887. //update the ordered impostors array
  62888. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  62889. });
  62890. //check for collisions
  62891. var contact = this.world.contacts;
  62892. while (contact !== null) {
  62893. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  62894. contact = contact.next;
  62895. continue;
  62896. }
  62897. //is this body colliding with any other? get the impostor
  62898. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  62899. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  62900. if (!mainImpostor || !collidingImpostor) {
  62901. contact = contact.next;
  62902. continue;
  62903. }
  62904. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  62905. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  62906. contact = contact.next;
  62907. }
  62908. };
  62909. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  62910. var mass = impostor.physicsBody.massInfo.mass;
  62911. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  62912. };
  62913. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  62914. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  62915. this.applyImpulse(impostor, force, contactPoint);
  62916. };
  62917. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  62918. var _this = this;
  62919. //parent-child relationship. Does this impostor has a parent impostor?
  62920. if (impostor.parent) {
  62921. if (impostor.physicsBody) {
  62922. this.removePhysicsBody(impostor);
  62923. //TODO is that needed?
  62924. impostor.forceUpdate();
  62925. }
  62926. return;
  62927. }
  62928. if (impostor.isBodyInitRequired()) {
  62929. var bodyConfig = {
  62930. name: impostor.uniqueId,
  62931. //Oimo must have mass, also for static objects.
  62932. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  62933. size: [],
  62934. type: [],
  62935. pos: [],
  62936. rot: [],
  62937. move: impostor.getParam("mass") !== 0,
  62938. //Supporting older versions of Oimo
  62939. world: this.world
  62940. };
  62941. var impostors = [impostor];
  62942. var addToArray = function (parent) {
  62943. if (!parent.getChildMeshes)
  62944. return;
  62945. parent.getChildMeshes().forEach(function (m) {
  62946. if (m.physicsImpostor) {
  62947. impostors.push(m.physicsImpostor);
  62948. //m.physicsImpostor._init();
  62949. }
  62950. });
  62951. };
  62952. addToArray(impostor.object);
  62953. var checkWithEpsilon_1 = function (value) {
  62954. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  62955. };
  62956. impostors.forEach(function (i) {
  62957. //get the correct bounding box
  62958. var oldQuaternion = i.object.rotationQuaternion;
  62959. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  62960. x: impostor.object.rotationQuaternion.x,
  62961. y: impostor.object.rotationQuaternion.y,
  62962. z: impostor.object.rotationQuaternion.z,
  62963. s: impostor.object.rotationQuaternion.w
  62964. });
  62965. var extendSize = i.getObjectExtendSize();
  62966. if (i === impostor) {
  62967. var center = impostor.getObjectCenter();
  62968. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  62969. //Can also use Array.prototype.push.apply
  62970. bodyConfig.pos.push(center.x);
  62971. bodyConfig.pos.push(center.y);
  62972. bodyConfig.pos.push(center.z);
  62973. //tmp solution
  62974. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  62975. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  62976. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  62977. }
  62978. else {
  62979. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  62980. bodyConfig.pos.push(localPosition.x);
  62981. bodyConfig.pos.push(localPosition.y);
  62982. bodyConfig.pos.push(localPosition.z);
  62983. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  62984. bodyConfig.rot.push(0);
  62985. bodyConfig.rot.push(0);
  62986. bodyConfig.rot.push(0);
  62987. }
  62988. // register mesh
  62989. switch (i.type) {
  62990. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62991. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  62992. case BABYLON.PhysicsImpostor.SphereImpostor:
  62993. var radiusX = extendSize.x;
  62994. var radiusY = extendSize.y;
  62995. var radiusZ = extendSize.z;
  62996. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  62997. bodyConfig.type.push('sphere');
  62998. //due to the way oimo works with compounds, add 3 times
  62999. bodyConfig.size.push(size);
  63000. bodyConfig.size.push(size);
  63001. bodyConfig.size.push(size);
  63002. break;
  63003. case BABYLON.PhysicsImpostor.CylinderImpostor:
  63004. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  63005. var sizeY = checkWithEpsilon_1(extendSize.y);
  63006. bodyConfig.type.push('cylinder');
  63007. bodyConfig.size.push(sizeX);
  63008. bodyConfig.size.push(sizeY);
  63009. //due to the way oimo works with compounds, add one more value.
  63010. bodyConfig.size.push(sizeY);
  63011. break;
  63012. case BABYLON.PhysicsImpostor.PlaneImpostor:
  63013. case BABYLON.PhysicsImpostor.BoxImpostor:
  63014. default:
  63015. var sizeX = checkWithEpsilon_1(extendSize.x);
  63016. var sizeY = checkWithEpsilon_1(extendSize.y);
  63017. var sizeZ = checkWithEpsilon_1(extendSize.z);
  63018. bodyConfig.type.push('box');
  63019. bodyConfig.size.push(sizeX);
  63020. bodyConfig.size.push(sizeY);
  63021. bodyConfig.size.push(sizeZ);
  63022. break;
  63023. }
  63024. //actually not needed, but hey...
  63025. i.object.rotationQuaternion = oldQuaternion;
  63026. });
  63027. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  63028. }
  63029. else {
  63030. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  63031. }
  63032. impostor.setDeltaPosition(this._tmpPositionVector);
  63033. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  63034. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  63035. };
  63036. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  63037. //impostor.physicsBody.dispose();
  63038. //Same as : (older oimo versions)
  63039. this.world.removeRigidBody(impostor.physicsBody);
  63040. };
  63041. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  63042. var mainBody = impostorJoint.mainImpostor.physicsBody;
  63043. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  63044. if (!mainBody || !connectedBody) {
  63045. return;
  63046. }
  63047. var jointData = impostorJoint.joint.jointData;
  63048. var options = jointData.nativeParams || {};
  63049. var type;
  63050. var nativeJointData = {
  63051. body1: mainBody,
  63052. body2: connectedBody,
  63053. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  63054. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  63055. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  63056. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  63057. min: options.min,
  63058. max: options.max,
  63059. collision: options.collision || jointData.collision,
  63060. spring: options.spring,
  63061. //supporting older version of Oimo
  63062. world: this.world
  63063. };
  63064. switch (impostorJoint.joint.type) {
  63065. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  63066. type = "jointBall";
  63067. break;
  63068. case BABYLON.PhysicsJoint.SpringJoint:
  63069. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  63070. var springData = jointData;
  63071. nativeJointData.min = springData.length || nativeJointData.min;
  63072. //Max should also be set, just make sure it is at least min
  63073. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  63074. case BABYLON.PhysicsJoint.DistanceJoint:
  63075. type = "jointDistance";
  63076. nativeJointData.max = jointData.maxDistance;
  63077. break;
  63078. case BABYLON.PhysicsJoint.PrismaticJoint:
  63079. type = "jointPrisme";
  63080. break;
  63081. case BABYLON.PhysicsJoint.SliderJoint:
  63082. type = "jointSlide";
  63083. break;
  63084. case BABYLON.PhysicsJoint.WheelJoint:
  63085. type = "jointWheel";
  63086. break;
  63087. case BABYLON.PhysicsJoint.HingeJoint:
  63088. default:
  63089. type = "jointHinge";
  63090. break;
  63091. }
  63092. nativeJointData.type = type;
  63093. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  63094. };
  63095. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  63096. //Bug in Oimo prevents us from disposing a joint in the playground
  63097. //joint.joint.physicsJoint.dispose();
  63098. //So we will bruteforce it!
  63099. try {
  63100. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  63101. }
  63102. catch (e) {
  63103. BABYLON.Tools.Warn(e);
  63104. }
  63105. };
  63106. OimoJSPlugin.prototype.isSupported = function () {
  63107. return this.BJSOIMO !== undefined;
  63108. };
  63109. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  63110. if (!impostor.physicsBody.sleeping) {
  63111. //TODO check that
  63112. if (impostor.physicsBody.shapes.next) {
  63113. var parentShape = this._getLastShape(impostor.physicsBody);
  63114. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  63115. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  63116. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  63117. }
  63118. else {
  63119. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  63120. }
  63121. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  63122. impostor.object.rotationQuaternion.normalize();
  63123. }
  63124. };
  63125. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  63126. var body = impostor.physicsBody;
  63127. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  63128. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  63129. body.syncShapes();
  63130. body.awake();
  63131. };
  63132. OimoJSPlugin.prototype._getLastShape = function (body) {
  63133. var lastShape = body.shapes;
  63134. while (lastShape.next) {
  63135. lastShape = lastShape.next;
  63136. }
  63137. return lastShape;
  63138. };
  63139. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  63140. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  63141. };
  63142. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  63143. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  63144. };
  63145. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  63146. var v = impostor.physicsBody.linearVelocity;
  63147. if (!v)
  63148. return null;
  63149. return new BABYLON.Vector3(v.x, v.y, v.z);
  63150. };
  63151. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  63152. var v = impostor.physicsBody.angularVelocity;
  63153. if (!v)
  63154. return null;
  63155. return new BABYLON.Vector3(v.x, v.y, v.z);
  63156. };
  63157. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  63158. var staticBody = mass === 0;
  63159. //this will actually set the body's density and not its mass.
  63160. //But this is how oimo treats the mass variable.
  63161. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  63162. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  63163. };
  63164. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  63165. return impostor.physicsBody.shapes.density;
  63166. };
  63167. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  63168. return impostor.physicsBody.shapes.friction;
  63169. };
  63170. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  63171. impostor.physicsBody.shapes.friction = friction;
  63172. };
  63173. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  63174. return impostor.physicsBody.shapes.restitution;
  63175. };
  63176. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  63177. impostor.physicsBody.shapes.restitution = restitution;
  63178. };
  63179. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  63180. impostor.physicsBody.sleep();
  63181. };
  63182. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  63183. impostor.physicsBody.awake();
  63184. };
  63185. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  63186. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  63187. if (minDistance !== void 0) {
  63188. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  63189. }
  63190. };
  63191. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  63192. //TODO separate rotational and transational motors.
  63193. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  63194. if (motor) {
  63195. motor.setMotor(speed, maxForce);
  63196. }
  63197. };
  63198. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  63199. //TODO separate rotational and transational motors.
  63200. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  63201. if (motor) {
  63202. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  63203. }
  63204. };
  63205. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  63206. var body = impostor.physicsBody;
  63207. mesh.position.x = body.position.x;
  63208. mesh.position.y = body.position.y;
  63209. mesh.position.z = body.position.z;
  63210. mesh.rotationQuaternion.x = body.orientation.x;
  63211. mesh.rotationQuaternion.y = body.orientation.y;
  63212. mesh.rotationQuaternion.z = body.orientation.z;
  63213. mesh.rotationQuaternion.w = body.orientation.s;
  63214. };
  63215. OimoJSPlugin.prototype.getRadius = function (impostor) {
  63216. return impostor.physicsBody.shapes.radius;
  63217. };
  63218. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  63219. var shape = impostor.physicsBody.shapes;
  63220. result.x = shape.halfWidth * 2;
  63221. result.y = shape.halfHeight * 2;
  63222. result.z = shape.halfDepth * 2;
  63223. };
  63224. OimoJSPlugin.prototype.dispose = function () {
  63225. this.world.clear();
  63226. };
  63227. return OimoJSPlugin;
  63228. }());
  63229. BABYLON.OimoJSPlugin = OimoJSPlugin;
  63230. })(BABYLON || (BABYLON = {}));
  63231. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  63232. var BABYLON;
  63233. (function (BABYLON) {
  63234. var Internals;
  63235. (function (Internals) {
  63236. /*
  63237. * Based on jsTGALoader - Javascript loader for TGA file
  63238. * By Vincent Thibault
  63239. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  63240. */
  63241. var TGATools = (function () {
  63242. function TGATools() {
  63243. }
  63244. TGATools.GetTGAHeader = function (data) {
  63245. var offset = 0;
  63246. var header = {
  63247. id_length: data[offset++],
  63248. colormap_type: data[offset++],
  63249. image_type: data[offset++],
  63250. colormap_index: data[offset++] | data[offset++] << 8,
  63251. colormap_length: data[offset++] | data[offset++] << 8,
  63252. colormap_size: data[offset++],
  63253. origin: [
  63254. data[offset++] | data[offset++] << 8,
  63255. data[offset++] | data[offset++] << 8
  63256. ],
  63257. width: data[offset++] | data[offset++] << 8,
  63258. height: data[offset++] | data[offset++] << 8,
  63259. pixel_size: data[offset++],
  63260. flags: data[offset++]
  63261. };
  63262. return header;
  63263. };
  63264. TGATools.UploadContent = function (gl, data) {
  63265. // Not enough data to contain header ?
  63266. if (data.length < 19) {
  63267. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  63268. return;
  63269. }
  63270. // Read Header
  63271. var offset = 18;
  63272. var header = TGATools.GetTGAHeader(data);
  63273. // Assume it's a valid Targa file.
  63274. if (header.id_length + offset > data.length) {
  63275. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  63276. return;
  63277. }
  63278. // Skip not needed data
  63279. offset += header.id_length;
  63280. var use_rle = false;
  63281. var use_pal = false;
  63282. var use_rgb = false;
  63283. var use_grey = false;
  63284. // Get some informations.
  63285. switch (header.image_type) {
  63286. case TGATools._TYPE_RLE_INDEXED:
  63287. use_rle = true;
  63288. case TGATools._TYPE_INDEXED:
  63289. use_pal = true;
  63290. break;
  63291. case TGATools._TYPE_RLE_RGB:
  63292. use_rle = true;
  63293. case TGATools._TYPE_RGB:
  63294. use_rgb = true;
  63295. break;
  63296. case TGATools._TYPE_RLE_GREY:
  63297. use_rle = true;
  63298. case TGATools._TYPE_GREY:
  63299. use_grey = true;
  63300. break;
  63301. }
  63302. var pixel_data;
  63303. var numAlphaBits = header.flags & 0xf;
  63304. var pixel_size = header.pixel_size >> 3;
  63305. var pixel_total = header.width * header.height * pixel_size;
  63306. // Read palettes
  63307. var palettes;
  63308. if (use_pal) {
  63309. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  63310. }
  63311. // Read LRE
  63312. if (use_rle) {
  63313. pixel_data = new Uint8Array(pixel_total);
  63314. var c, count, i;
  63315. var localOffset = 0;
  63316. var pixels = new Uint8Array(pixel_size);
  63317. while (offset < pixel_total && localOffset < pixel_total) {
  63318. c = data[offset++];
  63319. count = (c & 0x7f) + 1;
  63320. // RLE pixels
  63321. if (c & 0x80) {
  63322. // Bind pixel tmp array
  63323. for (i = 0; i < pixel_size; ++i) {
  63324. pixels[i] = data[offset++];
  63325. }
  63326. // Copy pixel array
  63327. for (i = 0; i < count; ++i) {
  63328. pixel_data.set(pixels, localOffset + i * pixel_size);
  63329. }
  63330. localOffset += pixel_size * count;
  63331. }
  63332. else {
  63333. count *= pixel_size;
  63334. for (i = 0; i < count; ++i) {
  63335. pixel_data[localOffset + i] = data[offset++];
  63336. }
  63337. localOffset += count;
  63338. }
  63339. }
  63340. }
  63341. else {
  63342. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  63343. }
  63344. // Load to texture
  63345. var x_start, y_start, x_step, y_step, y_end, x_end;
  63346. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  63347. default:
  63348. case TGATools._ORIGIN_UL:
  63349. x_start = 0;
  63350. x_step = 1;
  63351. x_end = header.width;
  63352. y_start = 0;
  63353. y_step = 1;
  63354. y_end = header.height;
  63355. break;
  63356. case TGATools._ORIGIN_BL:
  63357. x_start = 0;
  63358. x_step = 1;
  63359. x_end = header.width;
  63360. y_start = header.height - 1;
  63361. y_step = -1;
  63362. y_end = -1;
  63363. break;
  63364. case TGATools._ORIGIN_UR:
  63365. x_start = header.width - 1;
  63366. x_step = -1;
  63367. x_end = -1;
  63368. y_start = 0;
  63369. y_step = 1;
  63370. y_end = header.height;
  63371. break;
  63372. case TGATools._ORIGIN_BR:
  63373. x_start = header.width - 1;
  63374. x_step = -1;
  63375. x_end = -1;
  63376. y_start = header.height - 1;
  63377. y_step = -1;
  63378. y_end = -1;
  63379. break;
  63380. }
  63381. // Load the specify method
  63382. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  63383. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  63384. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  63385. };
  63386. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63387. var image = pixel_data, colormap = palettes;
  63388. var width = header.width, height = header.height;
  63389. var color, i = 0, x, y;
  63390. var imageData = new Uint8Array(width * height * 4);
  63391. for (y = y_start; y !== y_end; y += y_step) {
  63392. for (x = x_start; x !== x_end; x += x_step, i++) {
  63393. color = image[i];
  63394. imageData[(x + width * y) * 4 + 3] = 255;
  63395. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  63396. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  63397. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  63398. }
  63399. }
  63400. return imageData;
  63401. };
  63402. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63403. var image = pixel_data;
  63404. var width = header.width, height = header.height;
  63405. var color, i = 0, x, y;
  63406. var imageData = new Uint8Array(width * height * 4);
  63407. for (y = y_start; y !== y_end; y += y_step) {
  63408. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  63409. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  63410. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  63411. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  63412. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  63413. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  63414. }
  63415. }
  63416. return imageData;
  63417. };
  63418. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63419. var image = pixel_data;
  63420. var width = header.width, height = header.height;
  63421. var i = 0, x, y;
  63422. var imageData = new Uint8Array(width * height * 4);
  63423. for (y = y_start; y !== y_end; y += y_step) {
  63424. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  63425. imageData[(x + width * y) * 4 + 3] = 255;
  63426. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63427. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  63428. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  63429. }
  63430. }
  63431. return imageData;
  63432. };
  63433. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63434. var image = pixel_data;
  63435. var width = header.width, height = header.height;
  63436. var i = 0, x, y;
  63437. var imageData = new Uint8Array(width * height * 4);
  63438. for (y = y_start; y !== y_end; y += y_step) {
  63439. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  63440. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63441. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  63442. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  63443. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  63444. }
  63445. }
  63446. return imageData;
  63447. };
  63448. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63449. var image = pixel_data;
  63450. var width = header.width, height = header.height;
  63451. var color, i = 0, x, y;
  63452. var imageData = new Uint8Array(width * height * 4);
  63453. for (y = y_start; y !== y_end; y += y_step) {
  63454. for (x = x_start; x !== x_end; x += x_step, i++) {
  63455. color = image[i];
  63456. imageData[(x + width * y) * 4 + 0] = color;
  63457. imageData[(x + width * y) * 4 + 1] = color;
  63458. imageData[(x + width * y) * 4 + 2] = color;
  63459. imageData[(x + width * y) * 4 + 3] = 255;
  63460. }
  63461. }
  63462. return imageData;
  63463. };
  63464. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  63465. var image = pixel_data;
  63466. var width = header.width, height = header.height;
  63467. var i = 0, x, y;
  63468. var imageData = new Uint8Array(width * height * 4);
  63469. for (y = y_start; y !== y_end; y += y_step) {
  63470. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  63471. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  63472. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  63473. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  63474. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  63475. }
  63476. }
  63477. return imageData;
  63478. };
  63479. TGATools._TYPE_NO_DATA = 0;
  63480. TGATools._TYPE_INDEXED = 1;
  63481. TGATools._TYPE_RGB = 2;
  63482. TGATools._TYPE_GREY = 3;
  63483. TGATools._TYPE_RLE_INDEXED = 9;
  63484. TGATools._TYPE_RLE_RGB = 10;
  63485. TGATools._TYPE_RLE_GREY = 11;
  63486. TGATools._ORIGIN_MASK = 0x30;
  63487. TGATools._ORIGIN_SHIFT = 0x04;
  63488. TGATools._ORIGIN_BL = 0x00;
  63489. TGATools._ORIGIN_BR = 0x01;
  63490. TGATools._ORIGIN_UL = 0x02;
  63491. TGATools._ORIGIN_UR = 0x03;
  63492. return TGATools;
  63493. }());
  63494. Internals.TGATools = TGATools;
  63495. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63496. })(BABYLON || (BABYLON = {}));
  63497. //# sourceMappingURL=babylon.tga.js.map
  63498. var BABYLON;
  63499. (function (BABYLON) {
  63500. var Internals;
  63501. (function (Internals) {
  63502. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  63503. // All values and structures referenced from:
  63504. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  63505. var DDS_MAGIC = 0x20534444;
  63506. 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;
  63507. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  63508. 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;
  63509. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  63510. function FourCCToInt32(value) {
  63511. return value.charCodeAt(0) +
  63512. (value.charCodeAt(1) << 8) +
  63513. (value.charCodeAt(2) << 16) +
  63514. (value.charCodeAt(3) << 24);
  63515. }
  63516. function Int32ToFourCC(value) {
  63517. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  63518. }
  63519. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  63520. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  63521. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  63522. var FOURCC_DX10 = FourCCToInt32("DX10");
  63523. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  63524. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  63525. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  63526. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  63527. var headerLengthInt = 31; // The header length in 32 bit ints
  63528. // Offsets into the header array
  63529. var off_magic = 0;
  63530. var off_size = 1;
  63531. var off_flags = 2;
  63532. var off_height = 3;
  63533. var off_width = 4;
  63534. var off_mipmapCount = 7;
  63535. var off_pfFlags = 20;
  63536. var off_pfFourCC = 21;
  63537. var off_RGBbpp = 22;
  63538. var off_RMask = 23;
  63539. var off_GMask = 24;
  63540. var off_BMask = 25;
  63541. var off_AMask = 26;
  63542. var off_caps1 = 27;
  63543. var off_caps2 = 28;
  63544. var off_caps3 = 29;
  63545. var off_caps4 = 30;
  63546. var off_dxgiFormat = 32;
  63547. ;
  63548. var DDSTools = (function () {
  63549. function DDSTools() {
  63550. }
  63551. DDSTools.GetDDSInfo = function (arrayBuffer) {
  63552. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  63553. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  63554. var mipmapCount = 1;
  63555. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  63556. mipmapCount = Math.max(1, header[off_mipmapCount]);
  63557. }
  63558. var fourCC = header[off_pfFourCC];
  63559. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  63560. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63561. switch (fourCC) {
  63562. case FOURCC_D3DFMT_R16G16B16A16F:
  63563. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63564. break;
  63565. case FOURCC_D3DFMT_R32G32B32A32F:
  63566. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63567. break;
  63568. case FOURCC_DX10:
  63569. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  63570. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63571. break;
  63572. }
  63573. }
  63574. return {
  63575. width: header[off_width],
  63576. height: header[off_height],
  63577. mipmapCount: mipmapCount,
  63578. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  63579. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  63580. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  63581. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  63582. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  63583. dxgiFormat: dxgiFormat,
  63584. textureType: textureType
  63585. };
  63586. };
  63587. DDSTools._ToHalfFloat = function (value) {
  63588. if (!DDSTools._FloatView) {
  63589. DDSTools._FloatView = new Float32Array(1);
  63590. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  63591. }
  63592. DDSTools._FloatView[0] = value;
  63593. var x = DDSTools._Int32View[0];
  63594. var bits = (x >> 16) & 0x8000; /* Get the sign */
  63595. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  63596. var e = (x >> 23) & 0xff; /* Using int is faster here */
  63597. /* If zero, or denormal, or exponent underflows too much for a denormal
  63598. * half, return signed zero. */
  63599. if (e < 103) {
  63600. return bits;
  63601. }
  63602. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  63603. if (e > 142) {
  63604. bits |= 0x7c00;
  63605. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  63606. * not Inf, so make sure we set one mantissa bit too. */
  63607. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  63608. return bits;
  63609. }
  63610. /* If exponent underflows but not too much, return a denormal */
  63611. if (e < 113) {
  63612. m |= 0x0800;
  63613. /* Extra rounding may overflow and set mantissa to 0 and exponent
  63614. * to 1, which is OK. */
  63615. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  63616. return bits;
  63617. }
  63618. bits |= ((e - 112) << 10) | (m >> 1);
  63619. bits += m & 1;
  63620. return bits;
  63621. };
  63622. DDSTools._FromHalfFloat = function (value) {
  63623. var s = (value & 0x8000) >> 15;
  63624. var e = (value & 0x7C00) >> 10;
  63625. var f = value & 0x03FF;
  63626. if (e === 0) {
  63627. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  63628. }
  63629. else if (e == 0x1F) {
  63630. return f ? NaN : ((s ? -1 : 1) * Infinity);
  63631. }
  63632. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  63633. };
  63634. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63635. var destArray = new Float32Array(dataLength);
  63636. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63637. var index = 0;
  63638. for (var y = 0; y < height; y++) {
  63639. for (var x = 0; x < width; x++) {
  63640. var srcPos = (x + y * width) * 4;
  63641. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  63642. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  63643. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  63644. if (DDSTools.StoreLODInAlphaChannel) {
  63645. destArray[index + 3] = lod;
  63646. }
  63647. else {
  63648. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  63649. }
  63650. index += 4;
  63651. }
  63652. }
  63653. return destArray;
  63654. };
  63655. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63656. if (DDSTools.StoreLODInAlphaChannel) {
  63657. var destArray = new Uint16Array(dataLength);
  63658. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63659. var index = 0;
  63660. for (var y = 0; y < height; y++) {
  63661. for (var x = 0; x < width; x++) {
  63662. var srcPos = (x + y * width) * 4;
  63663. destArray[index] = srcData[srcPos];
  63664. destArray[index + 1] = srcData[srcPos + 1];
  63665. destArray[index + 2] = srcData[srcPos + 2];
  63666. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  63667. index += 4;
  63668. }
  63669. }
  63670. return destArray;
  63671. }
  63672. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  63673. };
  63674. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63675. if (DDSTools.StoreLODInAlphaChannel) {
  63676. var destArray = new Float32Array(dataLength);
  63677. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63678. var index = 0;
  63679. for (var y = 0; y < height; y++) {
  63680. for (var x = 0; x < width; x++) {
  63681. var srcPos = (x + y * width) * 4;
  63682. destArray[index] = srcData[srcPos];
  63683. destArray[index + 1] = srcData[srcPos + 1];
  63684. destArray[index + 2] = srcData[srcPos + 2];
  63685. destArray[index + 3] = lod;
  63686. index += 4;
  63687. }
  63688. }
  63689. return destArray;
  63690. }
  63691. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  63692. };
  63693. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63694. var destArray = new Uint8Array(dataLength);
  63695. var srcData = new Float32Array(arrayBuffer, dataOffset);
  63696. var index = 0;
  63697. for (var y = 0; y < height; y++) {
  63698. for (var x = 0; x < width; x++) {
  63699. var srcPos = (x + y * width) * 4;
  63700. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  63701. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  63702. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  63703. if (DDSTools.StoreLODInAlphaChannel) {
  63704. destArray[index + 3] = lod;
  63705. }
  63706. else {
  63707. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  63708. }
  63709. index += 4;
  63710. }
  63711. }
  63712. return destArray;
  63713. };
  63714. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  63715. var destArray = new Uint8Array(dataLength);
  63716. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  63717. var index = 0;
  63718. for (var y = 0; y < height; y++) {
  63719. for (var x = 0; x < width; x++) {
  63720. var srcPos = (x + y * width) * 4;
  63721. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  63722. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  63723. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  63724. if (DDSTools.StoreLODInAlphaChannel) {
  63725. destArray[index + 3] = lod;
  63726. }
  63727. else {
  63728. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  63729. }
  63730. index += 4;
  63731. }
  63732. }
  63733. return destArray;
  63734. };
  63735. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63736. var byteArray = new Uint8Array(dataLength);
  63737. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63738. var index = 0;
  63739. for (var y = 0; y < height; y++) {
  63740. for (var x = 0; x < width; x++) {
  63741. var srcPos = (x + y * width) * 4;
  63742. byteArray[index] = srcData[srcPos + 2];
  63743. byteArray[index + 1] = srcData[srcPos + 1];
  63744. byteArray[index + 2] = srcData[srcPos];
  63745. byteArray[index + 3] = srcData[srcPos + 3];
  63746. index += 4;
  63747. }
  63748. }
  63749. return byteArray;
  63750. };
  63751. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63752. var byteArray = new Uint8Array(dataLength);
  63753. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63754. var index = 0;
  63755. for (var y = 0; y < height; y++) {
  63756. for (var x = 0; x < width; x++) {
  63757. var srcPos = (x + y * width) * 3;
  63758. byteArray[index] = srcData[srcPos + 2];
  63759. byteArray[index + 1] = srcData[srcPos + 1];
  63760. byteArray[index + 2] = srcData[srcPos];
  63761. index += 3;
  63762. }
  63763. }
  63764. return byteArray;
  63765. };
  63766. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  63767. var byteArray = new Uint8Array(dataLength);
  63768. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  63769. var index = 0;
  63770. for (var y = 0; y < height; y++) {
  63771. for (var x = 0; x < width; x++) {
  63772. var srcPos = (x + y * width);
  63773. byteArray[index] = srcData[srcPos];
  63774. index++;
  63775. }
  63776. }
  63777. return byteArray;
  63778. };
  63779. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  63780. if (lodIndex === void 0) { lodIndex = -1; }
  63781. var ext = engine.getCaps().s3tc;
  63782. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  63783. if (header[off_magic] != DDS_MAGIC) {
  63784. BABYLON.Tools.Error("Invalid magic number in DDS header");
  63785. return;
  63786. }
  63787. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  63788. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  63789. return;
  63790. }
  63791. if (info.isCompressed && !ext) {
  63792. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  63793. return;
  63794. }
  63795. var bpp = header[off_RGBbpp];
  63796. dataOffset = header[off_size] + 4;
  63797. var computeFormats = false;
  63798. if (info.isFourCC) {
  63799. fourCC = header[off_pfFourCC];
  63800. switch (fourCC) {
  63801. case FOURCC_DXT1:
  63802. blockBytes = 8;
  63803. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  63804. break;
  63805. case FOURCC_DXT3:
  63806. blockBytes = 16;
  63807. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  63808. break;
  63809. case FOURCC_DXT5:
  63810. blockBytes = 16;
  63811. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  63812. break;
  63813. case FOURCC_D3DFMT_R16G16B16A16F:
  63814. computeFormats = true;
  63815. break;
  63816. case FOURCC_D3DFMT_R32G32B32A32F:
  63817. computeFormats = true;
  63818. break;
  63819. case FOURCC_DX10:
  63820. // There is an additionnal header so dataOffset need to be changed
  63821. dataOffset += 5 * 4; // 5 uints
  63822. var supported = false;
  63823. switch (info.dxgiFormat) {
  63824. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  63825. computeFormats = true;
  63826. supported = true;
  63827. break;
  63828. case DXGI_FORMAT_B8G8R8X8_UNORM:
  63829. info.isRGB = true;
  63830. info.isFourCC = false;
  63831. bpp = 32;
  63832. supported = true;
  63833. break;
  63834. }
  63835. if (supported) {
  63836. break;
  63837. }
  63838. default:
  63839. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  63840. return;
  63841. }
  63842. }
  63843. if (computeFormats) {
  63844. format = engine._getWebGLTextureType(info.textureType);
  63845. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63846. }
  63847. mipmapCount = 1;
  63848. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  63849. mipmapCount = Math.max(1, header[off_mipmapCount]);
  63850. }
  63851. for (var face = 0; face < faces; face++) {
  63852. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63853. width = header[off_width];
  63854. height = header[off_height];
  63855. for (mip = 0; mip < mipmapCount; ++mip) {
  63856. if (lodIndex === -1 || lodIndex === mip) {
  63857. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  63858. var i = (lodIndex === -1) ? mip : 0;
  63859. if (!info.isCompressed && info.isFourCC) {
  63860. dataLength = width * height * 4;
  63861. var floatArray;
  63862. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  63863. if (bpp === 128) {
  63864. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63865. }
  63866. else if (bpp === 64) {
  63867. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63868. }
  63869. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63870. format = engine._getWebGLTextureType(info.textureType);
  63871. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63872. }
  63873. else {
  63874. if (bpp === 128) {
  63875. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63876. }
  63877. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  63878. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63879. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63880. format = engine._getWebGLTextureType(info.textureType);
  63881. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  63882. }
  63883. else {
  63884. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  63885. }
  63886. }
  63887. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  63888. }
  63889. else if (info.isRGB) {
  63890. if (bpp === 24) {
  63891. dataLength = width * height * 3;
  63892. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63893. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  63894. }
  63895. else {
  63896. dataLength = width * height * 4;
  63897. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63898. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  63899. }
  63900. }
  63901. else if (info.isLuminance) {
  63902. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  63903. var unpaddedRowSize = width;
  63904. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  63905. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  63906. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  63907. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  63908. }
  63909. else {
  63910. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  63911. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  63912. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  63913. }
  63914. }
  63915. dataOffset += width * height * (bpp / 8);
  63916. width *= 0.5;
  63917. height *= 0.5;
  63918. width = Math.max(1.0, width);
  63919. height = Math.max(1.0, height);
  63920. }
  63921. }
  63922. };
  63923. DDSTools.StoreLODInAlphaChannel = false;
  63924. return DDSTools;
  63925. }());
  63926. Internals.DDSTools = DDSTools;
  63927. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63928. })(BABYLON || (BABYLON = {}));
  63929. //# sourceMappingURL=babylon.dds.js.map
  63930. var BABYLON;
  63931. (function (BABYLON) {
  63932. var Internals;
  63933. (function (Internals) {
  63934. /**
  63935. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  63936. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  63937. */
  63938. var KhronosTextureContainer = (function () {
  63939. /**
  63940. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  63941. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  63942. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  63943. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  63944. */
  63945. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  63946. this.arrayBuffer = arrayBuffer;
  63947. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  63948. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  63949. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  63950. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  63951. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  63952. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  63953. BABYLON.Tools.Error("texture missing KTX identifier");
  63954. return;
  63955. }
  63956. // load the reset of the header in native 32 bit int
  63957. var header = new Int32Array(this.arrayBuffer, 12, 13);
  63958. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  63959. var oppositeEndianess = header[0] === 0x01020304;
  63960. // read all the header elements in order they exist in the file, without modification (sans endainness)
  63961. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  63962. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  63963. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  63964. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  63965. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  63966. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  63967. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  63968. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  63969. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  63970. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  63971. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  63972. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  63973. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  63974. if (this.glType !== 0) {
  63975. BABYLON.Tools.Error("only compressed formats currently supported");
  63976. return;
  63977. }
  63978. else {
  63979. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  63980. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  63981. }
  63982. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  63983. BABYLON.Tools.Error("only 2D textures currently supported");
  63984. return;
  63985. }
  63986. if (this.numberOfArrayElements !== 0) {
  63987. BABYLON.Tools.Error("texture arrays not currently supported");
  63988. return;
  63989. }
  63990. if (this.numberOfFaces !== facesExpected) {
  63991. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  63992. return;
  63993. }
  63994. // we now have a completely validated file, so could use existence of loadType as success
  63995. // would need to make this more elaborate & adjust checks above to support more than one load type
  63996. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  63997. }
  63998. // not as fast hardware based, but will probably never need to use
  63999. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  64000. return ((val & 0xFF) << 24)
  64001. | ((val & 0xFF00) << 8)
  64002. | ((val >> 8) & 0xFF00)
  64003. | ((val >> 24) & 0xFF);
  64004. };
  64005. /**
  64006. * It is assumed that the texture has already been created & is currently bound
  64007. */
  64008. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  64009. switch (this.loadType) {
  64010. case KhronosTextureContainer.COMPRESSED_2D:
  64011. this._upload2DCompressedLevels(gl, loadMipmaps);
  64012. break;
  64013. case KhronosTextureContainer.TEX_2D:
  64014. case KhronosTextureContainer.COMPRESSED_3D:
  64015. case KhronosTextureContainer.TEX_3D:
  64016. }
  64017. };
  64018. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  64019. // initialize width & height for level 1
  64020. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  64021. var width = this.pixelWidth;
  64022. var height = this.pixelHeight;
  64023. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  64024. for (var level = 0; level < mipmapCount; level++) {
  64025. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  64026. for (var face = 0; face < this.numberOfFaces; face++) {
  64027. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  64028. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  64029. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  64030. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  64031. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  64032. }
  64033. width = Math.max(1.0, width * 0.5);
  64034. height = Math.max(1.0, height * 0.5);
  64035. }
  64036. };
  64037. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  64038. // load types
  64039. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  64040. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  64041. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  64042. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  64043. return KhronosTextureContainer;
  64044. }());
  64045. Internals.KhronosTextureContainer = KhronosTextureContainer;
  64046. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64047. })(BABYLON || (BABYLON = {}));
  64048. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  64049. var BABYLON;
  64050. (function (BABYLON) {
  64051. var DynamicFloatArrayElementInfo = (function () {
  64052. function DynamicFloatArrayElementInfo() {
  64053. }
  64054. return DynamicFloatArrayElementInfo;
  64055. }());
  64056. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  64057. /**
  64058. * 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.
  64059. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  64060. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  64061. * 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.
  64062. * 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.
  64063. * 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".
  64064. */
  64065. var DynamicFloatArray = (function () {
  64066. /**
  64067. * Construct an instance of the dynamic float array
  64068. * @param stride size of one element in float (i.e. not bytes!)
  64069. * @param initialElementCount the number of available entries at construction
  64070. */
  64071. function DynamicFloatArray(stride, initialElementCount) {
  64072. this.compareValueOffset = null;
  64073. this.sortingAscending = true;
  64074. this._stride = stride;
  64075. this.buffer = new Float32Array(stride * initialElementCount);
  64076. this._lastUsed = 0;
  64077. this._firstFree = 0;
  64078. this._allEntries = new Array(initialElementCount);
  64079. this._freeEntries = new Array(initialElementCount);
  64080. for (var i = 0; i < initialElementCount; i++) {
  64081. var element = new DynamicFloatArrayElementInfo();
  64082. element.offset = i * stride;
  64083. this._allEntries[i] = element;
  64084. this._freeEntries[initialElementCount - i - 1] = element;
  64085. }
  64086. }
  64087. /**
  64088. * Allocate an element in the array.
  64089. * @return the element info instance that contains the offset into the main buffer of the element's location.
  64090. * Beware, this offset may change when you call pack()
  64091. */
  64092. DynamicFloatArray.prototype.allocElement = function () {
  64093. if (this._freeEntries.length === 0) {
  64094. this._growBuffer();
  64095. }
  64096. var el = this._freeEntries.pop();
  64097. this._lastUsed = Math.max(el.offset, this._lastUsed);
  64098. if (el.offset === this._firstFree) {
  64099. if (this._freeEntries.length > 0) {
  64100. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  64101. }
  64102. else {
  64103. this._firstFree += this._stride;
  64104. }
  64105. }
  64106. return el;
  64107. };
  64108. /**
  64109. * Free the element corresponding to the given element info
  64110. * @param elInfo the element that describe the allocated element
  64111. */
  64112. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  64113. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  64114. this._freeEntries.push(elInfo);
  64115. };
  64116. /**
  64117. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  64118. * 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().
  64119. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  64120. */
  64121. DynamicFloatArray.prototype.pack = function () {
  64122. // no free slot? no need to pack
  64123. if (this._freeEntries.length === 0) {
  64124. return this.buffer;
  64125. }
  64126. // If the buffer is already packed the last used will always be lower than the first free
  64127. // 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.
  64128. if (this._lastUsed < this._firstFree) {
  64129. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  64130. return elementsBuffer_1;
  64131. }
  64132. var s = this._stride;
  64133. // 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
  64134. var lastFree = new DynamicFloatArrayElementInfo();
  64135. lastFree.offset = this.totalElementCount * s;
  64136. this._freeEntries.push(lastFree);
  64137. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  64138. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  64139. var firstFreeSlotOffset = sortedFree[0].offset;
  64140. var freeZoneSize = 1;
  64141. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  64142. var prevOffset = sortedFree[0].offset;
  64143. for (var i = 1; i < sortedFree.length; i++) {
  64144. // 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
  64145. if (firstFreeSlotOffset >= occupiedZoneSize) {
  64146. break;
  64147. }
  64148. var curFree = sortedFree[i];
  64149. var curOffset = curFree.offset;
  64150. // Compute the distance between this offset and the previous
  64151. var distance = curOffset - prevOffset;
  64152. // If the distance is the stride size, they are adjacent, it good, move to the next
  64153. if (distance === s) {
  64154. // Free zone is one element bigger
  64155. ++freeZoneSize;
  64156. // as we're about to iterate to the next, the cur becomes the previous...
  64157. prevOffset = curOffset;
  64158. continue;
  64159. }
  64160. // Distance is bigger, which means there's x element between the previous free and this one
  64161. var usedRange = (distance / s) - 1;
  64162. // Two cases the free zone is smaller than the data to move or bigger
  64163. // Copy what can fit in the free zone
  64164. var curMoveOffset = curOffset - s;
  64165. var copyCount = Math.min(freeZoneSize, usedRange);
  64166. for (var j = 0; j < copyCount; j++) {
  64167. var freeI = firstFreeSlotOffset / s;
  64168. var curI = curMoveOffset / s;
  64169. var moveEl = sortedAll[curI];
  64170. this._moveElement(moveEl, firstFreeSlotOffset);
  64171. var replacedEl = sortedAll[freeI];
  64172. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  64173. replacedEl.offset = curMoveOffset;
  64174. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  64175. sortedAll[freeI] = moveEl;
  64176. sortedAll[curI] = replacedEl;
  64177. curMoveOffset -= s;
  64178. firstFreeSlotOffset += s;
  64179. }
  64180. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  64181. if (freeZoneSize <= usedRange) {
  64182. firstFreeSlotOffset = curMoveOffset + s;
  64183. freeZoneSize = 1 + copyCount;
  64184. }
  64185. else {
  64186. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  64187. }
  64188. // as we're about to iterate to the next, the cur becomes the previous...
  64189. prevOffset = curOffset;
  64190. }
  64191. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  64192. this._lastUsed = firstFreeSlotOffset - s;
  64193. this._firstFree = firstFreeSlotOffset;
  64194. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  64195. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  64196. this._allEntries = sortedAll;
  64197. return elementsBuffer;
  64198. };
  64199. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  64200. for (var i = 0; i < this._stride; i++) {
  64201. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  64202. }
  64203. element.offset = destOffset;
  64204. };
  64205. DynamicFloatArray.prototype._growBuffer = function () {
  64206. // Allocate the new buffer with 50% more entries, copy the content of the current one
  64207. var newElCount = Math.floor(this.totalElementCount * 1.5);
  64208. var newBuffer = new Float32Array(newElCount * this._stride);
  64209. newBuffer.set(this.buffer);
  64210. var curCount = this.totalElementCount;
  64211. var addedCount = newElCount - this.totalElementCount;
  64212. for (var i = 0; i < addedCount; i++) {
  64213. var element = new DynamicFloatArrayElementInfo();
  64214. element.offset = (curCount + i) * this.stride;
  64215. this._allEntries.push(element);
  64216. this._freeEntries[addedCount - i - 1] = element;
  64217. }
  64218. this._firstFree = curCount * this.stride;
  64219. this.buffer = newBuffer;
  64220. };
  64221. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  64222. /**
  64223. * Get the total count of entries that can fit in the current buffer
  64224. * @returns the elements count
  64225. */
  64226. get: function () {
  64227. return this._allEntries.length;
  64228. },
  64229. enumerable: true,
  64230. configurable: true
  64231. });
  64232. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  64233. /**
  64234. * Get the count of free entries that can still be allocated without resizing the buffer
  64235. * @returns the free elements count
  64236. */
  64237. get: function () {
  64238. return this._freeEntries.length;
  64239. },
  64240. enumerable: true,
  64241. configurable: true
  64242. });
  64243. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  64244. /**
  64245. * Get the count of allocated elements
  64246. * @returns the allocated elements count
  64247. */
  64248. get: function () {
  64249. return this._allEntries.length - this._freeEntries.length;
  64250. },
  64251. enumerable: true,
  64252. configurable: true
  64253. });
  64254. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  64255. /**
  64256. * Return the size of one element in float
  64257. * @returns the size in float
  64258. */
  64259. get: function () {
  64260. return this._stride;
  64261. },
  64262. enumerable: true,
  64263. configurable: true
  64264. });
  64265. DynamicFloatArray.prototype.sort = function () {
  64266. var _this = this;
  64267. if (!this.compareValueOffset) {
  64268. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  64269. }
  64270. var count = this.usedElementCount;
  64271. // Do we have to (re)create the sort table?
  64272. if (!this._sortTable || this._sortTable.length < count) {
  64273. // 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...
  64274. var newCount = Math.min(this.totalElementCount, count * 2);
  64275. this._sortTable = new Array(newCount);
  64276. }
  64277. if (!this._sortedTable || this._sortedTable.length !== count) {
  64278. this._sortedTable = new Array(count);
  64279. }
  64280. // Because, you know...
  64281. this.pack();
  64282. //let stride = this.stride;
  64283. //for (let i = 0; i < count; i++) {
  64284. // let si = this._sortTable[i];
  64285. // if (!si) {
  64286. // si = new SortInfo();
  64287. // this._sortTable[i] = si;
  64288. // }
  64289. // si.entry = this._allEntries[i];
  64290. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  64291. // si.swapedOffset = null;
  64292. // this._sortedTable[i] = si;
  64293. //}
  64294. var curOffset = 0;
  64295. var stride = this.stride;
  64296. for (var i = 0; i < count; i++, curOffset += stride) {
  64297. var si = this._sortTable[i];
  64298. if (!si) {
  64299. si = new SortInfo();
  64300. this._sortTable[i] = si;
  64301. }
  64302. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  64303. si.offset = curOffset;
  64304. si.swapedOffset = null;
  64305. this._sortedTable[i] = si;
  64306. }
  64307. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  64308. if (this.sortingAscending) {
  64309. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  64310. }
  64311. else {
  64312. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  64313. }
  64314. var swapElements = function (src, dst) {
  64315. for (var i = 0; i < stride; i++) {
  64316. var tps = _this.buffer[dst + i];
  64317. _this.buffer[dst + i] = _this.buffer[src + i];
  64318. _this.buffer[src + i] = tps;
  64319. }
  64320. };
  64321. // 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:
  64322. // 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),
  64323. // and I still want something with a good algorithm complexity.
  64324. // 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,
  64325. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  64326. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  64327. // 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
  64328. // until we find a SortInfo object without a swapedOffset which means we got the right location
  64329. // 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
  64330. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  64331. for (var i = 0; i < count; i++) {
  64332. // Get the element to move
  64333. var sourceSI = this._sortedTable[i];
  64334. var destSI = this._sortTable[i];
  64335. var sourceOff = sourceSI.offset;
  64336. // If the source changed location, find the new one
  64337. if (sourceSI.swapedOffset) {
  64338. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  64339. var curSI = sourceSI;
  64340. while (curSI.swapedOffset) {
  64341. curSI = this._sortTable[curSI.swapedOffset / stride];
  64342. }
  64343. // Finally get the right location
  64344. sourceOff = curSI.offset;
  64345. }
  64346. // Tag the element being replaced with its new location
  64347. destSI.swapedOffset = sourceOff;
  64348. // Swap elements (only if needed)
  64349. if (sourceOff !== destSI.offset) {
  64350. swapElements(sourceOff, destSI.offset);
  64351. }
  64352. // Update the offset in the corresponding DFAE
  64353. //sourceSI.entry.offset = destSI.entry.offset;
  64354. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  64355. }
  64356. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  64357. return true;
  64358. };
  64359. return DynamicFloatArray;
  64360. }());
  64361. BABYLON.DynamicFloatArray = DynamicFloatArray;
  64362. var SortInfo = (function () {
  64363. function SortInfo() {
  64364. this.compareData = this.offset = this.swapedOffset = null;
  64365. }
  64366. return SortInfo;
  64367. }());
  64368. })(BABYLON || (BABYLON = {}));
  64369. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  64370. var BABYLON;
  64371. (function (BABYLON) {
  64372. var Debug;
  64373. (function (Debug) {
  64374. /**
  64375. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  64376. */
  64377. var SkeletonViewer = (function () {
  64378. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  64379. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  64380. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  64381. this.skeleton = skeleton;
  64382. this.mesh = mesh;
  64383. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  64384. this.renderingGroupId = renderingGroupId;
  64385. this.color = BABYLON.Color3.White();
  64386. this._debugLines = [];
  64387. this._isEnabled = false;
  64388. this._scene = scene;
  64389. this.update();
  64390. this._renderFunction = this.update.bind(this);
  64391. }
  64392. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  64393. get: function () {
  64394. return this._isEnabled;
  64395. },
  64396. set: function (value) {
  64397. if (this._isEnabled === value) {
  64398. return;
  64399. }
  64400. this._isEnabled = value;
  64401. if (value) {
  64402. this._scene.registerBeforeRender(this._renderFunction);
  64403. }
  64404. else {
  64405. this._scene.unregisterBeforeRender(this._renderFunction);
  64406. }
  64407. },
  64408. enumerable: true,
  64409. configurable: true
  64410. });
  64411. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  64412. if (x === void 0) { x = 0; }
  64413. if (y === void 0) { y = 0; }
  64414. if (z === void 0) { z = 0; }
  64415. var tmat = BABYLON.Tmp.Matrix[0];
  64416. var parentBone = bone.getParent();
  64417. tmat.copyFrom(bone.getLocalMatrix());
  64418. if (x !== 0 || y !== 0 || z !== 0) {
  64419. var tmat2 = BABYLON.Tmp.Matrix[1];
  64420. BABYLON.Matrix.IdentityToRef(tmat2);
  64421. tmat2.m[12] = x;
  64422. tmat2.m[13] = y;
  64423. tmat2.m[14] = z;
  64424. tmat2.multiplyToRef(tmat, tmat);
  64425. }
  64426. if (parentBone) {
  64427. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  64428. }
  64429. tmat.multiplyToRef(meshMat, tmat);
  64430. position.x = tmat.m[12];
  64431. position.y = tmat.m[13];
  64432. position.z = tmat.m[14];
  64433. };
  64434. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64435. var len = bones.length;
  64436. var meshPos = this.mesh.position;
  64437. for (var i = 0; i < len; i++) {
  64438. var bone = bones[i];
  64439. var points = this._debugLines[i];
  64440. if (!points) {
  64441. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64442. this._debugLines[i] = points;
  64443. }
  64444. this._getBonePosition(points[0], bone, meshMat);
  64445. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64446. points[0].subtractInPlace(meshPos);
  64447. points[1].subtractInPlace(meshPos);
  64448. }
  64449. };
  64450. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64451. var len = bones.length;
  64452. var boneNum = 0;
  64453. var meshPos = this.mesh.position;
  64454. for (var i = len - 1; i >= 0; i--) {
  64455. var childBone = bones[i];
  64456. var parentBone = childBone.getParent();
  64457. if (!parentBone) {
  64458. continue;
  64459. }
  64460. var points = this._debugLines[boneNum];
  64461. if (!points) {
  64462. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64463. this._debugLines[boneNum] = points;
  64464. }
  64465. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64466. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64467. points[0].subtractInPlace(meshPos);
  64468. points[1].subtractInPlace(meshPos);
  64469. boneNum++;
  64470. }
  64471. };
  64472. SkeletonViewer.prototype.update = function () {
  64473. if (this.autoUpdateBonesMatrices) {
  64474. this.skeleton.computeAbsoluteTransforms();
  64475. }
  64476. if (this.skeleton.bones[0].length === undefined) {
  64477. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64478. }
  64479. else {
  64480. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64481. }
  64482. if (!this._debugMesh) {
  64483. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  64484. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64485. }
  64486. else {
  64487. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64488. }
  64489. this._debugMesh.position.copyFrom(this.mesh.position);
  64490. this._debugMesh.color = this.color;
  64491. };
  64492. SkeletonViewer.prototype.dispose = function () {
  64493. if (this._debugMesh) {
  64494. this.isEnabled = false;
  64495. this._debugMesh.dispose();
  64496. this._debugMesh = null;
  64497. }
  64498. };
  64499. return SkeletonViewer;
  64500. }());
  64501. Debug.SkeletonViewer = SkeletonViewer;
  64502. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64503. })(BABYLON || (BABYLON = {}));
  64504. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64505. var BABYLON;
  64506. (function (BABYLON) {
  64507. var Debug;
  64508. (function (Debug) {
  64509. var AxesViewer = (function () {
  64510. function AxesViewer(scene, scaleLines) {
  64511. if (scaleLines === void 0) { scaleLines = 1; }
  64512. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64513. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64514. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64515. this.scaleLines = 1;
  64516. this.scaleLines = scaleLines;
  64517. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64518. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64519. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64520. this._xmesh.renderingGroupId = 2;
  64521. this._ymesh.renderingGroupId = 2;
  64522. this._zmesh.renderingGroupId = 2;
  64523. this._xmesh.material.checkReadyOnlyOnce = true;
  64524. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64525. this._ymesh.material.checkReadyOnlyOnce = true;
  64526. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64527. this._zmesh.material.checkReadyOnlyOnce = true;
  64528. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64529. this.scene = scene;
  64530. }
  64531. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64532. var scaleLines = this.scaleLines;
  64533. this._xmesh.position.copyFrom(position);
  64534. this._ymesh.position.copyFrom(position);
  64535. this._zmesh.position.copyFrom(position);
  64536. var point2 = this._xline[1];
  64537. point2.x = xaxis.x * scaleLines;
  64538. point2.y = xaxis.y * scaleLines;
  64539. point2.z = xaxis.z * scaleLines;
  64540. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  64541. point2 = this._yline[1];
  64542. point2.x = yaxis.x * scaleLines;
  64543. point2.y = yaxis.y * scaleLines;
  64544. point2.z = yaxis.z * scaleLines;
  64545. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  64546. point2 = this._zline[1];
  64547. point2.x = zaxis.x * scaleLines;
  64548. point2.y = zaxis.y * scaleLines;
  64549. point2.z = zaxis.z * scaleLines;
  64550. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  64551. };
  64552. AxesViewer.prototype.dispose = function () {
  64553. if (this._xmesh) {
  64554. this._xmesh.dispose();
  64555. this._ymesh.dispose();
  64556. this._zmesh.dispose();
  64557. this._xmesh = null;
  64558. this._ymesh = null;
  64559. this._zmesh = null;
  64560. this._xline = null;
  64561. this._yline = null;
  64562. this._zline = null;
  64563. this.scene = null;
  64564. }
  64565. };
  64566. return AxesViewer;
  64567. }());
  64568. Debug.AxesViewer = AxesViewer;
  64569. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64570. })(BABYLON || (BABYLON = {}));
  64571. //# sourceMappingURL=babylon.axesViewer.js.map
  64572. var BABYLON;
  64573. (function (BABYLON) {
  64574. var Debug;
  64575. (function (Debug) {
  64576. var BoneAxesViewer = (function (_super) {
  64577. __extends(BoneAxesViewer, _super);
  64578. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64579. if (scaleLines === void 0) { scaleLines = 1; }
  64580. var _this = _super.call(this, scene, scaleLines) || this;
  64581. _this.pos = BABYLON.Vector3.Zero();
  64582. _this.xaxis = BABYLON.Vector3.Zero();
  64583. _this.yaxis = BABYLON.Vector3.Zero();
  64584. _this.zaxis = BABYLON.Vector3.Zero();
  64585. _this.mesh = mesh;
  64586. _this.bone = bone;
  64587. return _this;
  64588. }
  64589. BoneAxesViewer.prototype.update = function () {
  64590. var bone = this.bone;
  64591. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64592. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64593. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64594. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64595. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64596. };
  64597. BoneAxesViewer.prototype.dispose = function () {
  64598. if (this.pos) {
  64599. this.pos = null;
  64600. this.xaxis = null;
  64601. this.yaxis = null;
  64602. this.zaxis = null;
  64603. this.mesh = null;
  64604. this.bone = null;
  64605. _super.prototype.dispose.call(this);
  64606. }
  64607. };
  64608. return BoneAxesViewer;
  64609. }(Debug.AxesViewer));
  64610. Debug.BoneAxesViewer = BoneAxesViewer;
  64611. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64612. })(BABYLON || (BABYLON = {}));
  64613. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64614. var BABYLON;
  64615. (function (BABYLON) {
  64616. var RayHelper = (function () {
  64617. function RayHelper(ray) {
  64618. this.ray = ray;
  64619. }
  64620. RayHelper.CreateAndShow = function (ray, scene, color) {
  64621. var helper = new RayHelper(ray);
  64622. helper.show(scene, color);
  64623. return helper;
  64624. };
  64625. RayHelper.prototype.show = function (scene, color) {
  64626. if (!this._renderFunction) {
  64627. var ray = this.ray;
  64628. this._renderFunction = this._render.bind(this);
  64629. this._scene = scene;
  64630. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64631. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64632. this._scene.registerBeforeRender(this._renderFunction);
  64633. }
  64634. if (color) {
  64635. this._renderLine.color.copyFrom(color);
  64636. }
  64637. };
  64638. RayHelper.prototype.hide = function () {
  64639. if (this._renderFunction) {
  64640. this._scene.unregisterBeforeRender(this._renderFunction);
  64641. this._scene = null;
  64642. this._renderFunction = null;
  64643. this._renderLine.dispose();
  64644. this._renderLine = null;
  64645. this._renderPoints = null;
  64646. }
  64647. };
  64648. RayHelper.prototype._render = function () {
  64649. var ray = this.ray;
  64650. var point = this._renderPoints[1];
  64651. var len = Math.min(ray.length, 1000000);
  64652. point.copyFrom(ray.direction);
  64653. point.scaleInPlace(len);
  64654. point.addInPlace(ray.origin);
  64655. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64656. };
  64657. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64658. this._attachedToMesh = mesh;
  64659. var ray = this.ray;
  64660. if (!ray.direction) {
  64661. ray.direction = BABYLON.Vector3.Zero();
  64662. }
  64663. if (!ray.origin) {
  64664. ray.origin = BABYLON.Vector3.Zero();
  64665. }
  64666. if (length) {
  64667. ray.length = length;
  64668. }
  64669. if (!meshSpaceOrigin) {
  64670. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64671. }
  64672. if (!meshSpaceDirection) {
  64673. // -1 so that this will work with Mesh.lookAt
  64674. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64675. }
  64676. if (!this._meshSpaceDirection) {
  64677. this._meshSpaceDirection = meshSpaceDirection.clone();
  64678. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64679. }
  64680. else {
  64681. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64682. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64683. }
  64684. if (!this._updateToMeshFunction) {
  64685. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64686. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64687. }
  64688. this._updateToMesh();
  64689. };
  64690. RayHelper.prototype.detachFromMesh = function () {
  64691. if (this._attachedToMesh) {
  64692. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64693. this._attachedToMesh = null;
  64694. this._updateToMeshFunction = null;
  64695. }
  64696. };
  64697. RayHelper.prototype._updateToMesh = function () {
  64698. var ray = this.ray;
  64699. if (this._attachedToMesh._isDisposed) {
  64700. this.detachFromMesh();
  64701. return;
  64702. }
  64703. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64704. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64705. };
  64706. RayHelper.prototype.dispose = function () {
  64707. this.hide();
  64708. this.detachFromMesh();
  64709. this.ray = null;
  64710. };
  64711. return RayHelper;
  64712. }());
  64713. BABYLON.RayHelper = RayHelper;
  64714. })(BABYLON || (BABYLON = {}));
  64715. //# sourceMappingURL=babylon.rayHelper.js.map
  64716. var BABYLON;
  64717. (function (BABYLON) {
  64718. var DebugLayer = (function () {
  64719. function DebugLayer(scene) {
  64720. this._scene = scene;
  64721. }
  64722. /** Creates the inspector window. */
  64723. DebugLayer.prototype._createInspector = function (config) {
  64724. if (config === void 0) { config = {}; }
  64725. var popup = config.popup || false;
  64726. var initialTab = config.initialTab || 0;
  64727. var parentElement = config.parentElement || null;
  64728. if (!this._inspector) {
  64729. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64730. } // else nothing to do,; instance is already existing
  64731. };
  64732. DebugLayer.prototype.isVisible = function () {
  64733. if (!this._inspector) {
  64734. return false;
  64735. }
  64736. return true;
  64737. };
  64738. DebugLayer.prototype.hide = function () {
  64739. if (this._inspector) {
  64740. try {
  64741. this._inspector.dispose();
  64742. }
  64743. catch (e) {
  64744. // If the inspector has been removed directly from the inspector tool
  64745. }
  64746. this._inspector = null;
  64747. }
  64748. };
  64749. DebugLayer.prototype.show = function (config) {
  64750. if (config === void 0) { config = {}; }
  64751. if (typeof INSPECTOR == 'undefined') {
  64752. // Load inspector and add it to the DOM
  64753. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64754. }
  64755. else {
  64756. // Otherwise creates the inspector
  64757. this._createInspector(config);
  64758. }
  64759. };
  64760. // Get protocol used - http or https
  64761. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64762. return DebugLayer;
  64763. }());
  64764. BABYLON.DebugLayer = DebugLayer;
  64765. })(BABYLON || (BABYLON = {}));
  64766. //# sourceMappingURL=babylon.debugLayer.js.map
  64767. var BABYLON;
  64768. (function (BABYLON) {
  64769. var Debug;
  64770. (function (Debug) {
  64771. var PhysicsViewer = (function () {
  64772. function PhysicsViewer(scene) {
  64773. this._impostors = [];
  64774. this._meshes = [];
  64775. this._numMeshes = 0;
  64776. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64777. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  64778. }
  64779. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64780. var plugin = this._physicsEnginePlugin;
  64781. for (var i = 0; i < this._numMeshes; i++) {
  64782. if (this._impostors[i].isDisposed) {
  64783. this.hideImpostor(this._impostors[i--]);
  64784. }
  64785. else {
  64786. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  64787. }
  64788. }
  64789. };
  64790. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64791. for (var i = 0; i < this._numMeshes; i++) {
  64792. if (this._impostors[i] == impostor) {
  64793. return;
  64794. }
  64795. }
  64796. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64797. if (debugMesh) {
  64798. this._impostors[this._numMeshes] = impostor;
  64799. this._meshes[this._numMeshes] = debugMesh;
  64800. if (this._numMeshes === 0) {
  64801. this._renderFunction = this._updateDebugMeshes.bind(this);
  64802. this._scene.registerBeforeRender(this._renderFunction);
  64803. }
  64804. this._numMeshes++;
  64805. }
  64806. };
  64807. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64808. var removed = false;
  64809. for (var i = 0; i < this._numMeshes; i++) {
  64810. if (this._impostors[i] == impostor) {
  64811. this._scene.removeMesh(this._meshes[i]);
  64812. this._meshes[i].dispose();
  64813. this._numMeshes--;
  64814. if (this._numMeshes > 0) {
  64815. this._meshes[i] = this._meshes[this._numMeshes];
  64816. this._impostors[i] = this._impostors[this._numMeshes];
  64817. this._meshes[this._numMeshes] = null;
  64818. this._impostors[this._numMeshes] = null;
  64819. }
  64820. else {
  64821. this._meshes[0] = null;
  64822. this._impostors[0] = null;
  64823. }
  64824. removed = true;
  64825. break;
  64826. }
  64827. }
  64828. if (removed && this._numMeshes === 0) {
  64829. this._scene.unregisterBeforeRender(this._renderFunction);
  64830. }
  64831. };
  64832. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64833. if (!this._debugMaterial) {
  64834. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64835. this._debugMaterial.wireframe = true;
  64836. }
  64837. return this._debugMaterial;
  64838. };
  64839. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64840. if (!this._debugBoxMesh) {
  64841. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64842. this._debugBoxMesh.renderingGroupId = 1;
  64843. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64844. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64845. scene.removeMesh(this._debugBoxMesh);
  64846. }
  64847. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64848. };
  64849. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64850. if (!this._debugSphereMesh) {
  64851. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64852. this._debugSphereMesh.renderingGroupId = 1;
  64853. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64854. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64855. scene.removeMesh(this._debugSphereMesh);
  64856. }
  64857. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64858. };
  64859. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64860. var body = impostor.physicsBody;
  64861. var shape = body.shapes[0];
  64862. var mesh;
  64863. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64864. mesh = this._getDebugBoxMesh(scene);
  64865. impostor.getBoxSizeToRef(mesh.scaling);
  64866. }
  64867. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64868. mesh = this._getDebugSphereMesh(scene);
  64869. var radius = impostor.getRadius();
  64870. mesh.scaling.x = radius * 2;
  64871. mesh.scaling.y = radius * 2;
  64872. mesh.scaling.z = radius * 2;
  64873. }
  64874. return mesh;
  64875. };
  64876. PhysicsViewer.prototype.dispose = function () {
  64877. for (var i = 0; i < this._numMeshes; i++) {
  64878. this.hideImpostor(this._impostors[i]);
  64879. }
  64880. if (this._debugBoxMesh) {
  64881. this._debugBoxMesh.dispose();
  64882. }
  64883. if (this._debugSphereMesh) {
  64884. this._debugSphereMesh.dispose();
  64885. }
  64886. if (this._debugMaterial) {
  64887. this._debugMaterial.dispose();
  64888. }
  64889. this._impostors.length = 0;
  64890. this._scene = null;
  64891. this._physicsEnginePlugin = null;
  64892. };
  64893. return PhysicsViewer;
  64894. }());
  64895. Debug.PhysicsViewer = PhysicsViewer;
  64896. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64897. })(BABYLON || (BABYLON = {}));
  64898. //# sourceMappingURL=babylon.physicsViewer.js.map
  64899. var BABYLON;
  64900. (function (BABYLON) {
  64901. var BoundingBoxRenderer = (function () {
  64902. function BoundingBoxRenderer(scene) {
  64903. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64904. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64905. this.showBackLines = true;
  64906. this.renderList = new BABYLON.SmartArray(32);
  64907. this._vertexBuffers = {};
  64908. this._scene = scene;
  64909. }
  64910. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64911. if (this._colorShader) {
  64912. return;
  64913. }
  64914. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  64915. attributes: [BABYLON.VertexBuffer.PositionKind],
  64916. uniforms: ["world", "viewProjection", "color"]
  64917. });
  64918. var engine = this._scene.getEngine();
  64919. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64920. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64921. this._createIndexBuffer();
  64922. };
  64923. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64924. var engine = this._scene.getEngine();
  64925. 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]);
  64926. };
  64927. BoundingBoxRenderer.prototype._rebuild = function () {
  64928. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  64929. this._createIndexBuffer();
  64930. };
  64931. BoundingBoxRenderer.prototype.reset = function () {
  64932. this.renderList.reset();
  64933. };
  64934. BoundingBoxRenderer.prototype.render = function () {
  64935. if (this.renderList.length === 0) {
  64936. return;
  64937. }
  64938. this._prepareRessources();
  64939. if (!this._colorShader.isReady()) {
  64940. return;
  64941. }
  64942. var engine = this._scene.getEngine();
  64943. engine.setDepthWrite(false);
  64944. this._colorShader._preBind();
  64945. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64946. var boundingBox = this.renderList.data[boundingBoxIndex];
  64947. var min = boundingBox.minimum;
  64948. var max = boundingBox.maximum;
  64949. var diff = max.subtract(min);
  64950. var median = min.add(diff.scale(0.5));
  64951. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64952. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64953. .multiply(boundingBox.getWorldMatrix());
  64954. // VBOs
  64955. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64956. if (this.showBackLines) {
  64957. // Back
  64958. engine.setDepthFunctionToGreaterOrEqual();
  64959. this._scene.resetCachedMaterial();
  64960. this._colorShader.setColor4("color", this.backColor.toColor4());
  64961. this._colorShader.bind(worldMatrix);
  64962. // Draw order
  64963. engine.draw(false, 0, 24);
  64964. }
  64965. // Front
  64966. engine.setDepthFunctionToLess();
  64967. this._scene.resetCachedMaterial();
  64968. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64969. this._colorShader.bind(worldMatrix);
  64970. // Draw order
  64971. engine.draw(false, 0, 24);
  64972. }
  64973. this._colorShader.unbind();
  64974. engine.setDepthFunctionToLessOrEqual();
  64975. engine.setDepthWrite(true);
  64976. };
  64977. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64978. this._prepareRessources();
  64979. if (!this._colorShader.isReady()) {
  64980. return;
  64981. }
  64982. var engine = this._scene.getEngine();
  64983. engine.setDepthWrite(false);
  64984. engine.setColorWrite(false);
  64985. this._colorShader._preBind();
  64986. var boundingBox = mesh._boundingInfo.boundingBox;
  64987. var min = boundingBox.minimum;
  64988. var max = boundingBox.maximum;
  64989. var diff = max.subtract(min);
  64990. var median = min.add(diff.scale(0.5));
  64991. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64992. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64993. .multiply(boundingBox.getWorldMatrix());
  64994. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64995. engine.setDepthFunctionToLess();
  64996. this._scene.resetCachedMaterial();
  64997. this._colorShader.bind(worldMatrix);
  64998. engine.draw(false, 0, 24);
  64999. this._colorShader.unbind();
  65000. engine.setDepthFunctionToLessOrEqual();
  65001. engine.setDepthWrite(true);
  65002. engine.setColorWrite(true);
  65003. };
  65004. BoundingBoxRenderer.prototype.dispose = function () {
  65005. if (!this._colorShader) {
  65006. return;
  65007. }
  65008. this.renderList.dispose();
  65009. this._colorShader.dispose();
  65010. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65011. if (buffer) {
  65012. buffer.dispose();
  65013. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65014. }
  65015. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65016. };
  65017. return BoundingBoxRenderer;
  65018. }());
  65019. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  65020. })(BABYLON || (BABYLON = {}));
  65021. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  65022. var BABYLON;
  65023. (function (BABYLON) {
  65024. var MorphTarget = (function () {
  65025. function MorphTarget(name, influence) {
  65026. if (influence === void 0) { influence = 0; }
  65027. this.name = name;
  65028. this.animations = new Array();
  65029. this.onInfluenceChanged = new BABYLON.Observable();
  65030. this.influence = influence;
  65031. }
  65032. Object.defineProperty(MorphTarget.prototype, "influence", {
  65033. get: function () {
  65034. return this._influence;
  65035. },
  65036. set: function (influence) {
  65037. if (this._influence === influence) {
  65038. return;
  65039. }
  65040. var previous = this._influence;
  65041. this._influence = influence;
  65042. if (this.onInfluenceChanged.hasObservers) {
  65043. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  65044. }
  65045. },
  65046. enumerable: true,
  65047. configurable: true
  65048. });
  65049. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  65050. get: function () {
  65051. return this._normals !== undefined;
  65052. },
  65053. enumerable: true,
  65054. configurable: true
  65055. });
  65056. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  65057. get: function () {
  65058. return this._tangents !== undefined;
  65059. },
  65060. enumerable: true,
  65061. configurable: true
  65062. });
  65063. MorphTarget.prototype.setPositions = function (data) {
  65064. this._positions = new Float32Array(data);
  65065. };
  65066. MorphTarget.prototype.getPositions = function () {
  65067. return this._positions;
  65068. };
  65069. MorphTarget.prototype.setNormals = function (data) {
  65070. this._normals = new Float32Array(data);
  65071. };
  65072. MorphTarget.prototype.getNormals = function () {
  65073. return this._normals;
  65074. };
  65075. MorphTarget.prototype.setTangents = function (data) {
  65076. this._tangents = new Float32Array(data);
  65077. };
  65078. MorphTarget.prototype.getTangents = function () {
  65079. return this._tangents;
  65080. };
  65081. /**
  65082. * Serializes the current target into a Serialization object.
  65083. * Returns the serialized object.
  65084. */
  65085. MorphTarget.prototype.serialize = function () {
  65086. var serializationObject = {};
  65087. serializationObject.name = this.name;
  65088. serializationObject.influence = this.influence;
  65089. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  65090. if (this.hasNormals) {
  65091. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  65092. }
  65093. if (this.hasTangents) {
  65094. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  65095. }
  65096. // Animations
  65097. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  65098. return serializationObject;
  65099. };
  65100. // Statics
  65101. MorphTarget.Parse = function (serializationObject) {
  65102. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  65103. result.setPositions(serializationObject.positions);
  65104. if (serializationObject.normals) {
  65105. result.setNormals(serializationObject.normals);
  65106. }
  65107. if (serializationObject.tangents) {
  65108. result.setTangents(serializationObject.tangents);
  65109. }
  65110. // Animations
  65111. if (serializationObject.animations) {
  65112. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  65113. var parsedAnimation = serializationObject.animations[animationIndex];
  65114. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  65115. }
  65116. }
  65117. return result;
  65118. };
  65119. MorphTarget.FromMesh = function (mesh, name, influence) {
  65120. if (!name) {
  65121. name = mesh.name;
  65122. }
  65123. var result = new MorphTarget(name, influence);
  65124. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  65125. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65126. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  65127. }
  65128. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  65129. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  65130. }
  65131. return result;
  65132. };
  65133. return MorphTarget;
  65134. }());
  65135. BABYLON.MorphTarget = MorphTarget;
  65136. })(BABYLON || (BABYLON = {}));
  65137. //# sourceMappingURL=babylon.morphTarget.js.map
  65138. var BABYLON;
  65139. (function (BABYLON) {
  65140. var MorphTargetManager = (function () {
  65141. function MorphTargetManager(scene) {
  65142. this._targets = new Array();
  65143. this._targetObservable = new Array();
  65144. this._activeTargets = new BABYLON.SmartArray(16);
  65145. this._supportsNormals = false;
  65146. this._supportsTangents = false;
  65147. this._vertexCount = 0;
  65148. this._uniqueId = 0;
  65149. this._tempInfluences = new Array();
  65150. if (!scene) {
  65151. scene = BABYLON.Engine.LastCreatedScene;
  65152. }
  65153. this._scene = scene;
  65154. this._scene.morphTargetManagers.push(this);
  65155. this._uniqueId = scene.getUniqueId();
  65156. }
  65157. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  65158. get: function () {
  65159. return this._uniqueId;
  65160. },
  65161. enumerable: true,
  65162. configurable: true
  65163. });
  65164. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  65165. get: function () {
  65166. return this._vertexCount;
  65167. },
  65168. enumerable: true,
  65169. configurable: true
  65170. });
  65171. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  65172. get: function () {
  65173. return this._supportsNormals;
  65174. },
  65175. enumerable: true,
  65176. configurable: true
  65177. });
  65178. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  65179. get: function () {
  65180. return this._supportsTangents;
  65181. },
  65182. enumerable: true,
  65183. configurable: true
  65184. });
  65185. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  65186. get: function () {
  65187. return this._targets.length;
  65188. },
  65189. enumerable: true,
  65190. configurable: true
  65191. });
  65192. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  65193. get: function () {
  65194. return this._activeTargets.length;
  65195. },
  65196. enumerable: true,
  65197. configurable: true
  65198. });
  65199. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  65200. get: function () {
  65201. return this._influences;
  65202. },
  65203. enumerable: true,
  65204. configurable: true
  65205. });
  65206. MorphTargetManager.prototype.getActiveTarget = function (index) {
  65207. return this._activeTargets.data[index];
  65208. };
  65209. MorphTargetManager.prototype.getTarget = function (index) {
  65210. return this._targets[index];
  65211. };
  65212. MorphTargetManager.prototype.addTarget = function (target) {
  65213. var _this = this;
  65214. if (this._vertexCount) {
  65215. if (this._vertexCount !== target.getPositions().length / 3) {
  65216. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  65217. return;
  65218. }
  65219. }
  65220. this._targets.push(target);
  65221. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  65222. _this._syncActiveTargets(needUpdate);
  65223. }));
  65224. this._syncActiveTargets(true);
  65225. };
  65226. MorphTargetManager.prototype.removeTarget = function (target) {
  65227. var index = this._targets.indexOf(target);
  65228. if (index >= 0) {
  65229. this._targets.splice(index, 1);
  65230. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  65231. this._vertexCount = 0;
  65232. this._syncActiveTargets(true);
  65233. }
  65234. };
  65235. /**
  65236. * Serializes the current manager into a Serialization object.
  65237. * Returns the serialized object.
  65238. */
  65239. MorphTargetManager.prototype.serialize = function () {
  65240. var serializationObject = {};
  65241. serializationObject.id = this.uniqueId;
  65242. serializationObject.targets = [];
  65243. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  65244. var target = _a[_i];
  65245. serializationObject.targets.push(target.serialize());
  65246. }
  65247. return serializationObject;
  65248. };
  65249. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  65250. this._syncActiveTargets(needUpdate);
  65251. };
  65252. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  65253. var influenceCount = 0;
  65254. this._activeTargets.reset();
  65255. this._supportsNormals = true;
  65256. this._supportsTangents = true;
  65257. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  65258. var target = _a[_i];
  65259. if (target.influence > 0) {
  65260. this._activeTargets.push(target);
  65261. this._tempInfluences[influenceCount++] = target.influence;
  65262. this._supportsNormals = this._supportsNormals && target.hasNormals;
  65263. this._supportsTangents = this._supportsTangents && target.hasTangents;
  65264. if (this._vertexCount === 0) {
  65265. this._vertexCount = target.getPositions().length / 3;
  65266. }
  65267. }
  65268. }
  65269. if (!this._influences || this._influences.length !== influenceCount) {
  65270. this._influences = new Float32Array(influenceCount);
  65271. }
  65272. for (var index = 0; index < influenceCount; index++) {
  65273. this._influences[index] = this._tempInfluences[index];
  65274. }
  65275. if (needUpdate) {
  65276. // Flag meshes as dirty to resync with the active targets
  65277. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  65278. var mesh = _c[_b];
  65279. if (mesh.morphTargetManager === this) {
  65280. mesh._syncGeometryWithMorphTargetManager();
  65281. }
  65282. }
  65283. }
  65284. };
  65285. // Statics
  65286. MorphTargetManager.Parse = function (serializationObject, scene) {
  65287. var result = new MorphTargetManager(scene);
  65288. result._uniqueId = serializationObject.id;
  65289. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  65290. var targetData = _a[_i];
  65291. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  65292. }
  65293. return result;
  65294. };
  65295. return MorphTargetManager;
  65296. }());
  65297. BABYLON.MorphTargetManager = MorphTargetManager;
  65298. })(BABYLON || (BABYLON = {}));
  65299. //# sourceMappingURL=babylon.morphTargetManager.js.map
  65300. var BABYLON;
  65301. (function (BABYLON) {
  65302. /**
  65303. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  65304. * It can help converting any input color in a desired output one. This can then be used to create effects
  65305. * from sepia, black and white to sixties or futuristic rendering...
  65306. *
  65307. * The only supported format is currently 3dl.
  65308. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  65309. */
  65310. var ColorGradingTexture = (function (_super) {
  65311. __extends(ColorGradingTexture, _super);
  65312. /**
  65313. * Instantiates a ColorGradingTexture from the following parameters.
  65314. *
  65315. * @param url The location of the color gradind data (currently only supporting 3dl)
  65316. * @param scene The scene the texture will be used in
  65317. */
  65318. function ColorGradingTexture(url, scene) {
  65319. var _this = _super.call(this, scene) || this;
  65320. if (!url) {
  65321. return _this;
  65322. }
  65323. _this._textureMatrix = BABYLON.Matrix.Identity();
  65324. _this.name = url;
  65325. _this.url = url;
  65326. _this.hasAlpha = false;
  65327. _this.isCube = false;
  65328. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65329. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65330. _this.anisotropicFilteringLevel = 1;
  65331. _this._texture = _this._getFromCache(url, true);
  65332. if (!_this._texture) {
  65333. if (!scene.useDelayedTextureLoading) {
  65334. _this.loadTexture();
  65335. }
  65336. else {
  65337. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65338. }
  65339. }
  65340. return _this;
  65341. }
  65342. /**
  65343. * Returns the texture matrix used in most of the material.
  65344. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  65345. */
  65346. ColorGradingTexture.prototype.getTextureMatrix = function () {
  65347. return this._textureMatrix;
  65348. };
  65349. /**
  65350. * Occurs when the file being loaded is a .3dl LUT file.
  65351. */
  65352. ColorGradingTexture.prototype.load3dlTexture = function () {
  65353. var _this = this;
  65354. var mipLevels = 0;
  65355. var floatArrayView = null;
  65356. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65357. this._texture = texture;
  65358. var callback = function (text) {
  65359. var data;
  65360. var tempData;
  65361. var line;
  65362. var lines = text.split('\n');
  65363. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  65364. var maxColor = 0;
  65365. for (var i = 0; i < lines.length; i++) {
  65366. line = lines[i];
  65367. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  65368. continue;
  65369. if (line.indexOf('#') === 0)
  65370. continue;
  65371. var words = line.split(" ");
  65372. if (size === 0) {
  65373. // Number of space + one
  65374. size = words.length;
  65375. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  65376. tempData = new Float32Array(size * size * size * 4);
  65377. continue;
  65378. }
  65379. if (size != 0) {
  65380. var r = Math.max(parseInt(words[0]), 0);
  65381. var g = Math.max(parseInt(words[1]), 0);
  65382. var b = Math.max(parseInt(words[2]), 0);
  65383. maxColor = Math.max(r, maxColor);
  65384. maxColor = Math.max(g, maxColor);
  65385. maxColor = Math.max(b, maxColor);
  65386. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  65387. tempData[pixelStorageIndex + 0] = r;
  65388. tempData[pixelStorageIndex + 1] = g;
  65389. tempData[pixelStorageIndex + 2] = b;
  65390. pixelIndexSlice++;
  65391. if (pixelIndexSlice % size == 0) {
  65392. pixelIndexH++;
  65393. pixelIndexSlice = 0;
  65394. if (pixelIndexH % size == 0) {
  65395. pixelIndexW++;
  65396. pixelIndexH = 0;
  65397. }
  65398. }
  65399. }
  65400. }
  65401. for (var i = 0; i < tempData.length; i++) {
  65402. if (i > 0 && (i + 1) % 4 === 0) {
  65403. data[i] = 255;
  65404. }
  65405. else {
  65406. var value = tempData[i];
  65407. data[i] = (value / maxColor * 255);
  65408. }
  65409. }
  65410. texture.updateSize(size * size, size);
  65411. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  65412. };
  65413. BABYLON.Tools.LoadFile(this.url, callback);
  65414. return this._texture;
  65415. };
  65416. /**
  65417. * Starts the loading process of the texture.
  65418. */
  65419. ColorGradingTexture.prototype.loadTexture = function () {
  65420. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  65421. this.load3dlTexture();
  65422. }
  65423. };
  65424. /**
  65425. * Clones the color gradind texture.
  65426. */
  65427. ColorGradingTexture.prototype.clone = function () {
  65428. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  65429. // Base texture
  65430. newTexture.level = this.level;
  65431. return newTexture;
  65432. };
  65433. /**
  65434. * Called during delayed load for textures.
  65435. */
  65436. ColorGradingTexture.prototype.delayLoad = function () {
  65437. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65438. return;
  65439. }
  65440. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65441. this._texture = this._getFromCache(this.url, true);
  65442. if (!this._texture) {
  65443. this.loadTexture();
  65444. }
  65445. };
  65446. /**
  65447. * Parses a color grading texture serialized by Babylon.
  65448. * @param parsedTexture The texture information being parsedTexture
  65449. * @param scene The scene to load the texture in
  65450. * @param rootUrl The root url of the data assets to load
  65451. * @return A color gradind texture
  65452. */
  65453. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65454. var texture = null;
  65455. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  65456. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  65457. texture.name = parsedTexture.name;
  65458. texture.level = parsedTexture.level;
  65459. }
  65460. return texture;
  65461. };
  65462. /**
  65463. * Serializes the LUT texture to json format.
  65464. */
  65465. ColorGradingTexture.prototype.serialize = function () {
  65466. if (!this.name) {
  65467. return null;
  65468. }
  65469. var serializationObject = {};
  65470. serializationObject.name = this.name;
  65471. serializationObject.level = this.level;
  65472. serializationObject.customType = "BABYLON.ColorGradingTexture";
  65473. return serializationObject;
  65474. };
  65475. /**
  65476. * Empty line regex stored for GC.
  65477. */
  65478. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  65479. return ColorGradingTexture;
  65480. }(BABYLON.BaseTexture));
  65481. BABYLON.ColorGradingTexture = ColorGradingTexture;
  65482. })(BABYLON || (BABYLON = {}));
  65483. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  65484. var BABYLON;
  65485. (function (BABYLON) {
  65486. /**
  65487. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  65488. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  65489. * 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;
  65490. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  65491. */
  65492. var ColorCurves = (function () {
  65493. function ColorCurves() {
  65494. this._dirty = true;
  65495. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  65496. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  65497. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  65498. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  65499. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  65500. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  65501. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  65502. this._globalHue = 30;
  65503. this._globalDensity = 0;
  65504. this._globalSaturation = 0;
  65505. this._globalExposure = 0;
  65506. this._highlightsHue = 30;
  65507. this._highlightsDensity = 0;
  65508. this._highlightsSaturation = 0;
  65509. this._highlightsExposure = 0;
  65510. this._midtonesHue = 30;
  65511. this._midtonesDensity = 0;
  65512. this._midtonesSaturation = 0;
  65513. this._midtonesExposure = 0;
  65514. this._shadowsHue = 30;
  65515. this._shadowsDensity = 0;
  65516. this._shadowsSaturation = 0;
  65517. this._shadowsExposure = 0;
  65518. }
  65519. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  65520. /**
  65521. * Gets the global Hue value.
  65522. * 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).
  65523. */
  65524. get: function () {
  65525. return this._globalHue;
  65526. },
  65527. /**
  65528. * Sets the global Hue value.
  65529. * 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).
  65530. */
  65531. set: function (value) {
  65532. this._globalHue = value;
  65533. this._dirty = true;
  65534. },
  65535. enumerable: true,
  65536. configurable: true
  65537. });
  65538. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  65539. /**
  65540. * Gets the global Density value.
  65541. * 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.
  65542. * Values less than zero provide a filter of opposite hue.
  65543. */
  65544. get: function () {
  65545. return this._globalDensity;
  65546. },
  65547. /**
  65548. * Sets the global Density value.
  65549. * 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.
  65550. * Values less than zero provide a filter of opposite hue.
  65551. */
  65552. set: function (value) {
  65553. this._globalDensity = value;
  65554. this._dirty = true;
  65555. },
  65556. enumerable: true,
  65557. configurable: true
  65558. });
  65559. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  65560. /**
  65561. * Gets the global Saturation value.
  65562. * 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.
  65563. */
  65564. get: function () {
  65565. return this._globalSaturation;
  65566. },
  65567. /**
  65568. * Sets the global Saturation value.
  65569. * 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.
  65570. */
  65571. set: function (value) {
  65572. this._globalSaturation = value;
  65573. this._dirty = true;
  65574. },
  65575. enumerable: true,
  65576. configurable: true
  65577. });
  65578. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  65579. /**
  65580. * Gets the highlights Hue value.
  65581. * 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).
  65582. */
  65583. get: function () {
  65584. return this._highlightsHue;
  65585. },
  65586. /**
  65587. * Sets the highlights Hue value.
  65588. * 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).
  65589. */
  65590. set: function (value) {
  65591. this._highlightsHue = value;
  65592. this._dirty = true;
  65593. },
  65594. enumerable: true,
  65595. configurable: true
  65596. });
  65597. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  65598. /**
  65599. * Gets the highlights Density value.
  65600. * 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.
  65601. * Values less than zero provide a filter of opposite hue.
  65602. */
  65603. get: function () {
  65604. return this._highlightsDensity;
  65605. },
  65606. /**
  65607. * Sets the highlights Density value.
  65608. * 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.
  65609. * Values less than zero provide a filter of opposite hue.
  65610. */
  65611. set: function (value) {
  65612. this._highlightsDensity = value;
  65613. this._dirty = true;
  65614. },
  65615. enumerable: true,
  65616. configurable: true
  65617. });
  65618. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  65619. /**
  65620. * Gets the highlights Saturation value.
  65621. * 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.
  65622. */
  65623. get: function () {
  65624. return this._highlightsSaturation;
  65625. },
  65626. /**
  65627. * Sets the highlights Saturation value.
  65628. * 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.
  65629. */
  65630. set: function (value) {
  65631. this._highlightsSaturation = value;
  65632. this._dirty = true;
  65633. },
  65634. enumerable: true,
  65635. configurable: true
  65636. });
  65637. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  65638. /**
  65639. * Gets the highlights Exposure value.
  65640. * 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.
  65641. */
  65642. get: function () {
  65643. return this._highlightsExposure;
  65644. },
  65645. /**
  65646. * Sets the highlights Exposure value.
  65647. * 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.
  65648. */
  65649. set: function (value) {
  65650. this._highlightsExposure = value;
  65651. this._dirty = true;
  65652. },
  65653. enumerable: true,
  65654. configurable: true
  65655. });
  65656. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  65657. /**
  65658. * Gets the midtones Hue value.
  65659. * 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).
  65660. */
  65661. get: function () {
  65662. return this._midtonesHue;
  65663. },
  65664. /**
  65665. * Sets the midtones Hue value.
  65666. * 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).
  65667. */
  65668. set: function (value) {
  65669. this._midtonesHue = value;
  65670. this._dirty = true;
  65671. },
  65672. enumerable: true,
  65673. configurable: true
  65674. });
  65675. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  65676. /**
  65677. * Gets the midtones Density value.
  65678. * 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.
  65679. * Values less than zero provide a filter of opposite hue.
  65680. */
  65681. get: function () {
  65682. return this._midtonesDensity;
  65683. },
  65684. /**
  65685. * Sets the midtones Density value.
  65686. * 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.
  65687. * Values less than zero provide a filter of opposite hue.
  65688. */
  65689. set: function (value) {
  65690. this._midtonesDensity = value;
  65691. this._dirty = true;
  65692. },
  65693. enumerable: true,
  65694. configurable: true
  65695. });
  65696. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  65697. /**
  65698. * Gets the midtones Saturation value.
  65699. * 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.
  65700. */
  65701. get: function () {
  65702. return this._midtonesSaturation;
  65703. },
  65704. /**
  65705. * Sets the midtones Saturation value.
  65706. * 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.
  65707. */
  65708. set: function (value) {
  65709. this._midtonesSaturation = value;
  65710. this._dirty = true;
  65711. },
  65712. enumerable: true,
  65713. configurable: true
  65714. });
  65715. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  65716. /**
  65717. * Gets the midtones Exposure value.
  65718. * 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.
  65719. */
  65720. get: function () {
  65721. return this._midtonesExposure;
  65722. },
  65723. /**
  65724. * Sets the midtones Exposure value.
  65725. * 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.
  65726. */
  65727. set: function (value) {
  65728. this._midtonesExposure = value;
  65729. this._dirty = true;
  65730. },
  65731. enumerable: true,
  65732. configurable: true
  65733. });
  65734. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  65735. /**
  65736. * Gets the shadows Hue value.
  65737. * 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).
  65738. */
  65739. get: function () {
  65740. return this._shadowsHue;
  65741. },
  65742. /**
  65743. * Sets the shadows Hue value.
  65744. * 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).
  65745. */
  65746. set: function (value) {
  65747. this._shadowsHue = value;
  65748. this._dirty = true;
  65749. },
  65750. enumerable: true,
  65751. configurable: true
  65752. });
  65753. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  65754. /**
  65755. * Gets the shadows Density value.
  65756. * 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.
  65757. * Values less than zero provide a filter of opposite hue.
  65758. */
  65759. get: function () {
  65760. return this._shadowsDensity;
  65761. },
  65762. /**
  65763. * Sets the shadows Density value.
  65764. * 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.
  65765. * Values less than zero provide a filter of opposite hue.
  65766. */
  65767. set: function (value) {
  65768. this._shadowsDensity = value;
  65769. this._dirty = true;
  65770. },
  65771. enumerable: true,
  65772. configurable: true
  65773. });
  65774. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  65775. /**
  65776. * Gets the shadows Saturation value.
  65777. * 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.
  65778. */
  65779. get: function () {
  65780. return this._shadowsSaturation;
  65781. },
  65782. /**
  65783. * Sets the shadows Saturation value.
  65784. * 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.
  65785. */
  65786. set: function (value) {
  65787. this._shadowsSaturation = value;
  65788. this._dirty = true;
  65789. },
  65790. enumerable: true,
  65791. configurable: true
  65792. });
  65793. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  65794. /**
  65795. * Gets the shadows Exposure value.
  65796. * 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.
  65797. */
  65798. get: function () {
  65799. return this._shadowsExposure;
  65800. },
  65801. /**
  65802. * Sets the shadows Exposure value.
  65803. * 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.
  65804. */
  65805. set: function (value) {
  65806. this._shadowsExposure = value;
  65807. this._dirty = true;
  65808. },
  65809. enumerable: true,
  65810. configurable: true
  65811. });
  65812. ColorCurves.prototype.getClassName = function () {
  65813. return "ColorCurves";
  65814. };
  65815. /**
  65816. * Binds the color curves to the shader.
  65817. * @param colorCurves The color curve to bind
  65818. * @param effect The effect to bind to
  65819. */
  65820. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  65821. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  65822. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  65823. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  65824. if (colorCurves._dirty) {
  65825. colorCurves._dirty = false;
  65826. // Fill in global info.
  65827. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  65828. // Compute highlights info.
  65829. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  65830. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  65831. // Compute midtones info.
  65832. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  65833. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  65834. // Compute shadows info.
  65835. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  65836. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  65837. // Compute deltas (neutral is midtones).
  65838. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  65839. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  65840. }
  65841. if (effect) {
  65842. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  65843. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  65844. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  65845. }
  65846. };
  65847. /**
  65848. * Prepare the list of uniforms associated with the ColorCurves effects.
  65849. * @param uniformsList The list of uniforms used in the effect
  65850. */
  65851. ColorCurves.PrepareUniforms = function (uniformsList) {
  65852. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  65853. };
  65854. /**
  65855. * Returns color grading data based on a hue, density, saturation and exposure value.
  65856. * @param filterHue The hue of the color filter.
  65857. * @param filterDensity The density of the color filter.
  65858. * @param saturation The saturation.
  65859. * @param exposure The exposure.
  65860. * @param result The result data container.
  65861. */
  65862. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  65863. if (hue == null) {
  65864. return;
  65865. }
  65866. hue = ColorCurves.clamp(hue, 0, 360);
  65867. density = ColorCurves.clamp(density, -100, 100);
  65868. saturation = ColorCurves.clamp(saturation, -100, 100);
  65869. exposure = ColorCurves.clamp(exposure, -100, 100);
  65870. // Remap the slider/config filter density with non-linear mapping and also scale by half
  65871. // so that the maximum filter density is only 50% control. This provides fine control
  65872. // for small values and reasonable range.
  65873. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  65874. density *= 0.5;
  65875. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  65876. if (density < 0) {
  65877. density *= -1;
  65878. hue = (hue + 180) % 360;
  65879. }
  65880. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  65881. result.scaleToRef(2, result);
  65882. result.a = 1 + 0.01 * saturation;
  65883. };
  65884. /**
  65885. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  65886. * @param value The input slider value in range [-100,100].
  65887. * @returns Adjusted value.
  65888. */
  65889. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  65890. value /= 100;
  65891. var x = Math.abs(value);
  65892. x = Math.pow(x, 2);
  65893. if (value < 0) {
  65894. x *= -1;
  65895. }
  65896. x *= 100;
  65897. return x;
  65898. };
  65899. /**
  65900. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  65901. * @param hue The hue (H) input.
  65902. * @param saturation The saturation (S) input.
  65903. * @param brightness The brightness (B) input.
  65904. * @result An RGBA color represented as Vector4.
  65905. */
  65906. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  65907. var h = ColorCurves.clamp(hue, 0, 360);
  65908. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  65909. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  65910. if (s === 0) {
  65911. result.r = v;
  65912. result.g = v;
  65913. result.b = v;
  65914. }
  65915. else {
  65916. // sector 0 to 5
  65917. h /= 60;
  65918. var i = Math.floor(h);
  65919. // fractional part of h
  65920. var f = h - i;
  65921. var p = v * (1 - s);
  65922. var q = v * (1 - s * f);
  65923. var t = v * (1 - s * (1 - f));
  65924. switch (i) {
  65925. case 0:
  65926. result.r = v;
  65927. result.g = t;
  65928. result.b = p;
  65929. break;
  65930. case 1:
  65931. result.r = q;
  65932. result.g = v;
  65933. result.b = p;
  65934. break;
  65935. case 2:
  65936. result.r = p;
  65937. result.g = v;
  65938. result.b = t;
  65939. break;
  65940. case 3:
  65941. result.r = p;
  65942. result.g = q;
  65943. result.b = v;
  65944. break;
  65945. case 4:
  65946. result.r = t;
  65947. result.g = p;
  65948. result.b = v;
  65949. break;
  65950. default:// case 5:
  65951. result.r = v;
  65952. result.g = p;
  65953. result.b = q;
  65954. break;
  65955. }
  65956. }
  65957. result.a = 1;
  65958. };
  65959. /**
  65960. * Returns a value clamped between min and max
  65961. * @param value The value to clamp
  65962. * @param min The minimum of value
  65963. * @param max The maximum of value
  65964. * @returns The clamped value.
  65965. */
  65966. ColorCurves.clamp = function (value, min, max) {
  65967. return Math.min(Math.max(value, min), max);
  65968. };
  65969. /**
  65970. * Clones the current color curve instance.
  65971. * @return The cloned curves
  65972. */
  65973. ColorCurves.prototype.clone = function () {
  65974. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  65975. };
  65976. /**
  65977. * Serializes the current color curve instance to a json representation.
  65978. * @return a JSON representation
  65979. */
  65980. ColorCurves.prototype.serialize = function () {
  65981. return BABYLON.SerializationHelper.Serialize(this);
  65982. };
  65983. /**
  65984. * Parses the color curve from a json representation.
  65985. * @param source the JSON source to parse
  65986. * @return The parsed curves
  65987. */
  65988. ColorCurves.Parse = function (source) {
  65989. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  65990. };
  65991. __decorate([
  65992. BABYLON.serialize()
  65993. ], ColorCurves.prototype, "_globalHue", void 0);
  65994. __decorate([
  65995. BABYLON.serialize()
  65996. ], ColorCurves.prototype, "_globalDensity", void 0);
  65997. __decorate([
  65998. BABYLON.serialize()
  65999. ], ColorCurves.prototype, "_globalSaturation", void 0);
  66000. __decorate([
  66001. BABYLON.serialize()
  66002. ], ColorCurves.prototype, "_globalExposure", void 0);
  66003. __decorate([
  66004. BABYLON.serialize()
  66005. ], ColorCurves.prototype, "_highlightsHue", void 0);
  66006. __decorate([
  66007. BABYLON.serialize()
  66008. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  66009. __decorate([
  66010. BABYLON.serialize()
  66011. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  66012. __decorate([
  66013. BABYLON.serialize()
  66014. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  66015. __decorate([
  66016. BABYLON.serialize()
  66017. ], ColorCurves.prototype, "_midtonesHue", void 0);
  66018. __decorate([
  66019. BABYLON.serialize()
  66020. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  66021. __decorate([
  66022. BABYLON.serialize()
  66023. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  66024. __decorate([
  66025. BABYLON.serialize()
  66026. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  66027. return ColorCurves;
  66028. }());
  66029. BABYLON.ColorCurves = ColorCurves;
  66030. })(BABYLON || (BABYLON = {}));
  66031. //# sourceMappingURL=babylon.colorCurves.js.map
  66032. var BABYLON;
  66033. (function (BABYLON) {
  66034. var Octree = (function () {
  66035. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  66036. if (maxDepth === void 0) { maxDepth = 2; }
  66037. this.maxDepth = maxDepth;
  66038. this.dynamicContent = new Array();
  66039. this._maxBlockCapacity = maxBlockCapacity || 64;
  66040. this._selectionContent = new BABYLON.SmartArray(1024);
  66041. this._creationFunc = creationFunc;
  66042. }
  66043. // Methods
  66044. Octree.prototype.update = function (worldMin, worldMax, entries) {
  66045. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  66046. };
  66047. Octree.prototype.addMesh = function (entry) {
  66048. for (var index = 0; index < this.blocks.length; index++) {
  66049. var block = this.blocks[index];
  66050. block.addEntry(entry);
  66051. }
  66052. };
  66053. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  66054. this._selectionContent.reset();
  66055. for (var index = 0; index < this.blocks.length; index++) {
  66056. var block = this.blocks[index];
  66057. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  66058. }
  66059. if (allowDuplicate) {
  66060. this._selectionContent.concat(this.dynamicContent);
  66061. }
  66062. else {
  66063. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66064. }
  66065. return this._selectionContent;
  66066. };
  66067. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  66068. this._selectionContent.reset();
  66069. for (var index = 0; index < this.blocks.length; index++) {
  66070. var block = this.blocks[index];
  66071. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  66072. }
  66073. if (allowDuplicate) {
  66074. this._selectionContent.concat(this.dynamicContent);
  66075. }
  66076. else {
  66077. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66078. }
  66079. return this._selectionContent;
  66080. };
  66081. Octree.prototype.intersectsRay = function (ray) {
  66082. this._selectionContent.reset();
  66083. for (var index = 0; index < this.blocks.length; index++) {
  66084. var block = this.blocks[index];
  66085. block.intersectsRay(ray, this._selectionContent);
  66086. }
  66087. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66088. return this._selectionContent;
  66089. };
  66090. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  66091. target.blocks = new Array();
  66092. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  66093. // Segmenting space
  66094. for (var x = 0; x < 2; x++) {
  66095. for (var y = 0; y < 2; y++) {
  66096. for (var z = 0; z < 2; z++) {
  66097. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  66098. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  66099. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  66100. block.addEntries(entries);
  66101. target.blocks.push(block);
  66102. }
  66103. }
  66104. }
  66105. };
  66106. Octree.CreationFuncForMeshes = function (entry, block) {
  66107. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  66108. block.entries.push(entry);
  66109. }
  66110. };
  66111. Octree.CreationFuncForSubMeshes = function (entry, block) {
  66112. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  66113. block.entries.push(entry);
  66114. }
  66115. };
  66116. return Octree;
  66117. }());
  66118. BABYLON.Octree = Octree;
  66119. })(BABYLON || (BABYLON = {}));
  66120. //# sourceMappingURL=babylon.octree.js.map
  66121. var BABYLON;
  66122. (function (BABYLON) {
  66123. var OctreeBlock = (function () {
  66124. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  66125. this.entries = new Array();
  66126. this._boundingVectors = new Array();
  66127. this._capacity = capacity;
  66128. this._depth = depth;
  66129. this._maxDepth = maxDepth;
  66130. this._creationFunc = creationFunc;
  66131. this._minPoint = minPoint;
  66132. this._maxPoint = maxPoint;
  66133. this._boundingVectors.push(minPoint.clone());
  66134. this._boundingVectors.push(maxPoint.clone());
  66135. this._boundingVectors.push(minPoint.clone());
  66136. this._boundingVectors[2].x = maxPoint.x;
  66137. this._boundingVectors.push(minPoint.clone());
  66138. this._boundingVectors[3].y = maxPoint.y;
  66139. this._boundingVectors.push(minPoint.clone());
  66140. this._boundingVectors[4].z = maxPoint.z;
  66141. this._boundingVectors.push(maxPoint.clone());
  66142. this._boundingVectors[5].z = minPoint.z;
  66143. this._boundingVectors.push(maxPoint.clone());
  66144. this._boundingVectors[6].x = minPoint.x;
  66145. this._boundingVectors.push(maxPoint.clone());
  66146. this._boundingVectors[7].y = minPoint.y;
  66147. }
  66148. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  66149. // Property
  66150. get: function () {
  66151. return this._capacity;
  66152. },
  66153. enumerable: true,
  66154. configurable: true
  66155. });
  66156. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  66157. get: function () {
  66158. return this._minPoint;
  66159. },
  66160. enumerable: true,
  66161. configurable: true
  66162. });
  66163. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  66164. get: function () {
  66165. return this._maxPoint;
  66166. },
  66167. enumerable: true,
  66168. configurable: true
  66169. });
  66170. // Methods
  66171. OctreeBlock.prototype.addEntry = function (entry) {
  66172. if (this.blocks) {
  66173. for (var index = 0; index < this.blocks.length; index++) {
  66174. var block = this.blocks[index];
  66175. block.addEntry(entry);
  66176. }
  66177. return;
  66178. }
  66179. this._creationFunc(entry, this);
  66180. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  66181. this.createInnerBlocks();
  66182. }
  66183. };
  66184. OctreeBlock.prototype.addEntries = function (entries) {
  66185. for (var index = 0; index < entries.length; index++) {
  66186. var mesh = entries[index];
  66187. this.addEntry(mesh);
  66188. }
  66189. };
  66190. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  66191. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  66192. if (this.blocks) {
  66193. for (var index = 0; index < this.blocks.length; index++) {
  66194. var block = this.blocks[index];
  66195. block.select(frustumPlanes, selection, allowDuplicate);
  66196. }
  66197. return;
  66198. }
  66199. if (allowDuplicate) {
  66200. selection.concat(this.entries);
  66201. }
  66202. else {
  66203. selection.concatWithNoDuplicate(this.entries);
  66204. }
  66205. }
  66206. };
  66207. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  66208. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  66209. if (this.blocks) {
  66210. for (var index = 0; index < this.blocks.length; index++) {
  66211. var block = this.blocks[index];
  66212. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  66213. }
  66214. return;
  66215. }
  66216. if (allowDuplicate) {
  66217. selection.concat(this.entries);
  66218. }
  66219. else {
  66220. selection.concatWithNoDuplicate(this.entries);
  66221. }
  66222. }
  66223. };
  66224. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  66225. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  66226. if (this.blocks) {
  66227. for (var index = 0; index < this.blocks.length; index++) {
  66228. var block = this.blocks[index];
  66229. block.intersectsRay(ray, selection);
  66230. }
  66231. return;
  66232. }
  66233. selection.concatWithNoDuplicate(this.entries);
  66234. }
  66235. };
  66236. OctreeBlock.prototype.createInnerBlocks = function () {
  66237. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  66238. };
  66239. return OctreeBlock;
  66240. }());
  66241. BABYLON.OctreeBlock = OctreeBlock;
  66242. })(BABYLON || (BABYLON = {}));
  66243. //# sourceMappingURL=babylon.octreeBlock.js.map
  66244. var BABYLON;
  66245. (function (BABYLON) {
  66246. var SIMDVector3 = (function () {
  66247. function SIMDVector3() {
  66248. }
  66249. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  66250. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  66251. };
  66252. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  66253. var m = transformation.m;
  66254. var m0 = SIMD.Float32x4.load(m, 0);
  66255. var m1 = SIMD.Float32x4.load(m, 4);
  66256. var m2 = SIMD.Float32x4.load(m, 8);
  66257. var m3 = SIMD.Float32x4.load(m, 12);
  66258. 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));
  66259. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  66260. result.x = SIMD.Float32x4.extractLane(r, 0);
  66261. result.y = SIMD.Float32x4.extractLane(r, 1);
  66262. result.z = SIMD.Float32x4.extractLane(r, 2);
  66263. };
  66264. return SIMDVector3;
  66265. }());
  66266. var SIMDMatrix = (function () {
  66267. function SIMDMatrix() {
  66268. }
  66269. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  66270. var tm = this.m;
  66271. var om = other.m;
  66272. var m0 = SIMD.Float32x4.load(om, 0);
  66273. var m1 = SIMD.Float32x4.load(om, 4);
  66274. var m2 = SIMD.Float32x4.load(om, 8);
  66275. var m3 = SIMD.Float32x4.load(om, 12);
  66276. for (var i = 0; i < 16; i += 4) {
  66277. 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)))));
  66278. }
  66279. return this;
  66280. };
  66281. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  66282. var src = this.m;
  66283. var dest = other.m;
  66284. // Load the 4 rows
  66285. var src0 = SIMD.Float32x4.load(src, 0);
  66286. var src1 = SIMD.Float32x4.load(src, 4);
  66287. var src2 = SIMD.Float32x4.load(src, 8);
  66288. var src3 = SIMD.Float32x4.load(src, 12);
  66289. // Transpose the source matrix. Sort of. Not a true transpose operation
  66290. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  66291. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  66292. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  66293. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  66294. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  66295. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  66296. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  66297. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  66298. // This is a true transposition, but it will lead to an incorrect result
  66299. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  66300. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  66301. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  66302. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  66303. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  66304. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  66305. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  66306. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  66307. // ----
  66308. tmp1 = SIMD.Float32x4.mul(row2, row3);
  66309. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66310. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  66311. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  66312. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66313. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  66314. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  66315. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  66316. // ----
  66317. tmp1 = SIMD.Float32x4.mul(row1, row2);
  66318. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66319. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  66320. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  66321. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66322. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  66323. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  66324. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  66325. // ----
  66326. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  66327. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66328. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  66329. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  66330. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  66331. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66332. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  66333. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  66334. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  66335. // ----
  66336. tmp1 = SIMD.Float32x4.mul(row0, row1);
  66337. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66338. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  66339. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  66340. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66341. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  66342. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  66343. // ----
  66344. tmp1 = SIMD.Float32x4.mul(row0, row3);
  66345. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66346. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  66347. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  66348. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66349. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  66350. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  66351. // ----
  66352. tmp1 = SIMD.Float32x4.mul(row0, row2);
  66353. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66354. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  66355. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  66356. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66357. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  66358. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  66359. // Compute determinant
  66360. var det = SIMD.Float32x4.mul(row0, minor0);
  66361. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  66362. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  66363. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  66364. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  66365. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  66366. // These shuffles aren't necessary if the faulty transposition is done
  66367. // up at the top of this function.
  66368. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  66369. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  66370. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  66371. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  66372. // Compute final values by multiplying with 1/det
  66373. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  66374. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  66375. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  66376. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  66377. return this;
  66378. };
  66379. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  66380. var out = result.m;
  66381. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  66382. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  66383. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  66384. // cc.kmVec3Subtract(f, pCenter, pEye);
  66385. var f = SIMD.Float32x4.sub(center, eye);
  66386. // cc.kmVec3Normalize(f, f);
  66387. var tmp = SIMD.Float32x4.mul(f, f);
  66388. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66389. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66390. // cc.kmVec3Assign(up, pUp);
  66391. // cc.kmVec3Normalize(up, up);
  66392. tmp = SIMD.Float32x4.mul(up, up);
  66393. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66394. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66395. // cc.kmVec3Cross(s, f, up);
  66396. 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)));
  66397. // cc.kmVec3Normalize(s, s);
  66398. tmp = SIMD.Float32x4.mul(s, s);
  66399. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66400. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66401. // cc.kmVec3Cross(u, s, f);
  66402. 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)));
  66403. // cc.kmVec3Normalize(s, s);
  66404. tmp = SIMD.Float32x4.mul(s, s);
  66405. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  66406. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  66407. var zero = SIMD.Float32x4.splat(0.0);
  66408. s = SIMD.Float32x4.neg(s);
  66409. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  66410. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  66411. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  66412. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  66413. 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);
  66414. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  66415. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  66416. 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)))));
  66417. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  66418. 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)))));
  66419. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  66420. 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)))));
  66421. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  66422. 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)))));
  66423. };
  66424. return SIMDMatrix;
  66425. }());
  66426. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  66427. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  66428. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  66429. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  66430. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  66431. var SIMDHelper = (function () {
  66432. function SIMDHelper() {
  66433. }
  66434. Object.defineProperty(SIMDHelper, "IsEnabled", {
  66435. get: function () {
  66436. return SIMDHelper._isEnabled;
  66437. },
  66438. enumerable: true,
  66439. configurable: true
  66440. });
  66441. SIMDHelper.DisableSIMD = function () {
  66442. // Replace functions
  66443. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  66444. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  66445. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  66446. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  66447. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  66448. SIMDHelper._isEnabled = false;
  66449. };
  66450. SIMDHelper.EnableSIMD = function () {
  66451. if (self.SIMD === undefined) {
  66452. return;
  66453. }
  66454. // check if polyfills needed
  66455. if (!self.Math.fround) {
  66456. self.Math.fround = (function (array) { return function (x) {
  66457. return array[0] = x, array[0];
  66458. }; })(new Float32Array(1));
  66459. }
  66460. if (!self.Math.imul) {
  66461. self.Math.imul = function (a, b) {
  66462. var ah = (a >>> 16) & 0xffff;
  66463. var al = a & 0xffff;
  66464. var bh = (b >>> 16) & 0xffff;
  66465. var bl = b & 0xffff;
  66466. // the shift by 0 fixes the sign on the high part
  66467. // the final |0 converts the unsigned value into a signed value
  66468. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  66469. };
  66470. }
  66471. // Replace functions
  66472. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  66473. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  66474. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  66475. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  66476. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  66477. SIMDHelper._isEnabled = true;
  66478. };
  66479. SIMDHelper._isEnabled = false;
  66480. return SIMDHelper;
  66481. }());
  66482. BABYLON.SIMDHelper = SIMDHelper;
  66483. })(BABYLON || (BABYLON = {}));
  66484. //# sourceMappingURL=babylon.math.SIMD.js.map
  66485. var BABYLON;
  66486. (function (BABYLON) {
  66487. var VRDistortionCorrectionPostProcess = (function (_super) {
  66488. __extends(VRDistortionCorrectionPostProcess, _super);
  66489. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  66490. var _this = _super.call(this, name, "vrDistortionCorrection", [
  66491. 'LensCenter',
  66492. 'Scale',
  66493. 'ScaleIn',
  66494. 'HmdWarpParam'
  66495. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  66496. _this._isRightEye = isRightEye;
  66497. _this._distortionFactors = vrMetrics.distortionK;
  66498. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  66499. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  66500. _this.adaptScaleToCurrentViewport = true;
  66501. _this.onSizeChangedObservable.add(function () {
  66502. _this.aspectRatio = _this.width * .5 / _this.height;
  66503. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  66504. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  66505. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  66506. });
  66507. _this.onApplyObservable.add(function (effect) {
  66508. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  66509. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  66510. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  66511. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  66512. });
  66513. return _this;
  66514. }
  66515. return VRDistortionCorrectionPostProcess;
  66516. }(BABYLON.PostProcess));
  66517. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  66518. })(BABYLON || (BABYLON = {}));
  66519. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  66520. var BABYLON;
  66521. (function (BABYLON) {
  66522. var AnaglyphPostProcess = (function (_super) {
  66523. __extends(AnaglyphPostProcess, _super);
  66524. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  66525. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  66526. _this._passedProcess = rigCameras[0]._rigPostProcess;
  66527. _this.onApplyObservable.add(function (effect) {
  66528. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  66529. });
  66530. return _this;
  66531. }
  66532. return AnaglyphPostProcess;
  66533. }(BABYLON.PostProcess));
  66534. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  66535. })(BABYLON || (BABYLON = {}));
  66536. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  66537. var BABYLON;
  66538. (function (BABYLON) {
  66539. var StereoscopicInterlacePostProcess = (function (_super) {
  66540. __extends(StereoscopicInterlacePostProcess, _super);
  66541. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  66542. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  66543. _this._passedProcess = rigCameras[0]._rigPostProcess;
  66544. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  66545. _this.onSizeChangedObservable.add(function () {
  66546. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  66547. });
  66548. _this.onApplyObservable.add(function (effect) {
  66549. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  66550. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  66551. });
  66552. return _this;
  66553. }
  66554. return StereoscopicInterlacePostProcess;
  66555. }(BABYLON.PostProcess));
  66556. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  66557. })(BABYLON || (BABYLON = {}));
  66558. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  66559. var BABYLON;
  66560. (function (BABYLON) {
  66561. var FreeCameraDeviceOrientationInput = (function () {
  66562. function FreeCameraDeviceOrientationInput() {
  66563. var _this = this;
  66564. this._screenOrientationAngle = 0;
  66565. this._screenQuaternion = new BABYLON.Quaternion();
  66566. this._alpha = 0;
  66567. this._beta = 0;
  66568. this._gamma = 0;
  66569. this._orientationChanged = function () {
  66570. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  66571. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  66572. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  66573. };
  66574. this._deviceOrientation = function (evt) {
  66575. _this._alpha = evt.alpha;
  66576. _this._beta = evt.beta;
  66577. _this._gamma = evt.gamma;
  66578. };
  66579. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  66580. this._orientationChanged();
  66581. }
  66582. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  66583. get: function () {
  66584. return this._camera;
  66585. },
  66586. set: function (camera) {
  66587. this._camera = camera;
  66588. if (this._camera != null && !this._camera.rotationQuaternion) {
  66589. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  66590. }
  66591. },
  66592. enumerable: true,
  66593. configurable: true
  66594. });
  66595. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  66596. window.addEventListener("orientationchange", this._orientationChanged);
  66597. window.addEventListener("deviceorientation", this._deviceOrientation);
  66598. //In certain cases, the attach control is called AFTER orientation was changed,
  66599. //So this is needed.
  66600. this._orientationChanged();
  66601. };
  66602. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  66603. window.removeEventListener("orientationchange", this._orientationChanged);
  66604. window.removeEventListener("deviceorientation", this._deviceOrientation);
  66605. };
  66606. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  66607. //if no device orientation provided, don't update the rotation.
  66608. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  66609. if (!this._alpha)
  66610. return;
  66611. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  66612. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  66613. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  66614. //Mirror on XY Plane
  66615. this._camera.rotationQuaternion.z *= -1;
  66616. this._camera.rotationQuaternion.w *= -1;
  66617. };
  66618. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  66619. return "FreeCameraDeviceOrientationInput";
  66620. };
  66621. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  66622. return "deviceOrientation";
  66623. };
  66624. return FreeCameraDeviceOrientationInput;
  66625. }());
  66626. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  66627. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  66628. })(BABYLON || (BABYLON = {}));
  66629. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  66630. var BABYLON;
  66631. (function (BABYLON) {
  66632. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  66633. function ArcRotateCameraVRDeviceOrientationInput() {
  66634. this.alphaCorrection = 1;
  66635. this.betaCorrection = 1;
  66636. this.gammaCorrection = 1;
  66637. this._alpha = 0;
  66638. this._beta = 0;
  66639. this._gamma = 0;
  66640. this._dirty = false;
  66641. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  66642. }
  66643. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  66644. this.camera.attachControl(element, noPreventDefault);
  66645. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  66646. };
  66647. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  66648. var camera = this.camera;
  66649. this._alpha = +evt.alpha | 0;
  66650. this._beta = +evt.beta | 0;
  66651. this._gamma = +evt.gamma | 0;
  66652. this._dirty = true;
  66653. };
  66654. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  66655. if (this._dirty) {
  66656. this._dirty = false;
  66657. if (this._gamma < 0) {
  66658. this._gamma = 180 + this._gamma;
  66659. }
  66660. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  66661. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  66662. }
  66663. };
  66664. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  66665. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  66666. };
  66667. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  66668. return "ArcRotateCameraVRDeviceOrientationInput";
  66669. };
  66670. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  66671. return "VRDeviceOrientation";
  66672. };
  66673. return ArcRotateCameraVRDeviceOrientationInput;
  66674. }());
  66675. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  66676. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  66677. })(BABYLON || (BABYLON = {}));
  66678. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  66679. var BABYLON;
  66680. (function (BABYLON) {
  66681. var VRCameraMetrics = (function () {
  66682. function VRCameraMetrics() {
  66683. this.compensateDistortion = true;
  66684. }
  66685. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  66686. get: function () {
  66687. return this.hResolution / (2 * this.vResolution);
  66688. },
  66689. enumerable: true,
  66690. configurable: true
  66691. });
  66692. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  66693. get: function () {
  66694. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  66695. },
  66696. enumerable: true,
  66697. configurable: true
  66698. });
  66699. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  66700. get: function () {
  66701. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66702. var h = (4 * meters) / this.hScreenSize;
  66703. return BABYLON.Matrix.Translation(h, 0, 0);
  66704. },
  66705. enumerable: true,
  66706. configurable: true
  66707. });
  66708. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  66709. get: function () {
  66710. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  66711. var h = (4 * meters) / this.hScreenSize;
  66712. return BABYLON.Matrix.Translation(-h, 0, 0);
  66713. },
  66714. enumerable: true,
  66715. configurable: true
  66716. });
  66717. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  66718. get: function () {
  66719. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  66720. },
  66721. enumerable: true,
  66722. configurable: true
  66723. });
  66724. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  66725. get: function () {
  66726. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  66727. },
  66728. enumerable: true,
  66729. configurable: true
  66730. });
  66731. VRCameraMetrics.GetDefault = function () {
  66732. var result = new VRCameraMetrics();
  66733. result.hResolution = 1280;
  66734. result.vResolution = 800;
  66735. result.hScreenSize = 0.149759993;
  66736. result.vScreenSize = 0.0935999975;
  66737. result.vScreenCenter = 0.0467999987;
  66738. result.eyeToScreenDistance = 0.0410000011;
  66739. result.lensSeparationDistance = 0.0635000020;
  66740. result.interpupillaryDistance = 0.0640000030;
  66741. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  66742. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  66743. result.postProcessScaleFactor = 1.714605507808412;
  66744. result.lensCenterOffset = 0.151976421;
  66745. return result;
  66746. };
  66747. return VRCameraMetrics;
  66748. }());
  66749. BABYLON.VRCameraMetrics = VRCameraMetrics;
  66750. })(BABYLON || (BABYLON = {}));
  66751. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  66752. var BABYLON;
  66753. (function (BABYLON) {
  66754. var WebVRFreeCamera = (function (_super) {
  66755. __extends(WebVRFreeCamera, _super);
  66756. function WebVRFreeCamera(name, position, scene, webVROptions) {
  66757. if (webVROptions === void 0) { webVROptions = {}; }
  66758. var _this = _super.call(this, name, position, scene) || this;
  66759. _this.webVROptions = webVROptions;
  66760. _this._vrDevice = null;
  66761. _this.rawPose = null;
  66762. _this._specsVersion = "1.1";
  66763. _this._attached = false;
  66764. _this._positionOffset = BABYLON.Vector3.Zero();
  66765. _this._descendants = [];
  66766. _this.devicePosition = BABYLON.Vector3.Zero();
  66767. _this.deviceScaleFactor = 1;
  66768. _this.controllers = [];
  66769. _this.onControllersAttachedObservable = new BABYLON.Observable();
  66770. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  66771. _this.minZ = 0.1;
  66772. //legacy support - the compensation boolean was removed.
  66773. if (arguments.length === 5) {
  66774. _this.webVROptions = arguments[4];
  66775. }
  66776. // default webVR options
  66777. if (_this.webVROptions.trackPosition == undefined) {
  66778. _this.webVROptions.trackPosition = true;
  66779. }
  66780. if (_this.webVROptions.controllerMeshes == undefined) {
  66781. _this.webVROptions.controllerMeshes = true;
  66782. }
  66783. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  66784. _this.webVROptions.defaultLightingOnControllers = true;
  66785. }
  66786. _this.rotationQuaternion = new BABYLON.Quaternion();
  66787. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66788. if (_this.webVROptions && _this.webVROptions.positionScale) {
  66789. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  66790. }
  66791. //enable VR
  66792. var engine = _this.getEngine();
  66793. _this._onVREnabled = function (success) { if (success) {
  66794. _this.initControllers();
  66795. } };
  66796. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  66797. engine.initWebVR().add(function (event) {
  66798. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  66799. return;
  66800. }
  66801. _this._vrDevice = event.vrDisplay;
  66802. //reset the rig parameters.
  66803. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  66804. if (_this._attached) {
  66805. _this.getEngine().enableVR();
  66806. }
  66807. });
  66808. if (typeof (VRFrameData) !== "undefined")
  66809. _this._frameData = new VRFrameData();
  66810. /**
  66811. * The idea behind the following lines:
  66812. * objects that have the camera as parent should actually have the rig cameras as a parent.
  66813. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  66814. * the second will not show it correctly.
  66815. *
  66816. * To solve this - each object that has the camera as parent will be added to a protected array.
  66817. * When the rig camera renders, it will take this array and set all of those to be its children.
  66818. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  66819. * Amazing!
  66820. */
  66821. scene.onBeforeCameraRenderObservable.add(function (camera) {
  66822. if (camera.parent === _this && _this.rigParenting) {
  66823. _this._descendants = _this.getDescendants(true, function (n) {
  66824. // don't take the cameras or the controllers!
  66825. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  66826. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  66827. return !isController && !isRigCamera;
  66828. });
  66829. _this._descendants.forEach(function (node) {
  66830. node.parent = camera;
  66831. });
  66832. }
  66833. });
  66834. scene.onAfterCameraRenderObservable.add(function (camera) {
  66835. if (camera.parent === _this && _this.rigParenting) {
  66836. _this._descendants.forEach(function (node) {
  66837. node.parent = _this;
  66838. });
  66839. }
  66840. });
  66841. return _this;
  66842. }
  66843. WebVRFreeCamera.prototype.dispose = function () {
  66844. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  66845. _super.prototype.dispose.call(this);
  66846. };
  66847. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  66848. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  66849. var gp = _a[_i];
  66850. if (gp.hand === name) {
  66851. return gp;
  66852. }
  66853. }
  66854. return undefined;
  66855. };
  66856. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  66857. get: function () {
  66858. if (!this._leftController) {
  66859. this._leftController = this.getControllerByName("left");
  66860. }
  66861. return this._leftController;
  66862. },
  66863. enumerable: true,
  66864. configurable: true
  66865. });
  66866. ;
  66867. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  66868. get: function () {
  66869. if (!this._rightController) {
  66870. this._rightController = this.getControllerByName("right");
  66871. }
  66872. return this._rightController;
  66873. },
  66874. enumerable: true,
  66875. configurable: true
  66876. });
  66877. ;
  66878. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  66879. if (length === void 0) { length = 100; }
  66880. if (this.leftCamera) {
  66881. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  66882. }
  66883. else {
  66884. return _super.prototype.getForwardRay.call(this, length);
  66885. }
  66886. };
  66887. WebVRFreeCamera.prototype._checkInputs = function () {
  66888. if (this._vrDevice && this._vrDevice.isPresenting) {
  66889. this._vrDevice.getFrameData(this._frameData);
  66890. this.updateFromDevice(this._frameData.pose);
  66891. }
  66892. _super.prototype._checkInputs.call(this);
  66893. };
  66894. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  66895. if (poseData && poseData.orientation) {
  66896. this.rawPose = poseData;
  66897. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  66898. if (this.getScene().useRightHandedSystem) {
  66899. this.deviceRotationQuaternion.z *= -1;
  66900. this.deviceRotationQuaternion.w *= -1;
  66901. }
  66902. if (this.webVROptions.trackPosition && this.rawPose.position) {
  66903. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  66904. if (this.getScene().useRightHandedSystem) {
  66905. this.devicePosition.z *= -1;
  66906. }
  66907. }
  66908. }
  66909. };
  66910. /**
  66911. * WebVR's attach control will start broadcasting frames to the device.
  66912. * Note that in certain browsers (chrome for example) this function must be called
  66913. * within a user-interaction callback. Example:
  66914. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  66915. *
  66916. * @param {HTMLElement} element
  66917. * @param {boolean} [noPreventDefault]
  66918. *
  66919. * @memberOf WebVRFreeCamera
  66920. */
  66921. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  66922. _super.prototype.attachControl.call(this, element, noPreventDefault);
  66923. this._attached = true;
  66924. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  66925. if (this._vrDevice) {
  66926. this.getEngine().enableVR();
  66927. }
  66928. };
  66929. WebVRFreeCamera.prototype.detachControl = function (element) {
  66930. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  66931. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  66932. _super.prototype.detachControl.call(this, element);
  66933. this._attached = false;
  66934. this.getEngine().disableVR();
  66935. };
  66936. WebVRFreeCamera.prototype.getClassName = function () {
  66937. return "WebVRFreeCamera";
  66938. };
  66939. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  66940. //uses the vrDisplay's "resetPose()".
  66941. //pitch and roll won't be affected.
  66942. this._vrDevice.resetPose();
  66943. };
  66944. WebVRFreeCamera.prototype._updateRigCameras = function () {
  66945. var camLeft = this._rigCameras[0];
  66946. var camRight = this._rigCameras[1];
  66947. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66948. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66949. camLeft.position.copyFrom(this.devicePosition);
  66950. camRight.position.copyFrom(this.devicePosition);
  66951. };
  66952. /**
  66953. * This function is called by the two RIG cameras.
  66954. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  66955. */
  66956. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  66957. var _this = this;
  66958. //WebVR 1.1
  66959. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  66960. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  66961. if (!this.getScene().useRightHandedSystem) {
  66962. [2, 6, 8, 9, 14].forEach(function (num) {
  66963. _this._webvrViewMatrix.m[num] *= -1;
  66964. });
  66965. }
  66966. // update the camera rotation matrix
  66967. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  66968. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  66969. // Computing target and final matrix
  66970. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  66971. var parentCamera = this._cameraRigParams["parentCamera"];
  66972. // should the view matrix be updated with scale and position offset?
  66973. if (parentCamera.deviceScaleFactor !== 1) {
  66974. this._webvrViewMatrix.invert();
  66975. // scale the position, if set
  66976. if (parentCamera.deviceScaleFactor) {
  66977. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  66978. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  66979. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  66980. }
  66981. this._webvrViewMatrix.invert();
  66982. }
  66983. return this._webvrViewMatrix;
  66984. };
  66985. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  66986. var _this = this;
  66987. var parentCamera = this.parent;
  66988. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  66989. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  66990. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  66991. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  66992. //babylon compatible matrix
  66993. if (!this.getScene().useRightHandedSystem) {
  66994. [8, 9, 10, 11].forEach(function (num) {
  66995. _this._projectionMatrix.m[num] *= -1;
  66996. });
  66997. }
  66998. return this._projectionMatrix;
  66999. };
  67000. WebVRFreeCamera.prototype.initControllers = function () {
  67001. var _this = this;
  67002. this.controllers = [];
  67003. var manager = this.getScene().gamepadManager;
  67004. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  67005. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  67006. var webVrController = gamepad;
  67007. if (webVrController.defaultModel) {
  67008. webVrController.defaultModel.setEnabled(false);
  67009. }
  67010. }
  67011. });
  67012. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  67013. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  67014. var webVrController = gamepad;
  67015. if (_this.webVROptions.controllerMeshes) {
  67016. if (webVrController.defaultModel) {
  67017. webVrController.defaultModel.setEnabled(true);
  67018. }
  67019. else {
  67020. // Load the meshes
  67021. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  67022. if (_this.webVROptions.defaultLightingOnControllers) {
  67023. if (!_this._lightOnControllers) {
  67024. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  67025. }
  67026. var activateLightOnSubMeshes_1 = function (mesh, light) {
  67027. var children = mesh.getChildren();
  67028. if (children.length !== 0) {
  67029. children.forEach(function (mesh) {
  67030. light.includedOnlyMeshes.push(mesh);
  67031. activateLightOnSubMeshes_1(mesh, light);
  67032. });
  67033. }
  67034. };
  67035. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  67036. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  67037. }
  67038. });
  67039. }
  67040. }
  67041. webVrController.attachToPoseControlledCamera(_this);
  67042. // since this is async - sanity check. Is the controller already stored?
  67043. if (_this.controllers.indexOf(webVrController) === -1) {
  67044. //add to the controllers array
  67045. _this.controllers.push(webVrController);
  67046. //did we find enough controllers? Great! let the developer know.
  67047. if (_this.controllers.length >= 2) {
  67048. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  67049. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  67050. // So we're overriding setting left & right manually to be sure
  67051. var firstViveWandDetected = false;
  67052. for (var i = 0; i < _this.controllers.length; i++) {
  67053. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  67054. if (!firstViveWandDetected) {
  67055. firstViveWandDetected = true;
  67056. _this.controllers[i].hand = "left";
  67057. }
  67058. else {
  67059. _this.controllers[i].hand = "right";
  67060. }
  67061. }
  67062. }
  67063. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  67064. }
  67065. }
  67066. }
  67067. });
  67068. };
  67069. return WebVRFreeCamera;
  67070. }(BABYLON.FreeCamera));
  67071. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  67072. })(BABYLON || (BABYLON = {}));
  67073. //# sourceMappingURL=babylon.webVRCamera.js.map
  67074. /// <reference path="babylon.freeCamera.ts" />
  67075. var BABYLON;
  67076. (function (BABYLON) {
  67077. // We're mainly based on the logic defined into the FreeCamera code
  67078. var DeviceOrientationCamera = (function (_super) {
  67079. __extends(DeviceOrientationCamera, _super);
  67080. function DeviceOrientationCamera(name, position, scene) {
  67081. var _this = _super.call(this, name, position, scene) || this;
  67082. _this._quaternionCache = new BABYLON.Quaternion();
  67083. _this.inputs.addDeviceOrientation();
  67084. return _this;
  67085. }
  67086. DeviceOrientationCamera.prototype.getClassName = function () {
  67087. return "DeviceOrientationCamera";
  67088. };
  67089. DeviceOrientationCamera.prototype._checkInputs = function () {
  67090. _super.prototype._checkInputs.call(this);
  67091. this._quaternionCache.copyFrom(this.rotationQuaternion);
  67092. if (this._initialQuaternion) {
  67093. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  67094. }
  67095. };
  67096. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  67097. var _this = this;
  67098. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  67099. //can only work if this camera has a rotation quaternion already.
  67100. if (!this.rotationQuaternion)
  67101. return;
  67102. if (!this._initialQuaternion) {
  67103. this._initialQuaternion = new BABYLON.Quaternion();
  67104. }
  67105. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  67106. ['x', 'y', 'z'].forEach(function (axisName) {
  67107. if (!axis[axisName]) {
  67108. _this._initialQuaternion[axisName] = 0;
  67109. }
  67110. else {
  67111. _this._initialQuaternion[axisName] *= -1;
  67112. }
  67113. });
  67114. this._initialQuaternion.normalize();
  67115. //force rotation update
  67116. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  67117. };
  67118. return DeviceOrientationCamera;
  67119. }(BABYLON.FreeCamera));
  67120. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  67121. })(BABYLON || (BABYLON = {}));
  67122. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  67123. var BABYLON;
  67124. (function (BABYLON) {
  67125. var VRDeviceOrientationFreeCamera = (function (_super) {
  67126. __extends(VRDeviceOrientationFreeCamera, _super);
  67127. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  67128. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67129. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67130. var _this = _super.call(this, name, position, scene) || this;
  67131. vrCameraMetrics.compensateDistortion = compensateDistortion;
  67132. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  67133. return _this;
  67134. }
  67135. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  67136. return "VRDeviceOrientationFreeCamera";
  67137. };
  67138. return VRDeviceOrientationFreeCamera;
  67139. }(BABYLON.DeviceOrientationCamera));
  67140. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  67141. var VRDeviceOrientationGamepadCamera = (function (_super) {
  67142. __extends(VRDeviceOrientationGamepadCamera, _super);
  67143. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  67144. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67145. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67146. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  67147. _this.inputs.addGamepad();
  67148. return _this;
  67149. }
  67150. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  67151. return "VRDeviceOrientationGamepadCamera";
  67152. };
  67153. return VRDeviceOrientationGamepadCamera;
  67154. }(VRDeviceOrientationFreeCamera));
  67155. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  67156. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  67157. __extends(VRDeviceOrientationArcRotateCamera, _super);
  67158. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  67159. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67160. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67161. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67162. vrCameraMetrics.compensateDistortion = compensateDistortion;
  67163. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  67164. _this.inputs.addVRDeviceOrientation();
  67165. return _this;
  67166. }
  67167. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  67168. return "VRDeviceOrientationArcRotateCamera";
  67169. };
  67170. return VRDeviceOrientationArcRotateCamera;
  67171. }(BABYLON.ArcRotateCamera));
  67172. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  67173. })(BABYLON || (BABYLON = {}));
  67174. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  67175. /// <reference path="babylon.freeCamera.ts" />
  67176. /// <reference path="babylon.arcRotateCamera.ts" />
  67177. /// <reference path="babylon.gamepadCamera.ts" />
  67178. /// <reference path="babylon.universalCamera.ts" />
  67179. var BABYLON;
  67180. (function (BABYLON) {
  67181. var AnaglyphFreeCamera = (function (_super) {
  67182. __extends(AnaglyphFreeCamera, _super);
  67183. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  67184. var _this = _super.call(this, name, position, scene) || this;
  67185. _this.interaxialDistance = interaxialDistance;
  67186. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67187. return _this;
  67188. }
  67189. AnaglyphFreeCamera.prototype.getClassName = function () {
  67190. return "AnaglyphFreeCamera";
  67191. };
  67192. return AnaglyphFreeCamera;
  67193. }(BABYLON.FreeCamera));
  67194. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  67195. var AnaglyphArcRotateCamera = (function (_super) {
  67196. __extends(AnaglyphArcRotateCamera, _super);
  67197. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  67198. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67199. _this.interaxialDistance = interaxialDistance;
  67200. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67201. return _this;
  67202. }
  67203. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  67204. return "AnaglyphArcRotateCamera";
  67205. };
  67206. return AnaglyphArcRotateCamera;
  67207. }(BABYLON.ArcRotateCamera));
  67208. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  67209. var AnaglyphGamepadCamera = (function (_super) {
  67210. __extends(AnaglyphGamepadCamera, _super);
  67211. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  67212. var _this = _super.call(this, name, position, scene) || this;
  67213. _this.interaxialDistance = interaxialDistance;
  67214. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67215. return _this;
  67216. }
  67217. AnaglyphGamepadCamera.prototype.getClassName = function () {
  67218. return "AnaglyphGamepadCamera";
  67219. };
  67220. return AnaglyphGamepadCamera;
  67221. }(BABYLON.GamepadCamera));
  67222. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  67223. var AnaglyphUniversalCamera = (function (_super) {
  67224. __extends(AnaglyphUniversalCamera, _super);
  67225. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  67226. var _this = _super.call(this, name, position, scene) || this;
  67227. _this.interaxialDistance = interaxialDistance;
  67228. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67229. return _this;
  67230. }
  67231. AnaglyphUniversalCamera.prototype.getClassName = function () {
  67232. return "AnaglyphUniversalCamera";
  67233. };
  67234. return AnaglyphUniversalCamera;
  67235. }(BABYLON.UniversalCamera));
  67236. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  67237. var StereoscopicFreeCamera = (function (_super) {
  67238. __extends(StereoscopicFreeCamera, _super);
  67239. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67240. var _this = _super.call(this, name, position, scene) || this;
  67241. _this.interaxialDistance = interaxialDistance;
  67242. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67243. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67244. return _this;
  67245. }
  67246. StereoscopicFreeCamera.prototype.getClassName = function () {
  67247. return "StereoscopicFreeCamera";
  67248. };
  67249. return StereoscopicFreeCamera;
  67250. }(BABYLON.FreeCamera));
  67251. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  67252. var StereoscopicArcRotateCamera = (function (_super) {
  67253. __extends(StereoscopicArcRotateCamera, _super);
  67254. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  67255. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67256. _this.interaxialDistance = interaxialDistance;
  67257. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67258. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67259. return _this;
  67260. }
  67261. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  67262. return "StereoscopicArcRotateCamera";
  67263. };
  67264. return StereoscopicArcRotateCamera;
  67265. }(BABYLON.ArcRotateCamera));
  67266. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  67267. var StereoscopicGamepadCamera = (function (_super) {
  67268. __extends(StereoscopicGamepadCamera, _super);
  67269. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67270. var _this = _super.call(this, name, position, scene) || this;
  67271. _this.interaxialDistance = interaxialDistance;
  67272. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67273. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67274. return _this;
  67275. }
  67276. StereoscopicGamepadCamera.prototype.getClassName = function () {
  67277. return "StereoscopicGamepadCamera";
  67278. };
  67279. return StereoscopicGamepadCamera;
  67280. }(BABYLON.GamepadCamera));
  67281. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  67282. var StereoscopicUniversalCamera = (function (_super) {
  67283. __extends(StereoscopicUniversalCamera, _super);
  67284. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67285. var _this = _super.call(this, name, position, scene) || this;
  67286. _this.interaxialDistance = interaxialDistance;
  67287. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67288. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67289. return _this;
  67290. }
  67291. StereoscopicUniversalCamera.prototype.getClassName = function () {
  67292. return "StereoscopicUniversalCamera";
  67293. };
  67294. return StereoscopicUniversalCamera;
  67295. }(BABYLON.UniversalCamera));
  67296. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  67297. })(BABYLON || (BABYLON = {}));
  67298. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  67299. var BABYLON;
  67300. (function (BABYLON) {
  67301. var VRExperienceHelper = (function () {
  67302. function VRExperienceHelper(scene, webVROptions) {
  67303. if (webVROptions === void 0) { webVROptions = {}; }
  67304. var _this = this;
  67305. this.webVROptions = webVROptions;
  67306. // Can the system support WebVR, even if a headset isn't plugged in?
  67307. this._webVRsupported = false;
  67308. // If WebVR is supported, is a headset plugged in and are we ready to present?
  67309. this._webVRready = false;
  67310. // Are we waiting for the requestPresent callback to complete?
  67311. this._webVRrequesting = false;
  67312. // Are we presenting to the headset right now?
  67313. this._webVRpresenting = false;
  67314. // Are we presenting in the fullscreen fallback?
  67315. this._fullscreenVRpresenting = false;
  67316. this._scene = scene;
  67317. if (!this._scene.activeCamera) {
  67318. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  67319. }
  67320. else {
  67321. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  67322. if (scene.activeCamera.rotation) {
  67323. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  67324. }
  67325. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  67326. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  67327. }
  67328. this._scene.activeCamera = this._deviceOrientationCamera;
  67329. this._position = this._scene.activeCamera.position;
  67330. this._canvas = scene.getEngine().getRenderingCanvas();
  67331. this._scene.activeCamera.attachControl(this._canvas);
  67332. this._btnVR = document.createElement("BUTTON");
  67333. this._btnVR.className = "babylonVRicon";
  67334. this._btnVR.id = "babylonVRiconbtn";
  67335. this._btnVR.title = "Click to switch to VR";
  67336. 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) }";
  67337. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  67338. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  67339. // css += ".babylonVRicon.vrdisplaysupported { }";
  67340. // css += ".babylonVRicon.vrdisplayready { }";
  67341. // css += ".babylonVRicon.vrdisplayrequesting { }";
  67342. var style = document.createElement('style');
  67343. style.appendChild(document.createTextNode(css));
  67344. document.getElementsByTagName('head')[0].appendChild(style);
  67345. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  67346. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  67347. this._btnVR.addEventListener("click", function () {
  67348. _this.enterVR();
  67349. });
  67350. window.addEventListener("resize", function () {
  67351. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  67352. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  67353. if (_this._fullscreenVRpresenting) {
  67354. _this.exitVR();
  67355. }
  67356. });
  67357. document.body.appendChild(this._btnVR);
  67358. // Exiting VR mode using 'ESC' key on desktop
  67359. this._onKeyDown = function (event) {
  67360. if (event.keyCode === 27 && _this.isInVRMode()) {
  67361. _this.exitVR();
  67362. }
  67363. };
  67364. document.addEventListener("keydown", this._onKeyDown);
  67365. // Exiting VR mode double tapping the touch screen
  67366. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  67367. if (_this.isInVRMode()) {
  67368. _this.exitVR();
  67369. }
  67370. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  67371. // Listen for WebVR display changes
  67372. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  67373. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  67374. this._onVRRequestPresentStart = function () {
  67375. _this._webVRrequesting = true;
  67376. _this.updateButtonVisibility();
  67377. };
  67378. this._onVRRequestPresentComplete = function (success) {
  67379. _this._webVRrequesting = false;
  67380. _this.updateButtonVisibility();
  67381. };
  67382. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  67383. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  67384. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  67385. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  67386. // Create the cameras
  67387. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  67388. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene);
  67389. this.updateButtonVisibility();
  67390. }
  67391. VRExperienceHelper.prototype.isInVRMode = function () {
  67392. return this._webVRpresenting || this._fullscreenVRpresenting;
  67393. };
  67394. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  67395. var vrDisplay = this._scene.getEngine().getVRDevice();
  67396. if (vrDisplay) {
  67397. var wasPresenting = this._webVRpresenting;
  67398. // A VR display is connected
  67399. this._webVRpresenting = vrDisplay.isPresenting;
  67400. if (wasPresenting && !this._webVRpresenting)
  67401. this.exitVR();
  67402. }
  67403. else {
  67404. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  67405. }
  67406. this.updateButtonVisibility();
  67407. };
  67408. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  67409. this._webVRsupported = eventArgs.vrSupported;
  67410. this._webVRready = !!eventArgs.vrDisplay;
  67411. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  67412. this.updateButtonVisibility();
  67413. };
  67414. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  67415. if (!this._btnVR) {
  67416. return;
  67417. }
  67418. this._btnVR.className = "babylonVRicon";
  67419. if (this.isInVRMode()) {
  67420. this._btnVR.className += " vrdisplaypresenting";
  67421. }
  67422. else {
  67423. if (this._webVRready)
  67424. this._btnVR.className += " vrdisplayready";
  67425. if (this._webVRsupported)
  67426. this._btnVR.className += " vrdisplaysupported";
  67427. if (this._webVRrequesting)
  67428. this._btnVR.className += " vrdisplayrequesting";
  67429. }
  67430. };
  67431. /**
  67432. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  67433. * Otherwise, will use the fullscreen API.
  67434. */
  67435. VRExperienceHelper.prototype.enterVR = function () {
  67436. if (this._webVRrequesting)
  67437. return;
  67438. // If WebVR is supported and a headset is connected
  67439. if (this._webVRready) {
  67440. if (!this._webVRpresenting) {
  67441. this._webVRCamera.position = this._position;
  67442. this._scene.activeCamera = this._webVRCamera;
  67443. }
  67444. }
  67445. else {
  67446. this._vrDeviceOrientationCamera.position = this._position;
  67447. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  67448. this._scene.getEngine().switchFullscreen(true);
  67449. this._fullscreenVRpresenting = true;
  67450. this.updateButtonVisibility();
  67451. }
  67452. this._scene.activeCamera.attachControl(this._canvas);
  67453. };
  67454. /**
  67455. * Attempt to exit VR, or fullscreen.
  67456. */
  67457. VRExperienceHelper.prototype.exitVR = function () {
  67458. if (this._webVRpresenting) {
  67459. this._scene.getEngine().disableVR();
  67460. }
  67461. if (this._scene.activeCamera) {
  67462. this._position = this._scene.activeCamera.position;
  67463. }
  67464. this._deviceOrientationCamera.position = this._position;
  67465. this._scene.activeCamera = this._deviceOrientationCamera;
  67466. this._scene.activeCamera.attachControl(this._canvas);
  67467. this._fullscreenVRpresenting = false;
  67468. this.updateButtonVisibility();
  67469. };
  67470. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  67471. get: function () {
  67472. return this._position;
  67473. },
  67474. set: function (value) {
  67475. this._position = value;
  67476. this._scene.activeCamera.position = value;
  67477. },
  67478. enumerable: true,
  67479. configurable: true
  67480. });
  67481. VRExperienceHelper.prototype.dispose = function () {
  67482. if (this.isInVRMode()) {
  67483. this.exitVR();
  67484. }
  67485. this._deviceOrientationCamera.dispose();
  67486. if (this._webVRCamera) {
  67487. this._webVRCamera.dispose();
  67488. }
  67489. if (this._vrDeviceOrientationCamera) {
  67490. this._vrDeviceOrientationCamera.dispose();
  67491. }
  67492. document.body.removeChild(this._btnVR);
  67493. document.removeEventListener("keydown", this._onKeyDown);
  67494. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  67495. };
  67496. VRExperienceHelper.prototype.getClassName = function () {
  67497. return "VRExperienceHelper";
  67498. };
  67499. return VRExperienceHelper;
  67500. }());
  67501. BABYLON.VRExperienceHelper = VRExperienceHelper;
  67502. })(BABYLON || (BABYLON = {}));
  67503. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  67504. // Mainly based on these 2 articles :
  67505. // 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
  67506. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  67507. var BABYLON;
  67508. (function (BABYLON) {
  67509. var JoystickAxis;
  67510. (function (JoystickAxis) {
  67511. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  67512. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  67513. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  67514. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  67515. var VirtualJoystick = (function () {
  67516. function VirtualJoystick(leftJoystick) {
  67517. var _this = this;
  67518. if (leftJoystick) {
  67519. this._leftJoystick = true;
  67520. }
  67521. else {
  67522. this._leftJoystick = false;
  67523. }
  67524. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  67525. VirtualJoystick._globalJoystickIndex++;
  67526. // By default left & right arrow keys are moving the X
  67527. // and up & down keys are moving the Y
  67528. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  67529. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  67530. this.reverseLeftRight = false;
  67531. this.reverseUpDown = false;
  67532. // collections of pointers
  67533. this._touches = new BABYLON.StringDictionary();
  67534. this.deltaPosition = BABYLON.Vector3.Zero();
  67535. this._joystickSensibility = 25;
  67536. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  67537. this._rotationSpeed = 25;
  67538. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  67539. this._rotateOnAxisRelativeToMesh = false;
  67540. this._onResize = function (evt) {
  67541. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  67542. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  67543. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  67544. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  67545. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  67546. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  67547. };
  67548. // injecting a canvas element on top of the canvas 3D game
  67549. if (!VirtualJoystick.vjCanvas) {
  67550. window.addEventListener("resize", this._onResize, false);
  67551. VirtualJoystick.vjCanvas = document.createElement("canvas");
  67552. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  67553. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  67554. VirtualJoystick.vjCanvas.width = window.innerWidth;
  67555. VirtualJoystick.vjCanvas.height = window.innerHeight;
  67556. VirtualJoystick.vjCanvas.style.width = "100%";
  67557. VirtualJoystick.vjCanvas.style.height = "100%";
  67558. VirtualJoystick.vjCanvas.style.position = "absolute";
  67559. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  67560. VirtualJoystick.vjCanvas.style.top = "0px";
  67561. VirtualJoystick.vjCanvas.style.left = "0px";
  67562. VirtualJoystick.vjCanvas.style.zIndex = "5";
  67563. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  67564. // Support for jQuery PEP polyfill
  67565. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  67566. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  67567. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  67568. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  67569. document.body.appendChild(VirtualJoystick.vjCanvas);
  67570. }
  67571. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  67572. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  67573. this.pressed = false;
  67574. // default joystick color
  67575. this._joystickColor = "cyan";
  67576. this._joystickPointerID = -1;
  67577. // current joystick position
  67578. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  67579. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  67580. // origin joystick position
  67581. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  67582. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  67583. this._onPointerDownHandlerRef = function (evt) {
  67584. _this._onPointerDown(evt);
  67585. };
  67586. this._onPointerMoveHandlerRef = function (evt) {
  67587. _this._onPointerMove(evt);
  67588. };
  67589. this._onPointerOutHandlerRef = function (evt) {
  67590. _this._onPointerUp(evt);
  67591. };
  67592. this._onPointerUpHandlerRef = function (evt) {
  67593. _this._onPointerUp(evt);
  67594. };
  67595. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  67596. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  67597. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  67598. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  67599. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  67600. evt.preventDefault(); // Disables system menu
  67601. }, false);
  67602. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  67603. }
  67604. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  67605. this._joystickSensibility = newJoystickSensibility;
  67606. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  67607. };
  67608. VirtualJoystick.prototype._onPointerDown = function (e) {
  67609. var positionOnScreenCondition;
  67610. e.preventDefault();
  67611. if (this._leftJoystick === true) {
  67612. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  67613. }
  67614. else {
  67615. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  67616. }
  67617. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  67618. // First contact will be dedicated to the virtual joystick
  67619. this._joystickPointerID = e.pointerId;
  67620. this._joystickPointerStartPos.x = e.clientX;
  67621. this._joystickPointerStartPos.y = e.clientY;
  67622. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  67623. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  67624. this._deltaJoystickVector.x = 0;
  67625. this._deltaJoystickVector.y = 0;
  67626. this.pressed = true;
  67627. this._touches.add(e.pointerId.toString(), e);
  67628. }
  67629. else {
  67630. // You can only trigger the action buttons with a joystick declared
  67631. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  67632. this._action();
  67633. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  67634. }
  67635. }
  67636. };
  67637. VirtualJoystick.prototype._onPointerMove = function (e) {
  67638. // If the current pointer is the one associated to the joystick (first touch contact)
  67639. if (this._joystickPointerID == e.pointerId) {
  67640. this._joystickPointerPos.x = e.clientX;
  67641. this._joystickPointerPos.y = e.clientY;
  67642. this._deltaJoystickVector = this._joystickPointerPos.clone();
  67643. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  67644. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  67645. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  67646. switch (this._axisTargetedByLeftAndRight) {
  67647. case JoystickAxis.X:
  67648. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  67649. break;
  67650. case JoystickAxis.Y:
  67651. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  67652. break;
  67653. case JoystickAxis.Z:
  67654. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  67655. break;
  67656. }
  67657. var directionUpDown = this.reverseUpDown ? 1 : -1;
  67658. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  67659. switch (this._axisTargetedByUpAndDown) {
  67660. case JoystickAxis.X:
  67661. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  67662. break;
  67663. case JoystickAxis.Y:
  67664. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  67665. break;
  67666. case JoystickAxis.Z:
  67667. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  67668. break;
  67669. }
  67670. }
  67671. else {
  67672. var data = this._touches.get(e.pointerId.toString());
  67673. if (data) {
  67674. data.x = e.clientX;
  67675. data.y = e.clientY;
  67676. }
  67677. }
  67678. };
  67679. VirtualJoystick.prototype._onPointerUp = function (e) {
  67680. if (this._joystickPointerID == e.pointerId) {
  67681. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  67682. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  67683. this._joystickPointerID = -1;
  67684. this.pressed = false;
  67685. }
  67686. else {
  67687. var touch = this._touches.get(e.pointerId.toString());
  67688. if (touch) {
  67689. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67690. }
  67691. }
  67692. this._deltaJoystickVector.x = 0;
  67693. this._deltaJoystickVector.y = 0;
  67694. this._touches.remove(e.pointerId.toString());
  67695. };
  67696. /**
  67697. * Change the color of the virtual joystick
  67698. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  67699. */
  67700. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  67701. this._joystickColor = newColor;
  67702. };
  67703. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  67704. this._action = action;
  67705. };
  67706. // Define which axis you'd like to control for left & right
  67707. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  67708. switch (axis) {
  67709. case JoystickAxis.X:
  67710. case JoystickAxis.Y:
  67711. case JoystickAxis.Z:
  67712. this._axisTargetedByLeftAndRight = axis;
  67713. break;
  67714. default:
  67715. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  67716. break;
  67717. }
  67718. };
  67719. // Define which axis you'd like to control for up & down
  67720. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  67721. switch (axis) {
  67722. case JoystickAxis.X:
  67723. case JoystickAxis.Y:
  67724. case JoystickAxis.Z:
  67725. this._axisTargetedByUpAndDown = axis;
  67726. break;
  67727. default:
  67728. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  67729. break;
  67730. }
  67731. };
  67732. VirtualJoystick.prototype._clearCanvas = function () {
  67733. if (this._leftJoystick) {
  67734. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  67735. }
  67736. else {
  67737. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  67738. }
  67739. };
  67740. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  67741. var _this = this;
  67742. if (this.pressed) {
  67743. this._touches.forEach(function (key, touch) {
  67744. if (touch.pointerId === _this._joystickPointerID) {
  67745. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  67746. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  67747. VirtualJoystick.vjCanvasContext.beginPath();
  67748. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67749. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67750. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  67751. VirtualJoystick.vjCanvasContext.stroke();
  67752. VirtualJoystick.vjCanvasContext.closePath();
  67753. VirtualJoystick.vjCanvasContext.beginPath();
  67754. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67755. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  67756. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  67757. VirtualJoystick.vjCanvasContext.stroke();
  67758. VirtualJoystick.vjCanvasContext.closePath();
  67759. VirtualJoystick.vjCanvasContext.beginPath();
  67760. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  67761. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  67762. VirtualJoystick.vjCanvasContext.stroke();
  67763. VirtualJoystick.vjCanvasContext.closePath();
  67764. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  67765. }
  67766. else {
  67767. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  67768. VirtualJoystick.vjCanvasContext.beginPath();
  67769. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  67770. VirtualJoystick.vjCanvasContext.beginPath();
  67771. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  67772. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  67773. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  67774. VirtualJoystick.vjCanvasContext.stroke();
  67775. VirtualJoystick.vjCanvasContext.closePath();
  67776. touch.prevX = touch.x;
  67777. touch.prevY = touch.y;
  67778. }
  67779. ;
  67780. });
  67781. }
  67782. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  67783. };
  67784. VirtualJoystick.prototype.releaseCanvas = function () {
  67785. if (VirtualJoystick.vjCanvas) {
  67786. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  67787. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  67788. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  67789. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  67790. window.removeEventListener("resize", this._onResize);
  67791. document.body.removeChild(VirtualJoystick.vjCanvas);
  67792. VirtualJoystick.vjCanvas = null;
  67793. }
  67794. };
  67795. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  67796. VirtualJoystick._globalJoystickIndex = 0;
  67797. return VirtualJoystick;
  67798. }());
  67799. BABYLON.VirtualJoystick = VirtualJoystick;
  67800. })(BABYLON || (BABYLON = {}));
  67801. //# sourceMappingURL=babylon.virtualJoystick.js.map
  67802. var BABYLON;
  67803. (function (BABYLON) {
  67804. // We're mainly based on the logic defined into the FreeCamera code
  67805. var VirtualJoysticksCamera = (function (_super) {
  67806. __extends(VirtualJoysticksCamera, _super);
  67807. function VirtualJoysticksCamera(name, position, scene) {
  67808. var _this = _super.call(this, name, position, scene) || this;
  67809. _this.inputs.addVirtualJoystick();
  67810. return _this;
  67811. }
  67812. VirtualJoysticksCamera.prototype.getClassName = function () {
  67813. return "VirtualJoysticksCamera";
  67814. };
  67815. return VirtualJoysticksCamera;
  67816. }(BABYLON.FreeCamera));
  67817. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  67818. })(BABYLON || (BABYLON = {}));
  67819. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  67820. var BABYLON;
  67821. (function (BABYLON) {
  67822. var FreeCameraVirtualJoystickInput = (function () {
  67823. function FreeCameraVirtualJoystickInput() {
  67824. }
  67825. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  67826. return this._leftjoystick;
  67827. };
  67828. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  67829. return this._rightjoystick;
  67830. };
  67831. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  67832. if (this._leftjoystick) {
  67833. var camera = this.camera;
  67834. var speed = camera._computeLocalCameraSpeed() * 50;
  67835. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  67836. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  67837. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  67838. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  67839. if (!this._leftjoystick.pressed) {
  67840. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  67841. }
  67842. if (!this._rightjoystick.pressed) {
  67843. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  67844. }
  67845. }
  67846. };
  67847. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  67848. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  67849. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  67850. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  67851. this._leftjoystick.setJoystickSensibility(0.15);
  67852. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  67853. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  67854. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  67855. this._rightjoystick.reverseUpDown = true;
  67856. this._rightjoystick.setJoystickSensibility(0.05);
  67857. this._rightjoystick.setJoystickColor("yellow");
  67858. };
  67859. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  67860. this._leftjoystick.releaseCanvas();
  67861. this._rightjoystick.releaseCanvas();
  67862. };
  67863. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  67864. return "FreeCameraVirtualJoystickInput";
  67865. };
  67866. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  67867. return "virtualJoystick";
  67868. };
  67869. return FreeCameraVirtualJoystickInput;
  67870. }());
  67871. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  67872. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  67873. })(BABYLON || (BABYLON = {}));
  67874. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  67875. var BABYLON;
  67876. (function (BABYLON) {
  67877. var SimplificationSettings = (function () {
  67878. function SimplificationSettings(quality, distance, optimizeMesh) {
  67879. this.quality = quality;
  67880. this.distance = distance;
  67881. this.optimizeMesh = optimizeMesh;
  67882. }
  67883. return SimplificationSettings;
  67884. }());
  67885. BABYLON.SimplificationSettings = SimplificationSettings;
  67886. var SimplificationQueue = (function () {
  67887. function SimplificationQueue() {
  67888. this.running = false;
  67889. this._simplificationArray = [];
  67890. }
  67891. SimplificationQueue.prototype.addTask = function (task) {
  67892. this._simplificationArray.push(task);
  67893. };
  67894. SimplificationQueue.prototype.executeNext = function () {
  67895. var task = this._simplificationArray.pop();
  67896. if (task) {
  67897. this.running = true;
  67898. this.runSimplification(task);
  67899. }
  67900. else {
  67901. this.running = false;
  67902. }
  67903. };
  67904. SimplificationQueue.prototype.runSimplification = function (task) {
  67905. var _this = this;
  67906. if (task.parallelProcessing) {
  67907. //parallel simplifier
  67908. task.settings.forEach(function (setting) {
  67909. var simplifier = _this.getSimplifier(task);
  67910. simplifier.simplify(setting, function (newMesh) {
  67911. task.mesh.addLODLevel(setting.distance, newMesh);
  67912. newMesh.isVisible = true;
  67913. //check if it is the last
  67914. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  67915. //all done, run the success callback.
  67916. task.successCallback();
  67917. }
  67918. _this.executeNext();
  67919. });
  67920. });
  67921. }
  67922. else {
  67923. //single simplifier.
  67924. var simplifier = this.getSimplifier(task);
  67925. var runDecimation = function (setting, callback) {
  67926. simplifier.simplify(setting, function (newMesh) {
  67927. task.mesh.addLODLevel(setting.distance, newMesh);
  67928. newMesh.isVisible = true;
  67929. //run the next quality level
  67930. callback();
  67931. });
  67932. };
  67933. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  67934. runDecimation(task.settings[loop.index], function () {
  67935. loop.executeNext();
  67936. });
  67937. }, function () {
  67938. //execution ended, run the success callback.
  67939. if (task.successCallback) {
  67940. task.successCallback();
  67941. }
  67942. _this.executeNext();
  67943. });
  67944. }
  67945. };
  67946. SimplificationQueue.prototype.getSimplifier = function (task) {
  67947. switch (task.simplificationType) {
  67948. case SimplificationType.QUADRATIC:
  67949. default:
  67950. return new QuadraticErrorSimplification(task.mesh);
  67951. }
  67952. };
  67953. return SimplificationQueue;
  67954. }());
  67955. BABYLON.SimplificationQueue = SimplificationQueue;
  67956. /**
  67957. * The implemented types of simplification.
  67958. * At the moment only Quadratic Error Decimation is implemented.
  67959. */
  67960. var SimplificationType;
  67961. (function (SimplificationType) {
  67962. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  67963. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  67964. var DecimationTriangle = (function () {
  67965. function DecimationTriangle(vertices) {
  67966. this.vertices = vertices;
  67967. this.error = new Array(4);
  67968. this.deleted = false;
  67969. this.isDirty = false;
  67970. this.deletePending = false;
  67971. this.borderFactor = 0;
  67972. }
  67973. return DecimationTriangle;
  67974. }());
  67975. BABYLON.DecimationTriangle = DecimationTriangle;
  67976. var DecimationVertex = (function () {
  67977. function DecimationVertex(position, id) {
  67978. this.position = position;
  67979. this.id = id;
  67980. this.isBorder = true;
  67981. this.q = new QuadraticMatrix();
  67982. this.triangleCount = 0;
  67983. this.triangleStart = 0;
  67984. this.originalOffsets = [];
  67985. }
  67986. DecimationVertex.prototype.updatePosition = function (newPosition) {
  67987. this.position.copyFrom(newPosition);
  67988. };
  67989. return DecimationVertex;
  67990. }());
  67991. BABYLON.DecimationVertex = DecimationVertex;
  67992. var QuadraticMatrix = (function () {
  67993. function QuadraticMatrix(data) {
  67994. this.data = new Array(10);
  67995. for (var i = 0; i < 10; ++i) {
  67996. if (data && data[i]) {
  67997. this.data[i] = data[i];
  67998. }
  67999. else {
  68000. this.data[i] = 0;
  68001. }
  68002. }
  68003. }
  68004. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  68005. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  68006. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  68007. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  68008. return det;
  68009. };
  68010. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  68011. for (var i = 0; i < 10; ++i) {
  68012. this.data[i] += matrix.data[i];
  68013. }
  68014. };
  68015. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  68016. for (var i = 0; i < 10; ++i) {
  68017. this.data[i] += data[i];
  68018. }
  68019. };
  68020. QuadraticMatrix.prototype.add = function (matrix) {
  68021. var m = new QuadraticMatrix();
  68022. for (var i = 0; i < 10; ++i) {
  68023. m.data[i] = this.data[i] + matrix.data[i];
  68024. }
  68025. return m;
  68026. };
  68027. QuadraticMatrix.FromData = function (a, b, c, d) {
  68028. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  68029. };
  68030. //returning an array to avoid garbage collection
  68031. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  68032. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  68033. };
  68034. return QuadraticMatrix;
  68035. }());
  68036. BABYLON.QuadraticMatrix = QuadraticMatrix;
  68037. var Reference = (function () {
  68038. function Reference(vertexId, triangleId) {
  68039. this.vertexId = vertexId;
  68040. this.triangleId = triangleId;
  68041. }
  68042. return Reference;
  68043. }());
  68044. BABYLON.Reference = Reference;
  68045. /**
  68046. * An implementation of the Quadratic Error simplification algorithm.
  68047. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  68048. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  68049. * @author RaananW
  68050. */
  68051. var QuadraticErrorSimplification = (function () {
  68052. function QuadraticErrorSimplification(_mesh) {
  68053. this._mesh = _mesh;
  68054. this.initialized = false;
  68055. this.syncIterations = 5000;
  68056. this.aggressiveness = 7;
  68057. this.decimationIterations = 100;
  68058. this.boundingBoxEpsilon = BABYLON.Epsilon;
  68059. }
  68060. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  68061. var _this = this;
  68062. this.initDecimatedMesh();
  68063. //iterating through the submeshes array, one after the other.
  68064. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  68065. _this.initWithMesh(loop.index, function () {
  68066. _this.runDecimation(settings, loop.index, function () {
  68067. loop.executeNext();
  68068. });
  68069. }, settings.optimizeMesh);
  68070. }, function () {
  68071. setTimeout(function () {
  68072. successCallback(_this._reconstructedMesh);
  68073. }, 0);
  68074. });
  68075. };
  68076. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  68077. var _this = this;
  68078. var gCount = 0;
  68079. triangle.vertices.forEach(function (vertex) {
  68080. var count = 0;
  68081. var vPos = vertex.position;
  68082. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  68083. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  68084. ++count;
  68085. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  68086. ++count;
  68087. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  68088. ++count;
  68089. if (count > 1) {
  68090. ++gCount;
  68091. }
  68092. ;
  68093. });
  68094. if (gCount > 1) {
  68095. console.log(triangle, gCount);
  68096. }
  68097. return gCount > 1;
  68098. };
  68099. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  68100. var _this = this;
  68101. var targetCount = ~~(this.triangles.length * settings.quality);
  68102. var deletedTriangles = 0;
  68103. var triangleCount = this.triangles.length;
  68104. var iterationFunction = function (iteration, callback) {
  68105. setTimeout(function () {
  68106. if (iteration % 5 === 0) {
  68107. _this.updateMesh(iteration === 0);
  68108. }
  68109. for (var i = 0; i < _this.triangles.length; ++i) {
  68110. _this.triangles[i].isDirty = false;
  68111. }
  68112. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  68113. var trianglesIterator = function (i) {
  68114. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  68115. var t = _this.triangles[tIdx];
  68116. if (!t)
  68117. return;
  68118. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  68119. return;
  68120. }
  68121. for (var j = 0; j < 3; ++j) {
  68122. if (t.error[j] < threshold) {
  68123. var deleted0 = [];
  68124. var deleted1 = [];
  68125. var v0 = t.vertices[j];
  68126. var v1 = t.vertices[(j + 1) % 3];
  68127. if (v0.isBorder || v1.isBorder)
  68128. continue;
  68129. var p = BABYLON.Vector3.Zero();
  68130. var n = BABYLON.Vector3.Zero();
  68131. var uv = BABYLON.Vector2.Zero();
  68132. var color = new BABYLON.Color4(0, 0, 0, 1);
  68133. _this.calculateError(v0, v1, p, n, uv, color);
  68134. var delTr = [];
  68135. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  68136. continue;
  68137. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  68138. continue;
  68139. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  68140. continue;
  68141. var uniqueArray = [];
  68142. delTr.forEach(function (deletedT) {
  68143. if (uniqueArray.indexOf(deletedT) === -1) {
  68144. deletedT.deletePending = true;
  68145. uniqueArray.push(deletedT);
  68146. }
  68147. });
  68148. if (uniqueArray.length % 2 !== 0) {
  68149. continue;
  68150. }
  68151. v0.q = v1.q.add(v0.q);
  68152. v0.updatePosition(p);
  68153. var tStart = _this.references.length;
  68154. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  68155. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  68156. var tCount = _this.references.length - tStart;
  68157. if (tCount <= v0.triangleCount) {
  68158. if (tCount) {
  68159. for (var c = 0; c < tCount; c++) {
  68160. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  68161. }
  68162. }
  68163. }
  68164. else {
  68165. v0.triangleStart = tStart;
  68166. }
  68167. v0.triangleCount = tCount;
  68168. break;
  68169. }
  68170. }
  68171. };
  68172. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  68173. }, 0);
  68174. };
  68175. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  68176. if (triangleCount - deletedTriangles <= targetCount)
  68177. loop.breakLoop();
  68178. else {
  68179. iterationFunction(loop.index, function () {
  68180. loop.executeNext();
  68181. });
  68182. }
  68183. }, function () {
  68184. setTimeout(function () {
  68185. //reconstruct this part of the mesh
  68186. _this.reconstructMesh(submeshIndex);
  68187. successCallback();
  68188. }, 0);
  68189. });
  68190. };
  68191. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  68192. var _this = this;
  68193. this.vertices = [];
  68194. this.triangles = [];
  68195. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68196. var indices = this._mesh.getIndices();
  68197. var submesh = this._mesh.subMeshes[submeshIndex];
  68198. var findInVertices = function (positionToSearch) {
  68199. if (optimizeMesh) {
  68200. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  68201. if (_this.vertices[ii].position.equals(positionToSearch)) {
  68202. return _this.vertices[ii];
  68203. }
  68204. }
  68205. }
  68206. return null;
  68207. };
  68208. var vertexReferences = [];
  68209. var vertexInit = function (i) {
  68210. var offset = i + submesh.verticesStart;
  68211. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  68212. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  68213. vertex.originalOffsets.push(offset);
  68214. if (vertex.id === _this.vertices.length) {
  68215. _this.vertices.push(vertex);
  68216. }
  68217. vertexReferences.push(vertex.id);
  68218. };
  68219. //var totalVertices = mesh.getTotalVertices();
  68220. var totalVertices = submesh.verticesCount;
  68221. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  68222. var indicesInit = function (i) {
  68223. var offset = (submesh.indexStart / 3) + i;
  68224. var pos = (offset * 3);
  68225. var i0 = indices[pos + 0];
  68226. var i1 = indices[pos + 1];
  68227. var i2 = indices[pos + 2];
  68228. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  68229. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  68230. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  68231. var triangle = new DecimationTriangle([v0, v1, v2]);
  68232. triangle.originalOffset = pos;
  68233. _this.triangles.push(triangle);
  68234. };
  68235. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  68236. _this.init(callback);
  68237. });
  68238. });
  68239. };
  68240. QuadraticErrorSimplification.prototype.init = function (callback) {
  68241. var _this = this;
  68242. var triangleInit1 = function (i) {
  68243. var t = _this.triangles[i];
  68244. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  68245. for (var j = 0; j < 3; j++) {
  68246. 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))));
  68247. }
  68248. };
  68249. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  68250. var triangleInit2 = function (i) {
  68251. var t = _this.triangles[i];
  68252. for (var j = 0; j < 3; ++j) {
  68253. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  68254. }
  68255. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  68256. };
  68257. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  68258. _this.initialized = true;
  68259. callback();
  68260. });
  68261. });
  68262. };
  68263. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  68264. var newTriangles = [];
  68265. var i;
  68266. for (i = 0; i < this.vertices.length; ++i) {
  68267. this.vertices[i].triangleCount = 0;
  68268. }
  68269. var t;
  68270. var j;
  68271. for (i = 0; i < this.triangles.length; ++i) {
  68272. if (!this.triangles[i].deleted) {
  68273. t = this.triangles[i];
  68274. for (j = 0; j < 3; ++j) {
  68275. t.vertices[j].triangleCount = 1;
  68276. }
  68277. newTriangles.push(t);
  68278. }
  68279. }
  68280. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  68281. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  68282. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  68283. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  68284. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68285. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68286. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68287. var vertexCount = 0;
  68288. for (i = 0; i < this.vertices.length; ++i) {
  68289. var vertex = this.vertices[i];
  68290. vertex.id = vertexCount;
  68291. if (vertex.triangleCount) {
  68292. vertex.originalOffsets.forEach(function (originalOffset) {
  68293. newPositionData.push(vertex.position.x);
  68294. newPositionData.push(vertex.position.y);
  68295. newPositionData.push(vertex.position.z);
  68296. newNormalData.push(normalData[originalOffset * 3]);
  68297. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  68298. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  68299. if (uvs && uvs.length) {
  68300. newUVsData.push(uvs[(originalOffset * 2)]);
  68301. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  68302. }
  68303. else if (colorsData && colorsData.length) {
  68304. newColorsData.push(colorsData[(originalOffset * 4)]);
  68305. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  68306. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  68307. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  68308. }
  68309. ++vertexCount;
  68310. });
  68311. }
  68312. }
  68313. var startingIndex = this._reconstructedMesh.getTotalIndices();
  68314. var startingVertex = this._reconstructedMesh.getTotalVertices();
  68315. var submeshesArray = this._reconstructedMesh.subMeshes;
  68316. this._reconstructedMesh.subMeshes = [];
  68317. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  68318. var originalIndices = this._mesh.getIndices();
  68319. for (i = 0; i < newTriangles.length; ++i) {
  68320. t = newTriangles[i]; //now get the new referencing point for each vertex
  68321. [0, 1, 2].forEach(function (idx) {
  68322. var id = originalIndices[t.originalOffset + idx];
  68323. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  68324. if (offset < 0)
  68325. offset = 0;
  68326. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  68327. });
  68328. }
  68329. //overwriting the old vertex buffers and indices.
  68330. this._reconstructedMesh.setIndices(newIndicesArray);
  68331. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  68332. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  68333. if (newUVsData.length > 0)
  68334. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  68335. if (newColorsData.length > 0)
  68336. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  68337. //create submesh
  68338. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  68339. if (submeshIndex > 0) {
  68340. this._reconstructedMesh.subMeshes = [];
  68341. submeshesArray.forEach(function (submesh) {
  68342. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  68343. });
  68344. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  68345. }
  68346. };
  68347. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  68348. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  68349. this._reconstructedMesh.material = this._mesh.material;
  68350. this._reconstructedMesh.parent = this._mesh.parent;
  68351. this._reconstructedMesh.isVisible = false;
  68352. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  68353. };
  68354. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  68355. for (var i = 0; i < vertex1.triangleCount; ++i) {
  68356. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  68357. if (t.deleted)
  68358. continue;
  68359. var s = this.references[vertex1.triangleStart + i].vertexId;
  68360. var v1 = t.vertices[(s + 1) % 3];
  68361. var v2 = t.vertices[(s + 2) % 3];
  68362. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  68363. deletedArray[i] = true;
  68364. delTr.push(t);
  68365. continue;
  68366. }
  68367. var d1 = v1.position.subtract(point);
  68368. d1 = d1.normalize();
  68369. var d2 = v2.position.subtract(point);
  68370. d2 = d2.normalize();
  68371. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  68372. return true;
  68373. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  68374. deletedArray[i] = false;
  68375. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  68376. return true;
  68377. }
  68378. return false;
  68379. };
  68380. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  68381. var newDeleted = deletedTriangles;
  68382. for (var i = 0; i < vertex.triangleCount; ++i) {
  68383. var ref = this.references[vertex.triangleStart + i];
  68384. var t = this.triangles[ref.triangleId];
  68385. if (t.deleted)
  68386. continue;
  68387. if (deletedArray[i] && t.deletePending) {
  68388. t.deleted = true;
  68389. newDeleted++;
  68390. continue;
  68391. }
  68392. t.vertices[ref.vertexId] = origVertex;
  68393. t.isDirty = true;
  68394. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  68395. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  68396. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  68397. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  68398. this.references.push(ref);
  68399. }
  68400. return newDeleted;
  68401. };
  68402. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  68403. for (var i = 0; i < this.vertices.length; ++i) {
  68404. var vCount = [];
  68405. var vId = [];
  68406. var v = this.vertices[i];
  68407. var j;
  68408. for (j = 0; j < v.triangleCount; ++j) {
  68409. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  68410. for (var ii = 0; ii < 3; ii++) {
  68411. var ofs = 0;
  68412. var vv = triangle.vertices[ii];
  68413. while (ofs < vCount.length) {
  68414. if (vId[ofs] === vv.id)
  68415. break;
  68416. ++ofs;
  68417. }
  68418. if (ofs === vCount.length) {
  68419. vCount.push(1);
  68420. vId.push(vv.id);
  68421. }
  68422. else {
  68423. vCount[ofs]++;
  68424. }
  68425. }
  68426. }
  68427. for (j = 0; j < vCount.length; ++j) {
  68428. if (vCount[j] === 1) {
  68429. this.vertices[vId[j]].isBorder = true;
  68430. }
  68431. else {
  68432. this.vertices[vId[j]].isBorder = false;
  68433. }
  68434. }
  68435. }
  68436. };
  68437. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  68438. if (identifyBorders === void 0) { identifyBorders = false; }
  68439. var i;
  68440. if (!identifyBorders) {
  68441. var newTrianglesVector = [];
  68442. for (i = 0; i < this.triangles.length; ++i) {
  68443. if (!this.triangles[i].deleted) {
  68444. newTrianglesVector.push(this.triangles[i]);
  68445. }
  68446. }
  68447. this.triangles = newTrianglesVector;
  68448. }
  68449. for (i = 0; i < this.vertices.length; ++i) {
  68450. this.vertices[i].triangleCount = 0;
  68451. this.vertices[i].triangleStart = 0;
  68452. }
  68453. var t;
  68454. var j;
  68455. var v;
  68456. for (i = 0; i < this.triangles.length; ++i) {
  68457. t = this.triangles[i];
  68458. for (j = 0; j < 3; ++j) {
  68459. v = t.vertices[j];
  68460. v.triangleCount++;
  68461. }
  68462. }
  68463. var tStart = 0;
  68464. for (i = 0; i < this.vertices.length; ++i) {
  68465. this.vertices[i].triangleStart = tStart;
  68466. tStart += this.vertices[i].triangleCount;
  68467. this.vertices[i].triangleCount = 0;
  68468. }
  68469. var newReferences = new Array(this.triangles.length * 3);
  68470. for (i = 0; i < this.triangles.length; ++i) {
  68471. t = this.triangles[i];
  68472. for (j = 0; j < 3; ++j) {
  68473. v = t.vertices[j];
  68474. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  68475. v.triangleCount++;
  68476. }
  68477. }
  68478. this.references = newReferences;
  68479. if (identifyBorders) {
  68480. this.identifyBorder();
  68481. }
  68482. };
  68483. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  68484. var x = point.x;
  68485. var y = point.y;
  68486. var z = point.z;
  68487. 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
  68488. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  68489. };
  68490. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  68491. var q = vertex1.q.add(vertex2.q);
  68492. var border = vertex1.isBorder && vertex2.isBorder;
  68493. var error = 0;
  68494. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  68495. if (qDet !== 0 && !border) {
  68496. if (!pointResult) {
  68497. pointResult = BABYLON.Vector3.Zero();
  68498. }
  68499. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  68500. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  68501. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  68502. error = this.vertexError(q, pointResult);
  68503. }
  68504. else {
  68505. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  68506. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  68507. var error1 = this.vertexError(q, vertex1.position);
  68508. var error2 = this.vertexError(q, vertex2.position);
  68509. var error3 = this.vertexError(q, p3);
  68510. error = Math.min(error1, error2, error3);
  68511. if (error === error1) {
  68512. if (pointResult) {
  68513. pointResult.copyFrom(vertex1.position);
  68514. }
  68515. }
  68516. else if (error === error2) {
  68517. if (pointResult) {
  68518. pointResult.copyFrom(vertex2.position);
  68519. }
  68520. }
  68521. else {
  68522. if (pointResult) {
  68523. pointResult.copyFrom(p3);
  68524. }
  68525. }
  68526. }
  68527. return error;
  68528. };
  68529. return QuadraticErrorSimplification;
  68530. }());
  68531. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  68532. })(BABYLON || (BABYLON = {}));
  68533. //# sourceMappingURL=babylon.meshSimplification.js.map
  68534. var BABYLON;
  68535. (function (BABYLON) {
  68536. var Internals;
  68537. (function (Internals) {
  68538. var MeshLODLevel = (function () {
  68539. function MeshLODLevel(distance, mesh) {
  68540. this.distance = distance;
  68541. this.mesh = mesh;
  68542. }
  68543. return MeshLODLevel;
  68544. }());
  68545. Internals.MeshLODLevel = MeshLODLevel;
  68546. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68547. })(BABYLON || (BABYLON = {}));
  68548. //# sourceMappingURL=babylon.meshLODLevel.js.map
  68549. var BABYLON;
  68550. (function (BABYLON) {
  68551. // Standard optimizations
  68552. var SceneOptimization = (function () {
  68553. function SceneOptimization(priority) {
  68554. if (priority === void 0) { priority = 0; }
  68555. this.priority = priority;
  68556. this.apply = function (scene) {
  68557. return true; // Return true if everything that can be done was applied
  68558. };
  68559. }
  68560. return SceneOptimization;
  68561. }());
  68562. BABYLON.SceneOptimization = SceneOptimization;
  68563. var TextureOptimization = (function (_super) {
  68564. __extends(TextureOptimization, _super);
  68565. function TextureOptimization(priority, maximumSize) {
  68566. if (priority === void 0) { priority = 0; }
  68567. if (maximumSize === void 0) { maximumSize = 1024; }
  68568. var _this = _super.call(this, priority) || this;
  68569. _this.priority = priority;
  68570. _this.maximumSize = maximumSize;
  68571. _this.apply = function (scene) {
  68572. var allDone = true;
  68573. for (var index = 0; index < scene.textures.length; index++) {
  68574. var texture = scene.textures[index];
  68575. if (!texture.canRescale || texture.getContext) {
  68576. continue;
  68577. }
  68578. var currentSize = texture.getSize();
  68579. var maxDimension = Math.max(currentSize.width, currentSize.height);
  68580. if (maxDimension > _this.maximumSize) {
  68581. texture.scale(0.5);
  68582. allDone = false;
  68583. }
  68584. }
  68585. return allDone;
  68586. };
  68587. return _this;
  68588. }
  68589. return TextureOptimization;
  68590. }(SceneOptimization));
  68591. BABYLON.TextureOptimization = TextureOptimization;
  68592. var HardwareScalingOptimization = (function (_super) {
  68593. __extends(HardwareScalingOptimization, _super);
  68594. function HardwareScalingOptimization(priority, maximumScale) {
  68595. if (priority === void 0) { priority = 0; }
  68596. if (maximumScale === void 0) { maximumScale = 2; }
  68597. var _this = _super.call(this, priority) || this;
  68598. _this.priority = priority;
  68599. _this.maximumScale = maximumScale;
  68600. _this._currentScale = 1;
  68601. _this.apply = function (scene) {
  68602. _this._currentScale++;
  68603. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  68604. return _this._currentScale >= _this.maximumScale;
  68605. };
  68606. return _this;
  68607. }
  68608. return HardwareScalingOptimization;
  68609. }(SceneOptimization));
  68610. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  68611. var ShadowsOptimization = (function (_super) {
  68612. __extends(ShadowsOptimization, _super);
  68613. function ShadowsOptimization() {
  68614. var _this = _super !== null && _super.apply(this, arguments) || this;
  68615. _this.apply = function (scene) {
  68616. scene.shadowsEnabled = false;
  68617. return true;
  68618. };
  68619. return _this;
  68620. }
  68621. return ShadowsOptimization;
  68622. }(SceneOptimization));
  68623. BABYLON.ShadowsOptimization = ShadowsOptimization;
  68624. var PostProcessesOptimization = (function (_super) {
  68625. __extends(PostProcessesOptimization, _super);
  68626. function PostProcessesOptimization() {
  68627. var _this = _super !== null && _super.apply(this, arguments) || this;
  68628. _this.apply = function (scene) {
  68629. scene.postProcessesEnabled = false;
  68630. return true;
  68631. };
  68632. return _this;
  68633. }
  68634. return PostProcessesOptimization;
  68635. }(SceneOptimization));
  68636. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  68637. var LensFlaresOptimization = (function (_super) {
  68638. __extends(LensFlaresOptimization, _super);
  68639. function LensFlaresOptimization() {
  68640. var _this = _super !== null && _super.apply(this, arguments) || this;
  68641. _this.apply = function (scene) {
  68642. scene.lensFlaresEnabled = false;
  68643. return true;
  68644. };
  68645. return _this;
  68646. }
  68647. return LensFlaresOptimization;
  68648. }(SceneOptimization));
  68649. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  68650. var ParticlesOptimization = (function (_super) {
  68651. __extends(ParticlesOptimization, _super);
  68652. function ParticlesOptimization() {
  68653. var _this = _super !== null && _super.apply(this, arguments) || this;
  68654. _this.apply = function (scene) {
  68655. scene.particlesEnabled = false;
  68656. return true;
  68657. };
  68658. return _this;
  68659. }
  68660. return ParticlesOptimization;
  68661. }(SceneOptimization));
  68662. BABYLON.ParticlesOptimization = ParticlesOptimization;
  68663. var RenderTargetsOptimization = (function (_super) {
  68664. __extends(RenderTargetsOptimization, _super);
  68665. function RenderTargetsOptimization() {
  68666. var _this = _super !== null && _super.apply(this, arguments) || this;
  68667. _this.apply = function (scene) {
  68668. scene.renderTargetsEnabled = false;
  68669. return true;
  68670. };
  68671. return _this;
  68672. }
  68673. return RenderTargetsOptimization;
  68674. }(SceneOptimization));
  68675. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  68676. var MergeMeshesOptimization = (function (_super) {
  68677. __extends(MergeMeshesOptimization, _super);
  68678. function MergeMeshesOptimization() {
  68679. var _this = _super !== null && _super.apply(this, arguments) || this;
  68680. _this._canBeMerged = function (abstractMesh) {
  68681. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  68682. return false;
  68683. }
  68684. var mesh = abstractMesh;
  68685. if (!mesh.isVisible || !mesh.isEnabled()) {
  68686. return false;
  68687. }
  68688. if (mesh.instances.length > 0) {
  68689. return false;
  68690. }
  68691. if (mesh.skeleton || mesh.hasLODLevels) {
  68692. return false;
  68693. }
  68694. if (mesh.parent) {
  68695. return false;
  68696. }
  68697. return true;
  68698. };
  68699. _this.apply = function (scene, updateSelectionTree) {
  68700. var globalPool = scene.meshes.slice(0);
  68701. var globalLength = globalPool.length;
  68702. for (var index = 0; index < globalLength; index++) {
  68703. var currentPool = new Array();
  68704. var current = globalPool[index];
  68705. // Checks
  68706. if (!_this._canBeMerged(current)) {
  68707. continue;
  68708. }
  68709. currentPool.push(current);
  68710. // Find compatible meshes
  68711. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  68712. var otherMesh = globalPool[subIndex];
  68713. if (!_this._canBeMerged(otherMesh)) {
  68714. continue;
  68715. }
  68716. if (otherMesh.material !== current.material) {
  68717. continue;
  68718. }
  68719. if (otherMesh.checkCollisions !== current.checkCollisions) {
  68720. continue;
  68721. }
  68722. currentPool.push(otherMesh);
  68723. globalLength--;
  68724. globalPool.splice(subIndex, 1);
  68725. subIndex--;
  68726. }
  68727. if (currentPool.length < 2) {
  68728. continue;
  68729. }
  68730. // Merge meshes
  68731. BABYLON.Mesh.MergeMeshes(currentPool);
  68732. }
  68733. if (updateSelectionTree != undefined) {
  68734. if (updateSelectionTree) {
  68735. scene.createOrUpdateSelectionOctree();
  68736. }
  68737. }
  68738. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  68739. scene.createOrUpdateSelectionOctree();
  68740. }
  68741. return true;
  68742. };
  68743. return _this;
  68744. }
  68745. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  68746. get: function () {
  68747. return MergeMeshesOptimization._UpdateSelectionTree;
  68748. },
  68749. set: function (value) {
  68750. MergeMeshesOptimization._UpdateSelectionTree = value;
  68751. },
  68752. enumerable: true,
  68753. configurable: true
  68754. });
  68755. MergeMeshesOptimization._UpdateSelectionTree = false;
  68756. return MergeMeshesOptimization;
  68757. }(SceneOptimization));
  68758. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  68759. // Options
  68760. var SceneOptimizerOptions = (function () {
  68761. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  68762. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  68763. if (trackerDuration === void 0) { trackerDuration = 2000; }
  68764. this.targetFrameRate = targetFrameRate;
  68765. this.trackerDuration = trackerDuration;
  68766. this.optimizations = new Array();
  68767. }
  68768. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  68769. var result = new SceneOptimizerOptions(targetFrameRate);
  68770. var priority = 0;
  68771. result.optimizations.push(new MergeMeshesOptimization(priority));
  68772. result.optimizations.push(new ShadowsOptimization(priority));
  68773. result.optimizations.push(new LensFlaresOptimization(priority));
  68774. // Next priority
  68775. priority++;
  68776. result.optimizations.push(new PostProcessesOptimization(priority));
  68777. result.optimizations.push(new ParticlesOptimization(priority));
  68778. // Next priority
  68779. priority++;
  68780. result.optimizations.push(new TextureOptimization(priority, 1024));
  68781. return result;
  68782. };
  68783. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  68784. var result = new SceneOptimizerOptions(targetFrameRate);
  68785. var priority = 0;
  68786. result.optimizations.push(new MergeMeshesOptimization(priority));
  68787. result.optimizations.push(new ShadowsOptimization(priority));
  68788. result.optimizations.push(new LensFlaresOptimization(priority));
  68789. // Next priority
  68790. priority++;
  68791. result.optimizations.push(new PostProcessesOptimization(priority));
  68792. result.optimizations.push(new ParticlesOptimization(priority));
  68793. // Next priority
  68794. priority++;
  68795. result.optimizations.push(new TextureOptimization(priority, 512));
  68796. // Next priority
  68797. priority++;
  68798. result.optimizations.push(new RenderTargetsOptimization(priority));
  68799. // Next priority
  68800. priority++;
  68801. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  68802. return result;
  68803. };
  68804. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  68805. var result = new SceneOptimizerOptions(targetFrameRate);
  68806. var priority = 0;
  68807. result.optimizations.push(new MergeMeshesOptimization(priority));
  68808. result.optimizations.push(new ShadowsOptimization(priority));
  68809. result.optimizations.push(new LensFlaresOptimization(priority));
  68810. // Next priority
  68811. priority++;
  68812. result.optimizations.push(new PostProcessesOptimization(priority));
  68813. result.optimizations.push(new ParticlesOptimization(priority));
  68814. // Next priority
  68815. priority++;
  68816. result.optimizations.push(new TextureOptimization(priority, 256));
  68817. // Next priority
  68818. priority++;
  68819. result.optimizations.push(new RenderTargetsOptimization(priority));
  68820. // Next priority
  68821. priority++;
  68822. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  68823. return result;
  68824. };
  68825. return SceneOptimizerOptions;
  68826. }());
  68827. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  68828. // Scene optimizer tool
  68829. var SceneOptimizer = (function () {
  68830. function SceneOptimizer() {
  68831. }
  68832. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  68833. // TODO: add an epsilon
  68834. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  68835. if (onSuccess) {
  68836. onSuccess();
  68837. }
  68838. return;
  68839. }
  68840. // Apply current level of optimizations
  68841. var allDone = true;
  68842. var noOptimizationApplied = true;
  68843. for (var index = 0; index < options.optimizations.length; index++) {
  68844. var optimization = options.optimizations[index];
  68845. if (optimization.priority === currentPriorityLevel) {
  68846. noOptimizationApplied = false;
  68847. allDone = allDone && optimization.apply(scene);
  68848. }
  68849. }
  68850. // If no optimization was applied, this is a failure :(
  68851. if (noOptimizationApplied) {
  68852. if (onFailure) {
  68853. onFailure();
  68854. }
  68855. return;
  68856. }
  68857. // If all optimizations were done, move to next level
  68858. if (allDone) {
  68859. currentPriorityLevel++;
  68860. }
  68861. // Let's the system running for a specific amount of time before checking FPS
  68862. scene.executeWhenReady(function () {
  68863. setTimeout(function () {
  68864. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  68865. }, options.trackerDuration);
  68866. });
  68867. };
  68868. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  68869. if (!options) {
  68870. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  68871. }
  68872. // Let's the system running for a specific amount of time before checking FPS
  68873. scene.executeWhenReady(function () {
  68874. setTimeout(function () {
  68875. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  68876. }, options.trackerDuration);
  68877. });
  68878. };
  68879. return SceneOptimizer;
  68880. }());
  68881. BABYLON.SceneOptimizer = SceneOptimizer;
  68882. })(BABYLON || (BABYLON = {}));
  68883. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  68884. var BABYLON;
  68885. (function (BABYLON) {
  68886. var OutlineRenderer = (function () {
  68887. function OutlineRenderer(scene) {
  68888. this.zOffset = 1;
  68889. this._scene = scene;
  68890. }
  68891. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  68892. var _this = this;
  68893. if (useOverlay === void 0) { useOverlay = false; }
  68894. var scene = this._scene;
  68895. var engine = this._scene.getEngine();
  68896. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68897. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  68898. return;
  68899. }
  68900. var mesh = subMesh.getRenderingMesh();
  68901. var material = subMesh.getMaterial();
  68902. engine.enableEffect(this._effect);
  68903. // Logarithmic depth
  68904. if (material.useLogarithmicDepth) {
  68905. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  68906. }
  68907. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  68908. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  68909. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68910. // Bones
  68911. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68912. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68913. }
  68914. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68915. // Alpha test
  68916. if (material && material.needAlphaTesting()) {
  68917. var alphaTexture = material.getAlphaTestTexture();
  68918. if (alphaTexture) {
  68919. this._effect.setTexture("diffuseSampler", alphaTexture);
  68920. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68921. }
  68922. }
  68923. engine.setZOffset(-this.zOffset);
  68924. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  68925. engine.setZOffset(0);
  68926. };
  68927. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  68928. var defines = [];
  68929. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68930. var mesh = subMesh.getMesh();
  68931. var material = subMesh.getMaterial();
  68932. if (material) {
  68933. // Alpha test
  68934. if (material.needAlphaTesting()) {
  68935. defines.push("#define ALPHATEST");
  68936. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68937. attribs.push(BABYLON.VertexBuffer.UVKind);
  68938. defines.push("#define UV1");
  68939. }
  68940. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68941. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68942. defines.push("#define UV2");
  68943. }
  68944. }
  68945. //Logarithmic depth
  68946. if (material.useLogarithmicDepth) {
  68947. defines.push("#define LOGARITHMICDEPTH");
  68948. }
  68949. }
  68950. // Bones
  68951. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68954. if (mesh.numBoneInfluencers > 4) {
  68955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68957. }
  68958. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68959. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68960. }
  68961. else {
  68962. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68963. }
  68964. // Instances
  68965. if (useInstances) {
  68966. defines.push("#define INSTANCES");
  68967. attribs.push("world0");
  68968. attribs.push("world1");
  68969. attribs.push("world2");
  68970. attribs.push("world3");
  68971. }
  68972. // Get correct effect
  68973. var join = defines.join("\n");
  68974. if (this._cachedDefines !== join) {
  68975. this._cachedDefines = join;
  68976. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  68977. }
  68978. return this._effect.isReady();
  68979. };
  68980. return OutlineRenderer;
  68981. }());
  68982. BABYLON.OutlineRenderer = OutlineRenderer;
  68983. })(BABYLON || (BABYLON = {}));
  68984. //# sourceMappingURL=babylon.outlineRenderer.js.map
  68985. var BABYLON;
  68986. (function (BABYLON) {
  68987. var FaceAdjacencies = (function () {
  68988. function FaceAdjacencies() {
  68989. this.edges = new Array();
  68990. this.edgesConnectedCount = 0;
  68991. }
  68992. return FaceAdjacencies;
  68993. }());
  68994. var EdgesRenderer = (function () {
  68995. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  68996. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  68997. if (epsilon === void 0) { epsilon = 0.95; }
  68998. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  68999. this.edgesWidthScalerForOrthographic = 1000.0;
  69000. this.edgesWidthScalerForPerspective = 50.0;
  69001. this._linesPositions = new Array();
  69002. this._linesNormals = new Array();
  69003. this._linesIndices = new Array();
  69004. this._buffers = {};
  69005. this._checkVerticesInsteadOfIndices = false;
  69006. this._source = source;
  69007. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  69008. this._epsilon = epsilon;
  69009. this._prepareRessources();
  69010. this._generateEdgesLines();
  69011. }
  69012. EdgesRenderer.prototype._prepareRessources = function () {
  69013. if (this._lineShader) {
  69014. return;
  69015. }
  69016. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  69017. attributes: ["position", "normal"],
  69018. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  69019. });
  69020. this._lineShader.disableDepthWrite = true;
  69021. this._lineShader.backFaceCulling = false;
  69022. };
  69023. EdgesRenderer.prototype._rebuild = function () {
  69024. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  69025. if (buffer) {
  69026. buffer._rebuild();
  69027. }
  69028. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  69029. if (buffer) {
  69030. buffer._rebuild();
  69031. }
  69032. var scene = this._source.getScene();
  69033. var engine = scene.getEngine();
  69034. this._ib = engine.createIndexBuffer(this._linesIndices);
  69035. };
  69036. EdgesRenderer.prototype.dispose = function () {
  69037. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  69038. if (buffer) {
  69039. buffer.dispose();
  69040. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  69041. }
  69042. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  69043. if (buffer) {
  69044. buffer.dispose();
  69045. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  69046. }
  69047. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  69048. this._lineShader.dispose();
  69049. };
  69050. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  69051. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  69052. return 0;
  69053. }
  69054. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  69055. return 1;
  69056. }
  69057. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  69058. return 2;
  69059. }
  69060. return -1;
  69061. };
  69062. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  69063. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  69064. return 0;
  69065. }
  69066. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  69067. return 1;
  69068. }
  69069. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  69070. return 2;
  69071. }
  69072. return -1;
  69073. };
  69074. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  69075. var needToCreateLine;
  69076. if (edge === undefined) {
  69077. needToCreateLine = true;
  69078. }
  69079. else {
  69080. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  69081. needToCreateLine = dotProduct < this._epsilon;
  69082. }
  69083. if (needToCreateLine) {
  69084. var offset = this._linesPositions.length / 3;
  69085. var normal = p0.subtract(p1);
  69086. normal.normalize();
  69087. // Positions
  69088. this._linesPositions.push(p0.x);
  69089. this._linesPositions.push(p0.y);
  69090. this._linesPositions.push(p0.z);
  69091. this._linesPositions.push(p0.x);
  69092. this._linesPositions.push(p0.y);
  69093. this._linesPositions.push(p0.z);
  69094. this._linesPositions.push(p1.x);
  69095. this._linesPositions.push(p1.y);
  69096. this._linesPositions.push(p1.z);
  69097. this._linesPositions.push(p1.x);
  69098. this._linesPositions.push(p1.y);
  69099. this._linesPositions.push(p1.z);
  69100. // Normals
  69101. this._linesNormals.push(p1.x);
  69102. this._linesNormals.push(p1.y);
  69103. this._linesNormals.push(p1.z);
  69104. this._linesNormals.push(-1);
  69105. this._linesNormals.push(p1.x);
  69106. this._linesNormals.push(p1.y);
  69107. this._linesNormals.push(p1.z);
  69108. this._linesNormals.push(1);
  69109. this._linesNormals.push(p0.x);
  69110. this._linesNormals.push(p0.y);
  69111. this._linesNormals.push(p0.z);
  69112. this._linesNormals.push(-1);
  69113. this._linesNormals.push(p0.x);
  69114. this._linesNormals.push(p0.y);
  69115. this._linesNormals.push(p0.z);
  69116. this._linesNormals.push(1);
  69117. // Indices
  69118. this._linesIndices.push(offset);
  69119. this._linesIndices.push(offset + 1);
  69120. this._linesIndices.push(offset + 2);
  69121. this._linesIndices.push(offset);
  69122. this._linesIndices.push(offset + 2);
  69123. this._linesIndices.push(offset + 3);
  69124. }
  69125. };
  69126. EdgesRenderer.prototype._generateEdgesLines = function () {
  69127. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69128. var indices = this._source.getIndices();
  69129. // First let's find adjacencies
  69130. var adjacencies = new Array();
  69131. var faceNormals = new Array();
  69132. var index;
  69133. var faceAdjacencies;
  69134. // Prepare faces
  69135. for (index = 0; index < indices.length; index += 3) {
  69136. faceAdjacencies = new FaceAdjacencies();
  69137. var p0Index = indices[index];
  69138. var p1Index = indices[index + 1];
  69139. var p2Index = indices[index + 2];
  69140. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  69141. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  69142. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  69143. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  69144. faceNormal.normalize();
  69145. faceNormals.push(faceNormal);
  69146. adjacencies.push(faceAdjacencies);
  69147. }
  69148. // Scan
  69149. for (index = 0; index < adjacencies.length; index++) {
  69150. faceAdjacencies = adjacencies[index];
  69151. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  69152. var otherFaceAdjacencies = adjacencies[otherIndex];
  69153. if (faceAdjacencies.edgesConnectedCount === 3) {
  69154. break;
  69155. }
  69156. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  69157. continue;
  69158. }
  69159. var otherP0 = indices[otherIndex * 3];
  69160. var otherP1 = indices[otherIndex * 3 + 1];
  69161. var otherP2 = indices[otherIndex * 3 + 2];
  69162. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  69163. var otherEdgeIndex;
  69164. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  69165. continue;
  69166. }
  69167. switch (edgeIndex) {
  69168. case 0:
  69169. if (this._checkVerticesInsteadOfIndices) {
  69170. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69171. }
  69172. else {
  69173. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  69174. }
  69175. break;
  69176. case 1:
  69177. if (this._checkVerticesInsteadOfIndices) {
  69178. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69179. }
  69180. else {
  69181. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  69182. }
  69183. break;
  69184. case 2:
  69185. if (this._checkVerticesInsteadOfIndices) {
  69186. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69187. }
  69188. else {
  69189. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  69190. }
  69191. break;
  69192. }
  69193. if (otherEdgeIndex === -1) {
  69194. continue;
  69195. }
  69196. faceAdjacencies.edges[edgeIndex] = otherIndex;
  69197. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  69198. faceAdjacencies.edgesConnectedCount++;
  69199. otherFaceAdjacencies.edgesConnectedCount++;
  69200. if (faceAdjacencies.edgesConnectedCount === 3) {
  69201. break;
  69202. }
  69203. }
  69204. }
  69205. }
  69206. // Create lines
  69207. for (index = 0; index < adjacencies.length; index++) {
  69208. // 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
  69209. var current = adjacencies[index];
  69210. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  69211. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  69212. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  69213. }
  69214. // Merge into a single mesh
  69215. var engine = this._source.getScene().getEngine();
  69216. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  69217. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  69218. this._ib = engine.createIndexBuffer(this._linesIndices);
  69219. this._indicesCount = this._linesIndices.length;
  69220. };
  69221. EdgesRenderer.prototype.render = function () {
  69222. if (!this._lineShader.isReady()) {
  69223. return;
  69224. }
  69225. var scene = this._source.getScene();
  69226. var engine = scene.getEngine();
  69227. this._lineShader._preBind();
  69228. // VBOs
  69229. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  69230. scene.resetCachedMaterial();
  69231. this._lineShader.setColor4("color", this._source.edgesColor);
  69232. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  69233. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  69234. }
  69235. else {
  69236. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  69237. }
  69238. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  69239. this._lineShader.bind(this._source.getWorldMatrix());
  69240. // Draw order
  69241. engine.draw(true, 0, this._indicesCount);
  69242. this._lineShader.unbind();
  69243. engine.setDepthWrite(true);
  69244. };
  69245. return EdgesRenderer;
  69246. }());
  69247. BABYLON.EdgesRenderer = EdgesRenderer;
  69248. })(BABYLON || (BABYLON = {}));
  69249. //# sourceMappingURL=babylon.edgesRenderer.js.map
  69250. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  69251. /// <reference path="..\Math\babylon.math.ts" />
  69252. var BABYLON;
  69253. (function (BABYLON) {
  69254. /**
  69255. * Special Glow Blur post process only blurring the alpha channel
  69256. * It enforces keeping the most luminous color in the color channel.
  69257. */
  69258. var GlowBlurPostProcess = (function (_super) {
  69259. __extends(GlowBlurPostProcess, _super);
  69260. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  69261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69262. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  69263. _this.direction = direction;
  69264. _this.kernel = kernel;
  69265. _this.onApplyObservable.add(function (effect) {
  69266. effect.setFloat2("screenSize", _this.width, _this.height);
  69267. effect.setVector2("direction", _this.direction);
  69268. effect.setFloat("blurWidth", _this.kernel);
  69269. });
  69270. return _this;
  69271. }
  69272. return GlowBlurPostProcess;
  69273. }(BABYLON.PostProcess));
  69274. /**
  69275. * The highlight layer Helps adding a glow effect around a mesh.
  69276. *
  69277. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  69278. * glowy meshes to your scene.
  69279. *
  69280. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  69281. */
  69282. var HighlightLayer = (function () {
  69283. /**
  69284. * Instantiates a new highlight Layer and references it to the scene..
  69285. * @param name The name of the layer
  69286. * @param scene The scene to use the layer in
  69287. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  69288. */
  69289. function HighlightLayer(name, scene, options) {
  69290. this.name = name;
  69291. this._vertexBuffers = {};
  69292. this._mainTextureDesiredSize = { width: 0, height: 0 };
  69293. this._meshes = {};
  69294. this._maxSize = 0;
  69295. this._shouldRender = false;
  69296. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  69297. this._excludedMeshes = {};
  69298. /**
  69299. * Specifies whether or not the inner glow is ACTIVE in the layer.
  69300. */
  69301. this.innerGlow = true;
  69302. /**
  69303. * Specifies whether or not the outer glow is ACTIVE in the layer.
  69304. */
  69305. this.outerGlow = true;
  69306. /**
  69307. * Specifies wether the highlight layer is enabled or not.
  69308. */
  69309. this.isEnabled = true;
  69310. /**
  69311. * An event triggered when the highlight layer has been disposed.
  69312. * @type {BABYLON.Observable}
  69313. */
  69314. this.onDisposeObservable = new BABYLON.Observable();
  69315. /**
  69316. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  69317. * @type {BABYLON.Observable}
  69318. */
  69319. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  69320. /**
  69321. * An event triggered when the highlight layer is being blurred.
  69322. * @type {BABYLON.Observable}
  69323. */
  69324. this.onBeforeBlurObservable = new BABYLON.Observable();
  69325. /**
  69326. * An event triggered when the highlight layer has been blurred.
  69327. * @type {BABYLON.Observable}
  69328. */
  69329. this.onAfterBlurObservable = new BABYLON.Observable();
  69330. /**
  69331. * An event triggered when the glowing blurred texture is being merged in the scene.
  69332. * @type {BABYLON.Observable}
  69333. */
  69334. this.onBeforeComposeObservable = new BABYLON.Observable();
  69335. /**
  69336. * An event triggered when the glowing blurred texture has been merged in the scene.
  69337. * @type {BABYLON.Observable}
  69338. */
  69339. this.onAfterComposeObservable = new BABYLON.Observable();
  69340. /**
  69341. * An event triggered when the highlight layer changes its size.
  69342. * @type {BABYLON.Observable}
  69343. */
  69344. this.onSizeChangedObservable = new BABYLON.Observable();
  69345. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69346. var engine = scene.getEngine();
  69347. this._engine = engine;
  69348. this._maxSize = this._engine.getCaps().maxTextureSize;
  69349. this._scene.highlightLayers.push(this);
  69350. // Warn on stencil.
  69351. if (!this._engine.isStencilEnable) {
  69352. 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 }");
  69353. }
  69354. // Adapt options
  69355. this._options = options || {
  69356. mainTextureRatio: 0.5,
  69357. blurTextureSizeRatio: 0.5,
  69358. blurHorizontalSize: 1.0,
  69359. blurVerticalSize: 1.0,
  69360. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  69361. };
  69362. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  69363. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  69364. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  69365. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  69366. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  69367. // VBO
  69368. var vertices = [];
  69369. vertices.push(1, 1);
  69370. vertices.push(-1, 1);
  69371. vertices.push(-1, -1);
  69372. vertices.push(1, -1);
  69373. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69374. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  69375. this._createIndexBuffer();
  69376. // Effect
  69377. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  69378. // Render target
  69379. this.setMainTextureSize();
  69380. // Create Textures and post processes
  69381. this.createTextureAndPostProcesses();
  69382. }
  69383. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  69384. /**
  69385. * Gets the horizontal size of the blur.
  69386. */
  69387. get: function () {
  69388. return this._horizontalBlurPostprocess.kernel;
  69389. },
  69390. /**
  69391. * Specifies the horizontal size of the blur.
  69392. */
  69393. set: function (value) {
  69394. this._horizontalBlurPostprocess.kernel = value;
  69395. },
  69396. enumerable: true,
  69397. configurable: true
  69398. });
  69399. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  69400. /**
  69401. * Gets the vertical size of the blur.
  69402. */
  69403. get: function () {
  69404. return this._verticalBlurPostprocess.kernel;
  69405. },
  69406. /**
  69407. * Specifies the vertical size of the blur.
  69408. */
  69409. set: function (value) {
  69410. this._verticalBlurPostprocess.kernel = value;
  69411. },
  69412. enumerable: true,
  69413. configurable: true
  69414. });
  69415. Object.defineProperty(HighlightLayer.prototype, "camera", {
  69416. /**
  69417. * Gets the camera attached to the layer.
  69418. */
  69419. get: function () {
  69420. return this._options.camera;
  69421. },
  69422. enumerable: true,
  69423. configurable: true
  69424. });
  69425. HighlightLayer.prototype._createIndexBuffer = function () {
  69426. var engine = this._scene.getEngine();
  69427. // Indices
  69428. var indices = [];
  69429. indices.push(0);
  69430. indices.push(1);
  69431. indices.push(2);
  69432. indices.push(0);
  69433. indices.push(2);
  69434. indices.push(3);
  69435. this._indexBuffer = engine.createIndexBuffer(indices);
  69436. };
  69437. HighlightLayer.prototype._rebuild = function () {
  69438. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  69439. this._createIndexBuffer();
  69440. };
  69441. /**
  69442. * Creates the render target textures and post processes used in the highlight layer.
  69443. */
  69444. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  69445. var _this = this;
  69446. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  69447. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  69448. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  69449. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  69450. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  69451. width: this._mainTextureDesiredSize.width,
  69452. height: this._mainTextureDesiredSize.height
  69453. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69454. this._mainTexture.activeCamera = this._options.camera;
  69455. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69456. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69457. this._mainTexture.anisotropicFilteringLevel = 1;
  69458. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69459. this._mainTexture.renderParticles = false;
  69460. this._mainTexture.renderList = null;
  69461. this._mainTexture.ignoreCameraViewport = true;
  69462. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  69463. width: blurTextureWidth,
  69464. height: blurTextureHeight
  69465. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69466. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69467. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69468. this._blurTexture.anisotropicFilteringLevel = 16;
  69469. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69470. this._blurTexture.renderParticles = false;
  69471. this._blurTexture.ignoreCameraViewport = true;
  69472. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69473. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  69474. effect.setTexture("textureSampler", _this._mainTexture);
  69475. });
  69476. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  69477. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69478. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  69479. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69480. });
  69481. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69482. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  69483. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69484. });
  69485. }
  69486. else {
  69487. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69488. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  69489. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69490. });
  69491. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  69492. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  69493. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  69494. });
  69495. }
  69496. this._mainTexture.onAfterUnbindObservable.add(function () {
  69497. _this.onBeforeBlurObservable.notifyObservers(_this);
  69498. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  69499. _this.onAfterBlurObservable.notifyObservers(_this);
  69500. });
  69501. // Custom render function
  69502. var renderSubMesh = function (subMesh) {
  69503. var mesh = subMesh.getRenderingMesh();
  69504. var scene = _this._scene;
  69505. var engine = scene.getEngine();
  69506. // Culling
  69507. engine.setState(subMesh.getMaterial().backFaceCulling);
  69508. // Managing instances
  69509. var batch = mesh._getInstancesRenderList(subMesh._id);
  69510. if (batch.mustReturn) {
  69511. return;
  69512. }
  69513. // Excluded Mesh
  69514. if (_this._excludedMeshes[mesh.uniqueId]) {
  69515. return;
  69516. }
  69517. ;
  69518. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69519. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  69520. var material = subMesh.getMaterial();
  69521. var emissiveTexture = null;
  69522. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  69523. emissiveTexture = material.emissiveTexture;
  69524. }
  69525. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  69526. engine.enableEffect(_this._glowMapGenerationEffect);
  69527. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  69528. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  69529. if (highlightLayerMesh) {
  69530. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  69531. }
  69532. else {
  69533. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  69534. }
  69535. // Alpha test
  69536. if (material && material.needAlphaTesting()) {
  69537. var alphaTexture = material.getAlphaTestTexture();
  69538. if (alphaTexture) {
  69539. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  69540. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69541. }
  69542. }
  69543. // Glow emissive only
  69544. if (emissiveTexture) {
  69545. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  69546. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  69547. }
  69548. // Bones
  69549. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69550. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69551. }
  69552. // Draw
  69553. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  69554. }
  69555. else {
  69556. // Need to reset refresh rate of the shadowMap
  69557. _this._mainTexture.resetRefreshCounter();
  69558. }
  69559. };
  69560. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69561. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  69562. var index;
  69563. var engine = _this._scene.getEngine();
  69564. if (depthOnlySubMeshes.length) {
  69565. engine.setColorWrite(false);
  69566. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69567. renderSubMesh(depthOnlySubMeshes.data[index]);
  69568. }
  69569. engine.setColorWrite(true);
  69570. }
  69571. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69572. renderSubMesh(opaqueSubMeshes.data[index]);
  69573. }
  69574. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69575. renderSubMesh(alphaTestSubMeshes.data[index]);
  69576. }
  69577. for (index = 0; index < transparentSubMeshes.length; index++) {
  69578. renderSubMesh(transparentSubMeshes.data[index]);
  69579. }
  69580. };
  69581. this._mainTexture.onClearObservable.add(function (engine) {
  69582. engine.clear(HighlightLayer.neutralColor, true, true, true);
  69583. });
  69584. };
  69585. /**
  69586. * Checks for the readiness of the element composing the layer.
  69587. * @param subMesh the mesh to check for
  69588. * @param useInstances specify wether or not to use instances to render the mesh
  69589. * @param emissiveTexture the associated emissive texture used to generate the glow
  69590. * @return true if ready otherwise, false
  69591. */
  69592. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  69593. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  69594. return false;
  69595. }
  69596. var defines = [];
  69597. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69598. var mesh = subMesh.getMesh();
  69599. var material = subMesh.getMaterial();
  69600. var uv1 = false;
  69601. var uv2 = false;
  69602. // Alpha test
  69603. if (material && material.needAlphaTesting()) {
  69604. var alphaTexture = material.getAlphaTestTexture();
  69605. if (alphaTexture) {
  69606. defines.push("#define ALPHATEST");
  69607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  69608. alphaTexture.coordinatesIndex === 1) {
  69609. defines.push("#define DIFFUSEUV2");
  69610. uv2 = true;
  69611. }
  69612. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69613. defines.push("#define DIFFUSEUV1");
  69614. uv1 = true;
  69615. }
  69616. }
  69617. }
  69618. // Emissive
  69619. if (emissiveTexture) {
  69620. defines.push("#define EMISSIVE");
  69621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  69622. emissiveTexture.coordinatesIndex === 1) {
  69623. defines.push("#define EMISSIVEUV2");
  69624. uv2 = true;
  69625. }
  69626. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69627. defines.push("#define EMISSIVEUV1");
  69628. uv1 = true;
  69629. }
  69630. }
  69631. if (uv1) {
  69632. attribs.push(BABYLON.VertexBuffer.UVKind);
  69633. defines.push("#define UV1");
  69634. }
  69635. if (uv2) {
  69636. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69637. defines.push("#define UV2");
  69638. }
  69639. // Bones
  69640. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69641. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69642. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69643. if (mesh.numBoneInfluencers > 4) {
  69644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69646. }
  69647. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69648. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69649. }
  69650. else {
  69651. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69652. }
  69653. // Instances
  69654. if (useInstances) {
  69655. defines.push("#define INSTANCES");
  69656. attribs.push("world0");
  69657. attribs.push("world1");
  69658. attribs.push("world2");
  69659. attribs.push("world3");
  69660. }
  69661. // Get correct effect
  69662. var join = defines.join("\n");
  69663. if (this._cachedDefines !== join) {
  69664. this._cachedDefines = join;
  69665. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  69666. }
  69667. return this._glowMapGenerationEffect.isReady();
  69668. };
  69669. /**
  69670. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  69671. */
  69672. HighlightLayer.prototype.render = function () {
  69673. var currentEffect = this._glowMapMergeEffect;
  69674. // Check
  69675. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  69676. return;
  69677. var engine = this._scene.getEngine();
  69678. this.onBeforeComposeObservable.notifyObservers(this);
  69679. // Render
  69680. engine.enableEffect(currentEffect);
  69681. engine.setState(false);
  69682. // Cache
  69683. var previousStencilBuffer = engine.getStencilBuffer();
  69684. var previousStencilFunction = engine.getStencilFunction();
  69685. var previousStencilMask = engine.getStencilMask();
  69686. var previousStencilOperationPass = engine.getStencilOperationPass();
  69687. var previousStencilOperationFail = engine.getStencilOperationFail();
  69688. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  69689. var previousAlphaMode = engine.getAlphaMode();
  69690. // Texture
  69691. currentEffect.setTexture("textureSampler", this._blurTexture);
  69692. // VBOs
  69693. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  69694. // Stencil operations
  69695. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  69696. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  69697. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  69698. // Draw order
  69699. engine.setAlphaMode(this._options.alphaBlendingMode);
  69700. engine.setStencilMask(0x00);
  69701. engine.setStencilBuffer(true);
  69702. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  69703. if (this.outerGlow) {
  69704. currentEffect.setFloat("offset", 0);
  69705. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  69706. engine.draw(true, 0, 6);
  69707. }
  69708. if (this.innerGlow) {
  69709. currentEffect.setFloat("offset", 1);
  69710. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  69711. engine.draw(true, 0, 6);
  69712. }
  69713. // Restore Cache
  69714. engine.setStencilFunction(previousStencilFunction);
  69715. engine.setStencilMask(previousStencilMask);
  69716. engine.setAlphaMode(previousAlphaMode);
  69717. engine.setStencilBuffer(previousStencilBuffer);
  69718. engine.setStencilOperationPass(previousStencilOperationPass);
  69719. engine.setStencilOperationFail(previousStencilOperationFail);
  69720. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  69721. engine._stencilState.reset();
  69722. this.onAfterComposeObservable.notifyObservers(this);
  69723. // Handle size changes.
  69724. var size = this._mainTexture.getSize();
  69725. this.setMainTextureSize();
  69726. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  69727. // Recreate RTT and post processes on size change.
  69728. this.onSizeChangedObservable.notifyObservers(this);
  69729. this.disposeTextureAndPostProcesses();
  69730. this.createTextureAndPostProcesses();
  69731. }
  69732. };
  69733. /**
  69734. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  69735. * @param mesh The mesh to exclude from the highlight layer
  69736. */
  69737. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  69738. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69739. if (!meshExcluded) {
  69740. this._excludedMeshes[mesh.uniqueId] = {
  69741. mesh: mesh,
  69742. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  69743. mesh.getEngine().setStencilBuffer(false);
  69744. }),
  69745. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  69746. mesh.getEngine().setStencilBuffer(true);
  69747. }),
  69748. };
  69749. }
  69750. };
  69751. /**
  69752. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  69753. * @param mesh The mesh to highlight
  69754. */
  69755. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  69756. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  69757. if (meshExcluded) {
  69758. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  69759. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  69760. }
  69761. this._excludedMeshes[mesh.uniqueId] = undefined;
  69762. };
  69763. /**
  69764. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  69765. * @param mesh The mesh to highlight
  69766. * @param color The color of the highlight
  69767. * @param glowEmissiveOnly Extract the glow from the emissive texture
  69768. */
  69769. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  69770. var _this = this;
  69771. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  69772. var meshHighlight = this._meshes[mesh.uniqueId];
  69773. if (meshHighlight) {
  69774. meshHighlight.color = color;
  69775. }
  69776. else {
  69777. this._meshes[mesh.uniqueId] = {
  69778. mesh: mesh,
  69779. color: color,
  69780. // Lambda required for capture due to Observable this context
  69781. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  69782. if (_this._excludedMeshes[mesh.uniqueId]) {
  69783. _this.defaultStencilReference(mesh);
  69784. }
  69785. else {
  69786. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  69787. }
  69788. }),
  69789. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  69790. glowEmissiveOnly: glowEmissiveOnly
  69791. };
  69792. }
  69793. this._shouldRender = true;
  69794. };
  69795. /**
  69796. * Remove a mesh from the highlight layer in order to make it stop glowing.
  69797. * @param mesh The mesh to highlight
  69798. */
  69799. HighlightLayer.prototype.removeMesh = function (mesh) {
  69800. var meshHighlight = this._meshes[mesh.uniqueId];
  69801. if (meshHighlight) {
  69802. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69803. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69804. }
  69805. this._meshes[mesh.uniqueId] = undefined;
  69806. this._shouldRender = false;
  69807. for (var meshHighlightToCheck in this._meshes) {
  69808. if (meshHighlightToCheck) {
  69809. this._shouldRender = true;
  69810. break;
  69811. }
  69812. }
  69813. };
  69814. /**
  69815. * Returns true if the layer contains information to display, otherwise false.
  69816. */
  69817. HighlightLayer.prototype.shouldRender = function () {
  69818. return this.isEnabled && this._shouldRender;
  69819. };
  69820. /**
  69821. * Sets the main texture desired size which is the closest power of two
  69822. * of the engine canvas size.
  69823. */
  69824. HighlightLayer.prototype.setMainTextureSize = function () {
  69825. if (this._options.mainTextureFixedSize) {
  69826. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  69827. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  69828. }
  69829. else {
  69830. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  69831. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  69832. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  69833. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  69834. }
  69835. };
  69836. /**
  69837. * Force the stencil to the normal expected value for none glowing parts
  69838. */
  69839. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  69840. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  69841. };
  69842. /**
  69843. * Dispose only the render target textures and post process.
  69844. */
  69845. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  69846. this._blurTexture.dispose();
  69847. this._mainTexture.dispose();
  69848. this._downSamplePostprocess.dispose();
  69849. this._horizontalBlurPostprocess.dispose();
  69850. this._verticalBlurPostprocess.dispose();
  69851. };
  69852. /**
  69853. * Dispose the highlight layer and free resources.
  69854. */
  69855. HighlightLayer.prototype.dispose = function () {
  69856. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69857. if (vertexBuffer) {
  69858. vertexBuffer.dispose();
  69859. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69860. }
  69861. if (this._indexBuffer) {
  69862. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69863. this._indexBuffer = null;
  69864. }
  69865. // Clean textures and post processes
  69866. this.disposeTextureAndPostProcesses();
  69867. // Clean mesh references
  69868. for (var id in this._meshes) {
  69869. var meshHighlight = this._meshes[id];
  69870. if (meshHighlight && meshHighlight.mesh) {
  69871. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  69872. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  69873. }
  69874. }
  69875. this._meshes = null;
  69876. for (var id in this._excludedMeshes) {
  69877. var meshHighlight = this._excludedMeshes[id];
  69878. if (meshHighlight) {
  69879. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  69880. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  69881. }
  69882. }
  69883. this._excludedMeshes = null;
  69884. // Remove from scene
  69885. var index = this._scene.highlightLayers.indexOf(this, 0);
  69886. if (index > -1) {
  69887. this._scene.highlightLayers.splice(index, 1);
  69888. }
  69889. // Callback
  69890. this.onDisposeObservable.notifyObservers(this);
  69891. this.onDisposeObservable.clear();
  69892. this.onBeforeRenderMainTextureObservable.clear();
  69893. this.onBeforeBlurObservable.clear();
  69894. this.onBeforeComposeObservable.clear();
  69895. this.onAfterComposeObservable.clear();
  69896. this.onSizeChangedObservable.clear();
  69897. };
  69898. /**
  69899. * The neutral color used during the preparation of the glow effect.
  69900. * This is black by default as the blend operation is a blend operation.
  69901. */
  69902. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  69903. /**
  69904. * Stencil value used for glowing meshes.
  69905. */
  69906. HighlightLayer.glowingMeshStencilReference = 0x02;
  69907. /**
  69908. * Stencil value used for the other meshes in the scene.
  69909. */
  69910. HighlightLayer.normalMeshStencilReference = 0x01;
  69911. return HighlightLayer;
  69912. }());
  69913. BABYLON.HighlightLayer = HighlightLayer;
  69914. })(BABYLON || (BABYLON = {}));
  69915. //# sourceMappingURL=babylon.highlightlayer.js.map
  69916. var BABYLON;
  69917. (function (BABYLON) {
  69918. var AssetTaskState;
  69919. (function (AssetTaskState) {
  69920. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  69921. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  69922. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  69923. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  69924. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  69925. var AbstractAssetTask = (function () {
  69926. function AbstractAssetTask() {
  69927. this.isCompleted = false;
  69928. this.taskState = AssetTaskState.INIT;
  69929. }
  69930. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69931. var _this = this;
  69932. this.taskState = AssetTaskState.RUNNING;
  69933. this.runTask(scene, function () {
  69934. _this.onDoneCallback(onSuccess, onError);
  69935. }, function (msg, exception) {
  69936. _this.onErrorCallback(onError, msg, exception);
  69937. });
  69938. };
  69939. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  69940. throw new Error("runTask is not implemented");
  69941. };
  69942. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  69943. this.taskState = AssetTaskState.ERROR;
  69944. this.errorObject = {
  69945. message: message,
  69946. exception: exception
  69947. };
  69948. if (this.onError) {
  69949. this.onError(this, message, exception);
  69950. }
  69951. onError();
  69952. };
  69953. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  69954. try {
  69955. this.taskState = AssetTaskState.DONE;
  69956. this.isCompleted = true;
  69957. if (this.onSuccess) {
  69958. this.onSuccess(this);
  69959. }
  69960. onSuccess();
  69961. }
  69962. catch (e) {
  69963. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  69964. }
  69965. };
  69966. return AbstractAssetTask;
  69967. }());
  69968. BABYLON.AbstractAssetTask = AbstractAssetTask;
  69969. var MeshAssetTask = (function (_super) {
  69970. __extends(MeshAssetTask, _super);
  69971. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  69972. var _this = _super.call(this) || this;
  69973. _this.name = name;
  69974. _this.meshesNames = meshesNames;
  69975. _this.rootUrl = rootUrl;
  69976. _this.sceneFilename = sceneFilename;
  69977. return _this;
  69978. }
  69979. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  69980. var _this = this;
  69981. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  69982. _this.loadedMeshes = meshes;
  69983. _this.loadedParticleSystems = particleSystems;
  69984. _this.loadedSkeletons = skeletons;
  69985. onSuccess();
  69986. }, null, function (scene, message, exception) {
  69987. onError(message, exception);
  69988. });
  69989. };
  69990. return MeshAssetTask;
  69991. }(AbstractAssetTask));
  69992. BABYLON.MeshAssetTask = MeshAssetTask;
  69993. var TextFileAssetTask = (function (_super) {
  69994. __extends(TextFileAssetTask, _super);
  69995. function TextFileAssetTask(name, url) {
  69996. var _this = _super.call(this) || this;
  69997. _this.name = name;
  69998. _this.url = url;
  69999. return _this;
  70000. }
  70001. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70002. var _this = this;
  70003. BABYLON.Tools.LoadFile(this.url, function (data) {
  70004. _this.text = data;
  70005. onSuccess();
  70006. }, null, scene.database, false, function (request, exception) {
  70007. onError(request.status + " " + request.statusText, exception);
  70008. });
  70009. };
  70010. return TextFileAssetTask;
  70011. }(AbstractAssetTask));
  70012. BABYLON.TextFileAssetTask = TextFileAssetTask;
  70013. var BinaryFileAssetTask = (function (_super) {
  70014. __extends(BinaryFileAssetTask, _super);
  70015. function BinaryFileAssetTask(name, url) {
  70016. var _this = _super.call(this) || this;
  70017. _this.name = name;
  70018. _this.url = url;
  70019. return _this;
  70020. }
  70021. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70022. var _this = this;
  70023. BABYLON.Tools.LoadFile(this.url, function (data) {
  70024. _this.data = data;
  70025. onSuccess();
  70026. }, null, scene.database, true, function (request, exception) {
  70027. onError(request.status + " " + request.statusText, exception);
  70028. });
  70029. };
  70030. return BinaryFileAssetTask;
  70031. }(AbstractAssetTask));
  70032. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  70033. var ImageAssetTask = (function (_super) {
  70034. __extends(ImageAssetTask, _super);
  70035. function ImageAssetTask(name, url) {
  70036. var _this = _super.call(this) || this;
  70037. _this.name = name;
  70038. _this.url = url;
  70039. return _this;
  70040. }
  70041. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70042. var _this = this;
  70043. var img = new Image();
  70044. BABYLON.Tools.SetCorsBehavior(this.url, img);
  70045. img.onload = function () {
  70046. _this.image = img;
  70047. onSuccess();
  70048. };
  70049. img.onerror = function (err) {
  70050. onError("Error loading image", err);
  70051. };
  70052. img.src = this.url;
  70053. };
  70054. return ImageAssetTask;
  70055. }(AbstractAssetTask));
  70056. BABYLON.ImageAssetTask = ImageAssetTask;
  70057. var TextureAssetTask = (function (_super) {
  70058. __extends(TextureAssetTask, _super);
  70059. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  70060. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70061. var _this = _super.call(this) || this;
  70062. _this.name = name;
  70063. _this.url = url;
  70064. _this.noMipmap = noMipmap;
  70065. _this.invertY = invertY;
  70066. _this.samplingMode = samplingMode;
  70067. return _this;
  70068. }
  70069. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70070. var onload = function () {
  70071. onSuccess();
  70072. };
  70073. var onerror = function (msg, exception) {
  70074. onError(msg, exception);
  70075. };
  70076. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  70077. };
  70078. return TextureAssetTask;
  70079. }(AbstractAssetTask));
  70080. BABYLON.TextureAssetTask = TextureAssetTask;
  70081. var CubeTextureAssetTask = (function (_super) {
  70082. __extends(CubeTextureAssetTask, _super);
  70083. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  70084. var _this = _super.call(this) || this;
  70085. _this.name = name;
  70086. _this.url = url;
  70087. _this.extensions = extensions;
  70088. _this.noMipmap = noMipmap;
  70089. _this.files = files;
  70090. return _this;
  70091. }
  70092. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70093. var onload = function () {
  70094. onSuccess();
  70095. };
  70096. var onerror = function (msg, exception) {
  70097. onError(msg, exception);
  70098. };
  70099. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  70100. };
  70101. return CubeTextureAssetTask;
  70102. }(AbstractAssetTask));
  70103. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  70104. var HDRCubeTextureAssetTask = (function (_super) {
  70105. __extends(HDRCubeTextureAssetTask, _super);
  70106. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  70107. if (noMipmap === void 0) { noMipmap = false; }
  70108. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70109. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70110. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70111. var _this = _super.call(this) || this;
  70112. _this.name = name;
  70113. _this.url = url;
  70114. _this.size = size;
  70115. _this.noMipmap = noMipmap;
  70116. _this.generateHarmonics = generateHarmonics;
  70117. _this.useInGammaSpace = useInGammaSpace;
  70118. _this.usePMREMGenerator = usePMREMGenerator;
  70119. return _this;
  70120. }
  70121. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  70122. var onload = function () {
  70123. onSuccess();
  70124. };
  70125. var onerror = function (message, exception) {
  70126. onError(message, exception);
  70127. };
  70128. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  70129. };
  70130. return HDRCubeTextureAssetTask;
  70131. }(AbstractAssetTask));
  70132. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  70133. var AssetsManager = (function () {
  70134. function AssetsManager(scene) {
  70135. this.tasks = new Array();
  70136. this.waitingTasksCount = 0;
  70137. //Observables
  70138. this.onTaskSuccessObservable = new BABYLON.Observable();
  70139. this.onTaskErrorObservable = new BABYLON.Observable();
  70140. this.onTasksDoneObservable = new BABYLON.Observable();
  70141. this.useDefaultLoadingScreen = true;
  70142. this._scene = scene;
  70143. }
  70144. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  70145. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  70146. this.tasks.push(task);
  70147. return task;
  70148. };
  70149. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  70150. var task = new TextFileAssetTask(taskName, url);
  70151. this.tasks.push(task);
  70152. return task;
  70153. };
  70154. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  70155. var task = new BinaryFileAssetTask(taskName, url);
  70156. this.tasks.push(task);
  70157. return task;
  70158. };
  70159. AssetsManager.prototype.addImageTask = function (taskName, url) {
  70160. var task = new ImageAssetTask(taskName, url);
  70161. this.tasks.push(task);
  70162. return task;
  70163. };
  70164. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  70165. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70166. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  70167. this.tasks.push(task);
  70168. return task;
  70169. };
  70170. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  70171. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  70172. this.tasks.push(task);
  70173. return task;
  70174. };
  70175. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  70176. if (noMipmap === void 0) { noMipmap = false; }
  70177. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70178. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70179. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70180. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  70181. this.tasks.push(task);
  70182. return task;
  70183. };
  70184. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  70185. this.waitingTasksCount--;
  70186. if (this.waitingTasksCount === 0) {
  70187. try {
  70188. if (this.onFinish) {
  70189. this.onFinish(this.tasks);
  70190. }
  70191. this.onTasksDoneObservable.notifyObservers(this.tasks);
  70192. }
  70193. catch (e) {
  70194. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  70195. console.log(e);
  70196. }
  70197. this._scene.getEngine().hideLoadingUI();
  70198. }
  70199. };
  70200. AssetsManager.prototype._runTask = function (task) {
  70201. var _this = this;
  70202. var done = function () {
  70203. try {
  70204. if (_this.onTaskSuccess) {
  70205. _this.onTaskSuccess(task);
  70206. }
  70207. _this.onTaskSuccessObservable.notifyObservers(task);
  70208. _this._decreaseWaitingTasksCount();
  70209. }
  70210. catch (e) {
  70211. error("Error executing task success callbacks", e);
  70212. }
  70213. };
  70214. var error = function (message, exception) {
  70215. task.errorObject = task.errorObject || {
  70216. message: message,
  70217. exception: exception
  70218. };
  70219. if (_this.onTaskError) {
  70220. _this.onTaskError(task);
  70221. }
  70222. _this.onTaskErrorObservable.notifyObservers(task);
  70223. _this._decreaseWaitingTasksCount();
  70224. };
  70225. task.run(this._scene, done, error);
  70226. };
  70227. AssetsManager.prototype.reset = function () {
  70228. this.tasks = new Array();
  70229. return this;
  70230. };
  70231. AssetsManager.prototype.load = function () {
  70232. this.waitingTasksCount = this.tasks.length;
  70233. if (this.waitingTasksCount === 0) {
  70234. if (this.onFinish) {
  70235. this.onFinish(this.tasks);
  70236. }
  70237. this.onTasksDoneObservable.notifyObservers(this.tasks);
  70238. return this;
  70239. }
  70240. if (this.useDefaultLoadingScreen) {
  70241. this._scene.getEngine().displayLoadingUI();
  70242. }
  70243. for (var index = 0; index < this.tasks.length; index++) {
  70244. var task = this.tasks[index];
  70245. this._runTask(task);
  70246. }
  70247. return this;
  70248. };
  70249. return AssetsManager;
  70250. }());
  70251. BABYLON.AssetsManager = AssetsManager;
  70252. })(BABYLON || (BABYLON = {}));
  70253. //# sourceMappingURL=babylon.assetsManager.js.map
  70254. var BABYLON;
  70255. (function (BABYLON) {
  70256. var MapTexture = (function (_super) {
  70257. __extends(MapTexture, _super);
  70258. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  70259. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70260. if (useMipMap === void 0) { useMipMap = false; }
  70261. if (margin === void 0) { margin = 0; }
  70262. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  70263. _this.name = name;
  70264. _this._size = size;
  70265. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70266. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70267. // Create the rectPackMap that will allocate portion of the texture
  70268. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  70269. // Create the texture that will store the content
  70270. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  70271. return _this;
  70272. }
  70273. /**
  70274. * Allocate a rectangle of a given size in the texture map
  70275. * @param size the size of the rectangle to allocation
  70276. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  70277. */
  70278. MapTexture.prototype.allocateRect = function (size) {
  70279. return this._rectPackingMap.addRect(size);
  70280. };
  70281. /**
  70282. * Free a given rectangle from the texture map
  70283. * @param rectInfo the instance corresponding to the rect to free.
  70284. */
  70285. MapTexture.prototype.freeRect = function (rectInfo) {
  70286. if (rectInfo) {
  70287. rectInfo.freeContent();
  70288. }
  70289. };
  70290. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  70291. /**
  70292. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  70293. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  70294. * @returns {}
  70295. */
  70296. get: function () {
  70297. return this._rectPackingMap.freeSpace;
  70298. },
  70299. enumerable: true,
  70300. configurable: true
  70301. });
  70302. /**
  70303. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  70304. * 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.
  70305. * Don't forget to call unbindTexture when you're done rendering
  70306. * @param rect the zone to render to
  70307. * @param clear true to clear the portion's color/depth data
  70308. */
  70309. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  70310. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  70311. };
  70312. /**
  70313. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  70314. * 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.
  70315. * Don't forget to call unbindTexture when you're done rendering
  70316. * @param pos the position into the texture
  70317. * @param size the portion to fit the clip space to
  70318. * @param clear true to clear the portion's color/depth data
  70319. */
  70320. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  70321. var engine = this.getScene().getEngine();
  70322. engine.bindFramebuffer(this._texture);
  70323. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  70324. if (clear) {
  70325. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  70326. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  70327. }
  70328. };
  70329. /**
  70330. * Unbind the texture map from the rendering engine.
  70331. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  70332. * @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.
  70333. */
  70334. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  70335. // Dump ?
  70336. if (dumpForDebug) {
  70337. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  70338. }
  70339. var engine = this.getScene().getEngine();
  70340. if (this._replacedViewport) {
  70341. engine.setViewport(this._replacedViewport);
  70342. this._replacedViewport = null;
  70343. }
  70344. engine.unBindFramebuffer(this._texture);
  70345. };
  70346. Object.defineProperty(MapTexture.prototype, "canRescale", {
  70347. get: function () {
  70348. return false;
  70349. },
  70350. enumerable: true,
  70351. configurable: true
  70352. });
  70353. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  70354. // Anyway, there's not much point to use this method for this kind of texture I guess
  70355. MapTexture.prototype.clone = function () {
  70356. return null;
  70357. };
  70358. return MapTexture;
  70359. }(BABYLON.Texture));
  70360. BABYLON.MapTexture = MapTexture;
  70361. })(BABYLON || (BABYLON = {}));
  70362. //# sourceMappingURL=babylon.mapTexture.js.map
  70363. var BABYLON;
  70364. (function (BABYLON) {
  70365. /**
  70366. * This class describe a rectangle that were added to the map.
  70367. * You have access to its coordinates either in pixel or normalized (UV)
  70368. */
  70369. var PackedRect = (function () {
  70370. function PackedRect(root, parent, pos, size) {
  70371. this._pos = pos;
  70372. this._size = size;
  70373. this._root = root;
  70374. this._parent = parent;
  70375. this._contentSize = null;
  70376. this._bottomNode = null;
  70377. this._leftNode = null;
  70378. this._initialSize = null;
  70379. this._rightNode = null;
  70380. }
  70381. Object.defineProperty(PackedRect.prototype, "pos", {
  70382. /**
  70383. * @returns the position of this node into the map
  70384. */
  70385. get: function () {
  70386. return this._pos;
  70387. },
  70388. enumerable: true,
  70389. configurable: true
  70390. });
  70391. Object.defineProperty(PackedRect.prototype, "contentSize", {
  70392. /**
  70393. * @returns the size of the rectangle this node handles
  70394. */
  70395. get: function () {
  70396. return this._contentSize;
  70397. },
  70398. enumerable: true,
  70399. configurable: true
  70400. });
  70401. /**
  70402. * Retrieve the inner position (considering the margin) and stores it into the res object
  70403. * @param res must be a valid Vector2 that will contain the inner position after this call
  70404. */
  70405. PackedRect.prototype.getInnerPosToRef = function (res) {
  70406. var m = this._root._margin;
  70407. res.x = this._pos.x + m;
  70408. res.y = this._pos.y + m;
  70409. };
  70410. /**
  70411. * Retrieve the inner size (considering the margin) and stores it into the res object
  70412. * @param res must be a valid Size that will contain the inner size after this call
  70413. */
  70414. PackedRect.prototype.getInnerSizeToRef = function (res) {
  70415. var m = this._root._margin;
  70416. res.width = this._contentSize.width - (m * 2);
  70417. res.height = this._contentSize.height - (m * 2);
  70418. };
  70419. Object.defineProperty(PackedRect.prototype, "UVs", {
  70420. /**
  70421. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  70422. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  70423. */
  70424. get: function () {
  70425. if (!this._contentSize) {
  70426. throw new Error("Can't compute UVs for this object because it's nor allocated");
  70427. }
  70428. return this.getUVsForCustomSize(this._contentSize);
  70429. },
  70430. enumerable: true,
  70431. configurable: true
  70432. });
  70433. /**
  70434. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  70435. * and then using only a part of the PackRect.
  70436. * This method will return the UVs for this part by given the custom size of what you really use
  70437. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  70438. */
  70439. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  70440. var mainWidth = this._root._size.width;
  70441. var mainHeight = this._root._size.height;
  70442. var margin = this._root._margin;
  70443. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  70444. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  70445. var uvs = new Array();
  70446. uvs.push(topLeft);
  70447. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  70448. uvs.push(rightBottom);
  70449. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  70450. return uvs;
  70451. };
  70452. /**
  70453. * Free this rectangle from the map.
  70454. * Call this method when you no longer need the rectangle to be in the map.
  70455. */
  70456. PackedRect.prototype.freeContent = function () {
  70457. if (!this.contentSize) {
  70458. return;
  70459. }
  70460. this._contentSize = null;
  70461. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  70462. this.attemptDefrag();
  70463. };
  70464. Object.defineProperty(PackedRect.prototype, "isUsed", {
  70465. get: function () {
  70466. return this._contentSize != null || this._leftNode != null;
  70467. },
  70468. enumerable: true,
  70469. configurable: true
  70470. });
  70471. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  70472. var node = this.findNode(contentSize);
  70473. // Not enough space...
  70474. if (!node) {
  70475. return null;
  70476. }
  70477. node.splitNode(contentSize);
  70478. return node;
  70479. };
  70480. PackedRect.prototype.findNode = function (size) {
  70481. var resNode = null;
  70482. var margin = this._root._margin * 2;
  70483. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  70484. if (this.isUsed) {
  70485. if (this._leftNode) {
  70486. resNode = this._leftNode.findNode(size);
  70487. }
  70488. if (!resNode && this._rightNode) {
  70489. resNode = this._rightNode.findNode(size);
  70490. }
  70491. if (!resNode && this._bottomNode) {
  70492. resNode = this._bottomNode.findNode(size);
  70493. }
  70494. }
  70495. else if (this._initialSize) {
  70496. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  70497. resNode = this;
  70498. }
  70499. else {
  70500. return null;
  70501. }
  70502. }
  70503. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  70504. resNode = this;
  70505. }
  70506. return resNode;
  70507. };
  70508. PackedRect.prototype.splitNode = function (contentSize) {
  70509. var cs = PackedRect.TpsSize;
  70510. var margin = this._root._margin * 2;
  70511. cs.copyFrom(contentSize);
  70512. cs.width += margin;
  70513. cs.height += margin;
  70514. // 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)
  70515. if (!this._contentSize && this._initialSize) {
  70516. this._contentSize = cs.clone();
  70517. 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));
  70518. return this._leftNode.splitNode(contentSize);
  70519. }
  70520. else {
  70521. this._contentSize = cs.clone();
  70522. this._initialSize = cs.clone();
  70523. if (cs.width !== this._size.width) {
  70524. 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));
  70525. }
  70526. if (cs.height !== this._size.height) {
  70527. 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));
  70528. }
  70529. return this;
  70530. }
  70531. };
  70532. PackedRect.prototype.attemptDefrag = function () {
  70533. if (!this.isUsed && this.isRecursiveFree) {
  70534. this.clearNode();
  70535. if (this._parent) {
  70536. this._parent.attemptDefrag();
  70537. }
  70538. }
  70539. };
  70540. PackedRect.prototype.clearNode = function () {
  70541. this._initialSize = null;
  70542. this._rightNode = null;
  70543. this._bottomNode = null;
  70544. };
  70545. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  70546. get: function () {
  70547. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  70548. },
  70549. enumerable: true,
  70550. configurable: true
  70551. });
  70552. PackedRect.prototype.evalFreeSize = function (size) {
  70553. var levelSize = 0;
  70554. if (!this.isUsed) {
  70555. var margin = this._root._margin;
  70556. var is = this._initialSize;
  70557. if (is) {
  70558. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  70559. }
  70560. else {
  70561. var size_1 = this._size;
  70562. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  70563. }
  70564. }
  70565. if (this._rightNode) {
  70566. levelSize += this._rightNode.evalFreeSize(0);
  70567. }
  70568. if (this._bottomNode) {
  70569. levelSize += this._bottomNode.evalFreeSize(0);
  70570. }
  70571. return levelSize + size;
  70572. };
  70573. PackedRect.TpsSize = BABYLON.Size.Zero();
  70574. return PackedRect;
  70575. }());
  70576. BABYLON.PackedRect = PackedRect;
  70577. /**
  70578. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  70579. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  70580. * 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.
  70581. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  70582. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  70583. */
  70584. var RectPackingMap = (function (_super) {
  70585. __extends(RectPackingMap, _super);
  70586. /**
  70587. * Create an instance of the object with a dimension using the given size
  70588. * @param size The dimension of the rectangle that will contain all the sub ones.
  70589. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  70590. */
  70591. function RectPackingMap(size, margin) {
  70592. if (margin === void 0) { margin = 0; }
  70593. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  70594. _this._margin = margin;
  70595. _this._root = _this;
  70596. return _this;
  70597. }
  70598. /**
  70599. * Add a rectangle, finding the best location to store it into the map
  70600. * @param size the dimension of the rectangle to store
  70601. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  70602. */
  70603. RectPackingMap.prototype.addRect = function (size) {
  70604. var node = this.findAndSplitNode(size);
  70605. return node;
  70606. };
  70607. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  70608. /**
  70609. * Return the current space free normalized between [0;1]
  70610. * @returns {}
  70611. */
  70612. get: function () {
  70613. var freeSize = 0;
  70614. freeSize = this.evalFreeSize(freeSize);
  70615. return freeSize / (this._size.width * this._size.height);
  70616. },
  70617. enumerable: true,
  70618. configurable: true
  70619. });
  70620. return RectPackingMap;
  70621. }(PackedRect));
  70622. BABYLON.RectPackingMap = RectPackingMap;
  70623. })(BABYLON || (BABYLON = {}));
  70624. //# sourceMappingURL=babylon.rectPackingMap.js.map
  70625. var BABYLON;
  70626. (function (BABYLON) {
  70627. /**
  70628. * This groups together the common properties used for image processing either in direct forward pass
  70629. * or through post processing effect depending on the use of the image processing pipeline in your scene
  70630. * or not.
  70631. */
  70632. var ImageProcessingConfiguration = (function () {
  70633. function ImageProcessingConfiguration() {
  70634. /**
  70635. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  70636. */
  70637. this.colorCurves = new BABYLON.ColorCurves();
  70638. this._colorCurvesEnabled = false;
  70639. this._colorGradingEnabled = false;
  70640. this._colorGradingWithGreenDepth = false;
  70641. this._colorGradingBGR = false;
  70642. this._exposure = 1.0;
  70643. this._toneMappingEnabled = false;
  70644. this._contrast = 1.0;
  70645. /**
  70646. * Vignette stretch size.
  70647. */
  70648. this.vignetteStretch = 0;
  70649. /**
  70650. * Vignette centre X Offset.
  70651. */
  70652. this.vignetteCentreX = 0;
  70653. /**
  70654. * Vignette centre Y Offset.
  70655. */
  70656. this.vignetteCentreY = 0;
  70657. /**
  70658. * Vignette weight or intensity of the vignette effect.
  70659. */
  70660. this.vignetteWeight = 1.5;
  70661. /**
  70662. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70663. * if vignetteEnabled is set to true.
  70664. */
  70665. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  70666. /**
  70667. * Camera field of view used by the Vignette effect.
  70668. */
  70669. this.vignetteCameraFov = 0.5;
  70670. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  70671. this._vignetteEnabled = false;
  70672. this._applyByPostProcess = false;
  70673. /**
  70674. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  70675. * @type {BABYLON.Observable}
  70676. */
  70677. this.onUpdateParameters = new BABYLON.Observable();
  70678. }
  70679. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  70680. /**
  70681. * Gets wether the color curves effect is enabled.
  70682. */
  70683. get: function () {
  70684. return this._colorCurvesEnabled;
  70685. },
  70686. /**
  70687. * Sets wether the color curves effect is enabled.
  70688. */
  70689. set: function (value) {
  70690. if (this._colorCurvesEnabled === value) {
  70691. return;
  70692. }
  70693. this._colorCurvesEnabled = value;
  70694. this._updateParameters();
  70695. },
  70696. enumerable: true,
  70697. configurable: true
  70698. });
  70699. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  70700. /**
  70701. * Gets wether the color grading effect is enabled.
  70702. */
  70703. get: function () {
  70704. return this._colorGradingEnabled;
  70705. },
  70706. /**
  70707. * Sets wether the color grading effect is enabled.
  70708. */
  70709. set: function (value) {
  70710. if (this._colorGradingEnabled === value) {
  70711. return;
  70712. }
  70713. this._colorGradingEnabled = value;
  70714. this._updateParameters();
  70715. },
  70716. enumerable: true,
  70717. configurable: true
  70718. });
  70719. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  70720. /**
  70721. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  70722. */
  70723. get: function () {
  70724. return this._colorGradingWithGreenDepth;
  70725. },
  70726. /**
  70727. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  70728. */
  70729. set: function (value) {
  70730. if (this._colorGradingWithGreenDepth === value) {
  70731. return;
  70732. }
  70733. this._colorGradingWithGreenDepth = value;
  70734. this._updateParameters();
  70735. },
  70736. enumerable: true,
  70737. configurable: true
  70738. });
  70739. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  70740. /**
  70741. * Gets wether the color grading texture contains BGR values.
  70742. */
  70743. get: function () {
  70744. return this._colorGradingBGR;
  70745. },
  70746. /**
  70747. * Sets wether the color grading texture contains BGR values.
  70748. */
  70749. set: function (value) {
  70750. if (this._colorGradingBGR === value) {
  70751. return;
  70752. }
  70753. this._colorGradingBGR = value;
  70754. this._updateParameters();
  70755. },
  70756. enumerable: true,
  70757. configurable: true
  70758. });
  70759. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  70760. /**
  70761. * Gets the Exposure used in the effect.
  70762. */
  70763. get: function () {
  70764. return this._exposure;
  70765. },
  70766. /**
  70767. * Sets the Exposure used in the effect.
  70768. */
  70769. set: function (value) {
  70770. if (this._exposure === value) {
  70771. return;
  70772. }
  70773. this._exposure = value;
  70774. this._updateParameters();
  70775. },
  70776. enumerable: true,
  70777. configurable: true
  70778. });
  70779. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  70780. /**
  70781. * Gets wether the tone mapping effect is enabled.
  70782. */
  70783. get: function () {
  70784. return this._toneMappingEnabled;
  70785. },
  70786. /**
  70787. * Sets wether the tone mapping effect is enabled.
  70788. */
  70789. set: function (value) {
  70790. if (this._toneMappingEnabled === value) {
  70791. return;
  70792. }
  70793. this._toneMappingEnabled = value;
  70794. this._updateParameters();
  70795. },
  70796. enumerable: true,
  70797. configurable: true
  70798. });
  70799. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  70800. /**
  70801. * Gets the contrast used in the effect.
  70802. */
  70803. get: function () {
  70804. return this._contrast;
  70805. },
  70806. /**
  70807. * Sets the contrast used in the effect.
  70808. */
  70809. set: function (value) {
  70810. if (this._contrast === value) {
  70811. return;
  70812. }
  70813. this._contrast = value;
  70814. this._updateParameters();
  70815. },
  70816. enumerable: true,
  70817. configurable: true
  70818. });
  70819. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  70820. /**
  70821. * Gets the vignette blend mode allowing different kind of effect.
  70822. */
  70823. get: function () {
  70824. return this._vignetteBlendMode;
  70825. },
  70826. /**
  70827. * Sets the vignette blend mode allowing different kind of effect.
  70828. */
  70829. set: function (value) {
  70830. if (this._vignetteBlendMode === value) {
  70831. return;
  70832. }
  70833. this._vignetteBlendMode = value;
  70834. this._updateParameters();
  70835. },
  70836. enumerable: true,
  70837. configurable: true
  70838. });
  70839. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  70840. /**
  70841. * Gets wether the vignette effect is enabled.
  70842. */
  70843. get: function () {
  70844. return this._vignetteEnabled;
  70845. },
  70846. /**
  70847. * Sets wether the vignette effect is enabled.
  70848. */
  70849. set: function (value) {
  70850. if (this._vignetteEnabled === value) {
  70851. return;
  70852. }
  70853. this._vignetteEnabled = value;
  70854. this._updateParameters();
  70855. },
  70856. enumerable: true,
  70857. configurable: true
  70858. });
  70859. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  70860. /**
  70861. * Gets wether the image processing is applied through a post process or not.
  70862. */
  70863. get: function () {
  70864. return this._applyByPostProcess;
  70865. },
  70866. /**
  70867. * Sets wether the image processing is applied through a post process or not.
  70868. */
  70869. set: function (value) {
  70870. if (this._applyByPostProcess === value) {
  70871. return;
  70872. }
  70873. this._applyByPostProcess = value;
  70874. this._updateParameters();
  70875. },
  70876. enumerable: true,
  70877. configurable: true
  70878. });
  70879. /**
  70880. * Method called each time the image processing information changes requires to recompile the effect.
  70881. */
  70882. ImageProcessingConfiguration.prototype._updateParameters = function () {
  70883. this.onUpdateParameters.notifyObservers(this);
  70884. };
  70885. ImageProcessingConfiguration.prototype.getClassName = function () {
  70886. return "ImageProcessingConfiguration";
  70887. };
  70888. /**
  70889. * Prepare the list of uniforms associated with the Image Processing effects.
  70890. * @param uniformsList The list of uniforms used in the effect
  70891. * @param defines the list of defines currently in use
  70892. */
  70893. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  70894. if (defines.EXPOSURE) {
  70895. uniforms.push("exposureLinear");
  70896. }
  70897. if (defines.CONTRAST) {
  70898. uniforms.push("contrast");
  70899. }
  70900. if (defines.COLORGRADING) {
  70901. uniforms.push("colorTransformSettings");
  70902. }
  70903. if (defines.VIGNETTE) {
  70904. uniforms.push("vInverseScreenSize");
  70905. uniforms.push("vignetteSettings1");
  70906. uniforms.push("vignetteSettings2");
  70907. }
  70908. if (defines.COLORCURVES) {
  70909. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  70910. }
  70911. };
  70912. /**
  70913. * Prepare the list of samplers associated with the Image Processing effects.
  70914. * @param uniformsList The list of uniforms used in the effect
  70915. * @param defines the list of defines currently in use
  70916. */
  70917. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  70918. if (defines.COLORGRADING) {
  70919. samplersList.push("txColorTransform");
  70920. }
  70921. };
  70922. /**
  70923. * Prepare the list of defines associated to the shader.
  70924. * @param defines the list of defines to complete
  70925. */
  70926. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  70927. if (forPostProcess === void 0) { forPostProcess = false; }
  70928. if (forPostProcess !== this.applyByPostProcess) {
  70929. defines.VIGNETTE = false;
  70930. defines.TONEMAPPING = false;
  70931. defines.CONTRAST = false;
  70932. defines.EXPOSURE = false;
  70933. defines.COLORCURVES = false;
  70934. defines.COLORGRADING = false;
  70935. defines.IMAGEPROCESSING = false;
  70936. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  70937. return;
  70938. }
  70939. defines.VIGNETTE = this.vignetteEnabled;
  70940. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  70941. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  70942. defines.TONEMAPPING = this.toneMappingEnabled;
  70943. defines.CONTRAST = (this.contrast !== 1.0);
  70944. defines.EXPOSURE = (this.exposure !== 1.0);
  70945. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  70946. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  70947. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  70948. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  70949. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  70950. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  70951. };
  70952. /**
  70953. * Returns true if all the image processing information are ready.
  70954. */
  70955. ImageProcessingConfiguration.prototype.isReady = function () {
  70956. // Color Grading texure can not be none blocking.
  70957. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  70958. };
  70959. /**
  70960. * Binds the image processing to the shader.
  70961. * @param effect The effect to bind to
  70962. */
  70963. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  70964. if (aspectRatio === void 0) { aspectRatio = 1; }
  70965. // Color Curves
  70966. if (this._colorCurvesEnabled) {
  70967. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  70968. }
  70969. // Vignette
  70970. if (this._vignetteEnabled) {
  70971. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  70972. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  70973. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  70974. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  70975. var vignetteScaleX = vignetteScaleY * aspectRatio;
  70976. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  70977. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  70978. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  70979. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  70980. var vignettePower = -2.0 * this.vignetteWeight;
  70981. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  70982. }
  70983. // Exposure
  70984. effect.setFloat("exposureLinear", this.exposure);
  70985. // Contrast
  70986. effect.setFloat("contrast", this.contrast);
  70987. // Color transform settings
  70988. if (this.colorGradingTexture) {
  70989. effect.setTexture("txColorTransform", this.colorGradingTexture);
  70990. var textureSize = this.colorGradingTexture.getSize().height;
  70991. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  70992. 0.5 / textureSize, // textureOffset
  70993. textureSize, // textureSize
  70994. this.colorGradingTexture.level // weight
  70995. );
  70996. }
  70997. };
  70998. /**
  70999. * Clones the current image processing instance.
  71000. * @return The cloned image processing
  71001. */
  71002. ImageProcessingConfiguration.prototype.clone = function () {
  71003. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  71004. };
  71005. /**
  71006. * Serializes the current image processing instance to a json representation.
  71007. * @return a JSON representation
  71008. */
  71009. ImageProcessingConfiguration.prototype.serialize = function () {
  71010. return BABYLON.SerializationHelper.Serialize(this);
  71011. };
  71012. /**
  71013. * Parses the image processing from a json representation.
  71014. * @param source the JSON source to parse
  71015. * @return The parsed image processing
  71016. */
  71017. ImageProcessingConfiguration.Parse = function (source) {
  71018. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  71019. };
  71020. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  71021. /**
  71022. * Used to apply the vignette as a mix with the pixel color.
  71023. */
  71024. get: function () {
  71025. return this._VIGNETTEMODE_MULTIPLY;
  71026. },
  71027. enumerable: true,
  71028. configurable: true
  71029. });
  71030. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  71031. /**
  71032. * Used to apply the vignette as a replacement of the pixel color.
  71033. */
  71034. get: function () {
  71035. return this._VIGNETTEMODE_OPAQUE;
  71036. },
  71037. enumerable: true,
  71038. configurable: true
  71039. });
  71040. // Static constants associated to the image processing.
  71041. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  71042. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  71043. __decorate([
  71044. BABYLON.serializeAsColorCurves()
  71045. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  71046. __decorate([
  71047. BABYLON.serialize()
  71048. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  71049. __decorate([
  71050. BABYLON.serializeAsTexture()
  71051. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  71052. __decorate([
  71053. BABYLON.serialize()
  71054. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  71055. __decorate([
  71056. BABYLON.serialize()
  71057. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  71058. __decorate([
  71059. BABYLON.serialize()
  71060. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  71061. __decorate([
  71062. BABYLON.serialize()
  71063. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  71064. __decorate([
  71065. BABYLON.serialize()
  71066. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  71067. __decorate([
  71068. BABYLON.serialize()
  71069. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  71070. __decorate([
  71071. BABYLON.serialize()
  71072. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  71073. __decorate([
  71074. BABYLON.serialize()
  71075. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  71076. __decorate([
  71077. BABYLON.serialize()
  71078. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  71079. __decorate([
  71080. BABYLON.serialize()
  71081. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  71082. __decorate([
  71083. BABYLON.serializeAsColor4()
  71084. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  71085. __decorate([
  71086. BABYLON.serialize()
  71087. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  71088. __decorate([
  71089. BABYLON.serialize()
  71090. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  71091. __decorate([
  71092. BABYLON.serialize()
  71093. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  71094. __decorate([
  71095. BABYLON.serialize()
  71096. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  71097. return ImageProcessingConfiguration;
  71098. }());
  71099. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  71100. })(BABYLON || (BABYLON = {}));
  71101. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  71102. var BABYLON;
  71103. (function (BABYLON) {
  71104. var serializedGeometries = [];
  71105. var serializeGeometry = function (geometry, serializationGeometries) {
  71106. if (serializedGeometries[geometry.id]) {
  71107. return;
  71108. }
  71109. if (geometry.doNotSerialize) {
  71110. return;
  71111. }
  71112. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  71113. serializationGeometries.boxes.push(geometry.serialize());
  71114. }
  71115. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  71116. serializationGeometries.spheres.push(geometry.serialize());
  71117. }
  71118. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  71119. serializationGeometries.cylinders.push(geometry.serialize());
  71120. }
  71121. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  71122. serializationGeometries.toruses.push(geometry.serialize());
  71123. }
  71124. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  71125. serializationGeometries.grounds.push(geometry.serialize());
  71126. }
  71127. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  71128. serializationGeometries.planes.push(geometry.serialize());
  71129. }
  71130. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  71131. serializationGeometries.torusKnots.push(geometry.serialize());
  71132. }
  71133. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  71134. throw new Error("Unknown primitive type");
  71135. }
  71136. else {
  71137. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  71138. }
  71139. serializedGeometries[geometry.id] = true;
  71140. };
  71141. var serializeMesh = function (mesh, serializationScene) {
  71142. var serializationObject = {};
  71143. // Geometry
  71144. var geometry = mesh._geometry;
  71145. if (geometry) {
  71146. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  71147. // 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
  71148. serializeGeometry(geometry, serializationScene.geometries);
  71149. }
  71150. }
  71151. // Custom
  71152. if (mesh.serialize) {
  71153. mesh.serialize(serializationObject);
  71154. }
  71155. return serializationObject;
  71156. };
  71157. var finalizeSingleMesh = function (mesh, serializationObject) {
  71158. //only works if the mesh is already loaded
  71159. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71160. //serialize material
  71161. if (mesh.material) {
  71162. if (mesh.material instanceof BABYLON.StandardMaterial) {
  71163. serializationObject.materials = serializationObject.materials || [];
  71164. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71165. serializationObject.materials.push(mesh.material.serialize());
  71166. }
  71167. }
  71168. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  71169. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  71170. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71171. serializationObject.multiMaterials.push(mesh.material.serialize());
  71172. }
  71173. }
  71174. }
  71175. //serialize geometry
  71176. var geometry = mesh._geometry;
  71177. if (geometry) {
  71178. if (!serializationObject.geometries) {
  71179. serializationObject.geometries = {};
  71180. serializationObject.geometries.boxes = [];
  71181. serializationObject.geometries.spheres = [];
  71182. serializationObject.geometries.cylinders = [];
  71183. serializationObject.geometries.toruses = [];
  71184. serializationObject.geometries.grounds = [];
  71185. serializationObject.geometries.planes = [];
  71186. serializationObject.geometries.torusKnots = [];
  71187. serializationObject.geometries.vertexData = [];
  71188. }
  71189. serializeGeometry(geometry, serializationObject.geometries);
  71190. }
  71191. // Skeletons
  71192. if (mesh.skeleton) {
  71193. serializationObject.skeletons = serializationObject.skeletons || [];
  71194. serializationObject.skeletons.push(mesh.skeleton.serialize());
  71195. }
  71196. //serialize the actual mesh
  71197. serializationObject.meshes = serializationObject.meshes || [];
  71198. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71199. }
  71200. };
  71201. var SceneSerializer = (function () {
  71202. function SceneSerializer() {
  71203. }
  71204. SceneSerializer.ClearCache = function () {
  71205. serializedGeometries = [];
  71206. };
  71207. SceneSerializer.Serialize = function (scene) {
  71208. var serializationObject = {};
  71209. SceneSerializer.ClearCache();
  71210. // Scene
  71211. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  71212. serializationObject.autoClear = scene.autoClear;
  71213. serializationObject.clearColor = scene.clearColor.asArray();
  71214. serializationObject.ambientColor = scene.ambientColor.asArray();
  71215. serializationObject.gravity = scene.gravity.asArray();
  71216. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  71217. serializationObject.workerCollisions = scene.workerCollisions;
  71218. // Fog
  71219. if (scene.fogMode && scene.fogMode !== 0) {
  71220. serializationObject.fogMode = scene.fogMode;
  71221. serializationObject.fogColor = scene.fogColor.asArray();
  71222. serializationObject.fogStart = scene.fogStart;
  71223. serializationObject.fogEnd = scene.fogEnd;
  71224. serializationObject.fogDensity = scene.fogDensity;
  71225. }
  71226. //Physics
  71227. if (scene.isPhysicsEnabled()) {
  71228. serializationObject.physicsEnabled = true;
  71229. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  71230. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  71231. }
  71232. // Metadata
  71233. if (scene.metadata) {
  71234. serializationObject.metadata = scene.metadata;
  71235. }
  71236. // Morph targets
  71237. serializationObject.morphTargetManagers = [];
  71238. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  71239. var abstractMesh = _a[_i];
  71240. var manager = abstractMesh.morphTargetManager;
  71241. if (manager) {
  71242. serializationObject.morphTargetManagers.push(manager.serialize());
  71243. }
  71244. }
  71245. // Lights
  71246. serializationObject.lights = [];
  71247. var index;
  71248. var light;
  71249. for (index = 0; index < scene.lights.length; index++) {
  71250. light = scene.lights[index];
  71251. if (!light.doNotSerialize) {
  71252. serializationObject.lights.push(light.serialize());
  71253. }
  71254. }
  71255. // Cameras
  71256. serializationObject.cameras = [];
  71257. for (index = 0; index < scene.cameras.length; index++) {
  71258. var camera = scene.cameras[index];
  71259. if (!camera.doNotSerialize) {
  71260. serializationObject.cameras.push(camera.serialize());
  71261. }
  71262. }
  71263. if (scene.activeCamera) {
  71264. serializationObject.activeCameraID = scene.activeCamera.id;
  71265. }
  71266. // Animations
  71267. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  71268. // Materials
  71269. serializationObject.materials = [];
  71270. serializationObject.multiMaterials = [];
  71271. var material;
  71272. for (index = 0; index < scene.materials.length; index++) {
  71273. material = scene.materials[index];
  71274. if (!material.doNotSerialize) {
  71275. serializationObject.materials.push(material.serialize());
  71276. }
  71277. }
  71278. // MultiMaterials
  71279. serializationObject.multiMaterials = [];
  71280. for (index = 0; index < scene.multiMaterials.length; index++) {
  71281. var multiMaterial = scene.multiMaterials[index];
  71282. serializationObject.multiMaterials.push(multiMaterial.serialize());
  71283. }
  71284. // Skeletons
  71285. serializationObject.skeletons = [];
  71286. for (index = 0; index < scene.skeletons.length; index++) {
  71287. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  71288. }
  71289. // Geometries
  71290. serializationObject.geometries = {};
  71291. serializationObject.geometries.boxes = [];
  71292. serializationObject.geometries.spheres = [];
  71293. serializationObject.geometries.cylinders = [];
  71294. serializationObject.geometries.toruses = [];
  71295. serializationObject.geometries.grounds = [];
  71296. serializationObject.geometries.planes = [];
  71297. serializationObject.geometries.torusKnots = [];
  71298. serializationObject.geometries.vertexData = [];
  71299. serializedGeometries = [];
  71300. var geometries = scene.getGeometries();
  71301. for (index = 0; index < geometries.length; index++) {
  71302. var geometry = geometries[index];
  71303. if (geometry.isReady()) {
  71304. serializeGeometry(geometry, serializationObject.geometries);
  71305. }
  71306. }
  71307. // Meshes
  71308. serializationObject.meshes = [];
  71309. for (index = 0; index < scene.meshes.length; index++) {
  71310. var abstractMesh = scene.meshes[index];
  71311. if (abstractMesh instanceof BABYLON.Mesh) {
  71312. var mesh = abstractMesh;
  71313. if (!mesh.doNotSerialize) {
  71314. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71315. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71316. }
  71317. }
  71318. }
  71319. }
  71320. // Particles Systems
  71321. serializationObject.particleSystems = [];
  71322. for (index = 0; index < scene.particleSystems.length; index++) {
  71323. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  71324. }
  71325. // Lens flares
  71326. serializationObject.lensFlareSystems = [];
  71327. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  71328. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  71329. }
  71330. // Shadows
  71331. serializationObject.shadowGenerators = [];
  71332. for (index = 0; index < scene.lights.length; index++) {
  71333. light = scene.lights[index];
  71334. var shadowGenerator = light.getShadowGenerator();
  71335. if (shadowGenerator) {
  71336. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71337. }
  71338. }
  71339. // Action Manager
  71340. if (scene.actionManager) {
  71341. serializationObject.actions = scene.actionManager.serialize("scene");
  71342. }
  71343. // Audio
  71344. serializationObject.sounds = [];
  71345. for (index = 0; index < scene.soundTracks.length; index++) {
  71346. var soundtrack = scene.soundTracks[index];
  71347. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71348. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71349. }
  71350. }
  71351. return serializationObject;
  71352. };
  71353. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  71354. if (withParents === void 0) { withParents = false; }
  71355. if (withChildren === void 0) { withChildren = false; }
  71356. var serializationObject = {};
  71357. SceneSerializer.ClearCache();
  71358. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  71359. if (withParents || withChildren) {
  71360. //deliberate for loop! not for each, appended should be processed as well.
  71361. for (var i = 0; i < toSerialize.length; ++i) {
  71362. if (withChildren) {
  71363. toSerialize[i].getDescendants().forEach(function (node) {
  71364. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  71365. toSerialize.push(node);
  71366. }
  71367. });
  71368. }
  71369. //make sure the array doesn't contain the object already
  71370. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  71371. toSerialize.push(toSerialize[i].parent);
  71372. }
  71373. }
  71374. }
  71375. toSerialize.forEach(function (mesh) {
  71376. finalizeSingleMesh(mesh, serializationObject);
  71377. });
  71378. return serializationObject;
  71379. };
  71380. return SceneSerializer;
  71381. }());
  71382. BABYLON.SceneSerializer = SceneSerializer;
  71383. })(BABYLON || (BABYLON = {}));
  71384. //# sourceMappingURL=babylon.sceneSerializer.js.map
  71385. var BABYLON;
  71386. (function (BABYLON) {
  71387. var ReflectionProbe = (function () {
  71388. function ReflectionProbe(name, size, scene, generateMipMaps) {
  71389. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71390. var _this = this;
  71391. this.name = name;
  71392. this._viewMatrix = BABYLON.Matrix.Identity();
  71393. this._target = BABYLON.Vector3.Zero();
  71394. this._add = BABYLON.Vector3.Zero();
  71395. this.invertYAxis = false;
  71396. this.position = BABYLON.Vector3.Zero();
  71397. this._scene = scene;
  71398. this._scene.reflectionProbes.push(this);
  71399. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  71400. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  71401. switch (faceIndex) {
  71402. case 0:
  71403. _this._add.copyFromFloats(1, 0, 0);
  71404. break;
  71405. case 1:
  71406. _this._add.copyFromFloats(-1, 0, 0);
  71407. break;
  71408. case 2:
  71409. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  71410. break;
  71411. case 3:
  71412. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  71413. break;
  71414. case 4:
  71415. _this._add.copyFromFloats(0, 0, 1);
  71416. break;
  71417. case 5:
  71418. _this._add.copyFromFloats(0, 0, -1);
  71419. break;
  71420. }
  71421. if (_this._attachedMesh) {
  71422. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  71423. }
  71424. _this.position.addToRef(_this._add, _this._target);
  71425. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  71426. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  71427. });
  71428. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  71429. scene.updateTransformMatrix(true);
  71430. });
  71431. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  71432. }
  71433. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  71434. get: function () {
  71435. return this._renderTargetTexture.samples;
  71436. },
  71437. set: function (value) {
  71438. this._renderTargetTexture.samples = value;
  71439. },
  71440. enumerable: true,
  71441. configurable: true
  71442. });
  71443. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  71444. get: function () {
  71445. return this._renderTargetTexture.refreshRate;
  71446. },
  71447. set: function (value) {
  71448. this._renderTargetTexture.refreshRate = value;
  71449. },
  71450. enumerable: true,
  71451. configurable: true
  71452. });
  71453. ReflectionProbe.prototype.getScene = function () {
  71454. return this._scene;
  71455. };
  71456. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  71457. get: function () {
  71458. return this._renderTargetTexture;
  71459. },
  71460. enumerable: true,
  71461. configurable: true
  71462. });
  71463. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  71464. get: function () {
  71465. return this._renderTargetTexture.renderList;
  71466. },
  71467. enumerable: true,
  71468. configurable: true
  71469. });
  71470. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  71471. this._attachedMesh = mesh;
  71472. };
  71473. /**
  71474. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71475. *
  71476. * @param renderingGroupId The rendering group id corresponding to its index
  71477. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71478. */
  71479. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71480. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71481. };
  71482. ReflectionProbe.prototype.dispose = function () {
  71483. var index = this._scene.reflectionProbes.indexOf(this);
  71484. if (index !== -1) {
  71485. // Remove from the scene if found
  71486. this._scene.reflectionProbes.splice(index, 1);
  71487. }
  71488. if (this._renderTargetTexture) {
  71489. this._renderTargetTexture.dispose();
  71490. this._renderTargetTexture = null;
  71491. }
  71492. };
  71493. return ReflectionProbe;
  71494. }());
  71495. BABYLON.ReflectionProbe = ReflectionProbe;
  71496. })(BABYLON || (BABYLON = {}));
  71497. //# sourceMappingURL=babylon.reflectionProbe.js.map
  71498. var BABYLON;
  71499. (function (BABYLON) {
  71500. var Layer = (function () {
  71501. function Layer(name, imgUrl, scene, isBackground, color) {
  71502. this.name = name;
  71503. this.scale = new BABYLON.Vector2(1, 1);
  71504. this.offset = new BABYLON.Vector2(0, 0);
  71505. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  71506. this.layerMask = 0x0FFFFFFF;
  71507. this._vertexBuffers = {};
  71508. // Events
  71509. /**
  71510. * An event triggered when the layer is disposed.
  71511. * @type {BABYLON.Observable}
  71512. */
  71513. this.onDisposeObservable = new BABYLON.Observable();
  71514. /**
  71515. * An event triggered before rendering the scene
  71516. * @type {BABYLON.Observable}
  71517. */
  71518. this.onBeforeRenderObservable = new BABYLON.Observable();
  71519. /**
  71520. * An event triggered after rendering the scene
  71521. * @type {BABYLON.Observable}
  71522. */
  71523. this.onAfterRenderObservable = new BABYLON.Observable();
  71524. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  71525. this.isBackground = isBackground === undefined ? true : isBackground;
  71526. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  71527. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71528. this._scene.layers.push(this);
  71529. var engine = this._scene.getEngine();
  71530. // VBO
  71531. var vertices = [];
  71532. vertices.push(1, 1);
  71533. vertices.push(-1, 1);
  71534. vertices.push(-1, -1);
  71535. vertices.push(1, -1);
  71536. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71537. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71538. this._createIndexBuffer();
  71539. // Effects
  71540. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  71541. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  71542. }
  71543. Object.defineProperty(Layer.prototype, "onDispose", {
  71544. set: function (callback) {
  71545. if (this._onDisposeObserver) {
  71546. this.onDisposeObservable.remove(this._onDisposeObserver);
  71547. }
  71548. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  71549. },
  71550. enumerable: true,
  71551. configurable: true
  71552. });
  71553. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  71554. set: function (callback) {
  71555. if (this._onBeforeRenderObserver) {
  71556. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71557. }
  71558. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71559. },
  71560. enumerable: true,
  71561. configurable: true
  71562. });
  71563. Object.defineProperty(Layer.prototype, "onAfterRender", {
  71564. set: function (callback) {
  71565. if (this._onAfterRenderObserver) {
  71566. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71567. }
  71568. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71569. },
  71570. enumerable: true,
  71571. configurable: true
  71572. });
  71573. Layer.prototype._createIndexBuffer = function () {
  71574. var engine = this._scene.getEngine();
  71575. // Indices
  71576. var indices = [];
  71577. indices.push(0);
  71578. indices.push(1);
  71579. indices.push(2);
  71580. indices.push(0);
  71581. indices.push(2);
  71582. indices.push(3);
  71583. this._indexBuffer = engine.createIndexBuffer(indices);
  71584. };
  71585. Layer.prototype._rebuild = function () {
  71586. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  71587. this._createIndexBuffer();
  71588. };
  71589. Layer.prototype.render = function () {
  71590. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  71591. // Check
  71592. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  71593. return;
  71594. var engine = this._scene.getEngine();
  71595. this.onBeforeRenderObservable.notifyObservers(this);
  71596. // Render
  71597. engine.enableEffect(currentEffect);
  71598. engine.setState(false);
  71599. // Texture
  71600. currentEffect.setTexture("textureSampler", this.texture);
  71601. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  71602. // Color
  71603. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  71604. // Scale / offset
  71605. currentEffect.setVector2("offset", this.offset);
  71606. currentEffect.setVector2("scale", this.scale);
  71607. // VBOs
  71608. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  71609. // Draw order
  71610. if (!this.alphaTest) {
  71611. engine.setAlphaMode(this.alphaBlendingMode);
  71612. engine.draw(true, 0, 6);
  71613. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71614. }
  71615. else {
  71616. engine.draw(true, 0, 6);
  71617. }
  71618. this.onAfterRenderObservable.notifyObservers(this);
  71619. };
  71620. Layer.prototype.dispose = function () {
  71621. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71622. if (vertexBuffer) {
  71623. vertexBuffer.dispose();
  71624. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71625. }
  71626. if (this._indexBuffer) {
  71627. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71628. this._indexBuffer = null;
  71629. }
  71630. if (this.texture) {
  71631. this.texture.dispose();
  71632. this.texture = null;
  71633. }
  71634. // Remove from scene
  71635. var index = this._scene.layers.indexOf(this);
  71636. this._scene.layers.splice(index, 1);
  71637. // Callback
  71638. this.onDisposeObservable.notifyObservers(this);
  71639. this.onDisposeObservable.clear();
  71640. this.onAfterRenderObservable.clear();
  71641. this.onBeforeRenderObservable.clear();
  71642. };
  71643. return Layer;
  71644. }());
  71645. BABYLON.Layer = Layer;
  71646. })(BABYLON || (BABYLON = {}));
  71647. //# sourceMappingURL=babylon.layer.js.map
  71648. var BABYLON;
  71649. (function (BABYLON) {
  71650. var TextureTools = (function () {
  71651. function TextureTools() {
  71652. }
  71653. /**
  71654. * Uses the GPU to create a copy texture rescaled at a given size
  71655. * @param texture Texture to copy from
  71656. * @param width Desired width
  71657. * @param height Desired height
  71658. * @return Generated texture
  71659. */
  71660. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  71661. if (useBilinearMode === void 0) { useBilinearMode = true; }
  71662. var scene = texture.getScene();
  71663. var engine = scene.getEngine();
  71664. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  71665. rtt.wrapU = texture.wrapU;
  71666. rtt.wrapV = texture.wrapV;
  71667. rtt.uOffset = texture.uOffset;
  71668. rtt.vOffset = texture.vOffset;
  71669. rtt.uScale = texture.uScale;
  71670. rtt.vScale = texture.vScale;
  71671. rtt.uAng = texture.uAng;
  71672. rtt.vAng = texture.vAng;
  71673. rtt.wAng = texture.wAng;
  71674. rtt.coordinatesIndex = texture.coordinatesIndex;
  71675. rtt.level = texture.level;
  71676. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  71677. rtt._texture.isReady = false;
  71678. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71679. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71680. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71681. passPostProcess.getEffect().executeWhenCompiled(function () {
  71682. passPostProcess.onApply = function (effect) {
  71683. effect.setTexture("textureSampler", texture);
  71684. };
  71685. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  71686. engine.unBindFramebuffer(rtt.getInternalTexture());
  71687. rtt.disposeFramebufferObjects();
  71688. passPostProcess.dispose();
  71689. rtt._texture.isReady = true;
  71690. });
  71691. return rtt;
  71692. };
  71693. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  71694. if (!scene._environmentBRDFTexture) {
  71695. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71696. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71697. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71698. scene._environmentBRDFTexture = texture;
  71699. }
  71700. return scene._environmentBRDFTexture;
  71701. };
  71702. 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=";
  71703. return TextureTools;
  71704. }());
  71705. BABYLON.TextureTools = TextureTools;
  71706. })(BABYLON || (BABYLON = {}));
  71707. //# sourceMappingURL=babylon.textureTools.js.map
  71708. var BABYLON;
  71709. (function (BABYLON) {
  71710. var FramingBehavior = (function () {
  71711. function FramingBehavior() {
  71712. this._mode = FramingBehavior.FitFrustumSidesMode;
  71713. this._radiusScale = 1.0;
  71714. this._positionScale = 0.5;
  71715. this._defaultElevation = 0.3;
  71716. this._elevationReturnTime = 1500;
  71717. this._elevationReturnWaitTime = 1000;
  71718. this._zoomStopsAnimation = false;
  71719. this._framingTime = 1500;
  71720. this._isPointerDown = false;
  71721. this._lastFrameTime = null;
  71722. this._lastInteractionTime = -Infinity;
  71723. // Framing control
  71724. this._animatables = new Array();
  71725. this._betaIsAnimating = false;
  71726. this._lastFrameRadius = 0;
  71727. }
  71728. Object.defineProperty(FramingBehavior.prototype, "name", {
  71729. get: function () {
  71730. return "Framing";
  71731. },
  71732. enumerable: true,
  71733. configurable: true
  71734. });
  71735. Object.defineProperty(FramingBehavior.prototype, "mode", {
  71736. /**
  71737. * Gets current mode used by the behavior.
  71738. */
  71739. get: function () {
  71740. return this._mode;
  71741. },
  71742. /**
  71743. * Sets the current mode used by the behavior
  71744. */
  71745. set: function (mode) {
  71746. this._mode = mode;
  71747. },
  71748. enumerable: true,
  71749. configurable: true
  71750. });
  71751. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  71752. /**
  71753. * Gets the scale applied to the radius
  71754. */
  71755. get: function () {
  71756. return this._radiusScale;
  71757. },
  71758. /**
  71759. * Sets the scale applied to the radius (1 by default)
  71760. */
  71761. set: function (radius) {
  71762. this._radiusScale = radius;
  71763. },
  71764. enumerable: true,
  71765. configurable: true
  71766. });
  71767. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  71768. /**
  71769. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71770. */
  71771. get: function () {
  71772. return this._positionScale;
  71773. },
  71774. /**
  71775. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71776. */
  71777. set: function (scale) {
  71778. this._positionScale = scale;
  71779. },
  71780. enumerable: true,
  71781. configurable: true
  71782. });
  71783. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  71784. /**
  71785. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71786. * behaviour is triggered, in radians.
  71787. */
  71788. get: function () {
  71789. return this._defaultElevation;
  71790. },
  71791. /**
  71792. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  71793. * behaviour is triggered, in radians.
  71794. */
  71795. set: function (elevation) {
  71796. this._defaultElevation = elevation;
  71797. },
  71798. enumerable: true,
  71799. configurable: true
  71800. });
  71801. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  71802. /**
  71803. * Gets the time (in milliseconds) taken to return to the default beta position.
  71804. * Negative value indicates camera should not return to default.
  71805. */
  71806. get: function () {
  71807. return this._elevationReturnTime;
  71808. },
  71809. /**
  71810. * Sets the time (in milliseconds) taken to return to the default beta position.
  71811. * Negative value indicates camera should not return to default.
  71812. */
  71813. set: function (speed) {
  71814. this._elevationReturnTime = speed;
  71815. },
  71816. enumerable: true,
  71817. configurable: true
  71818. });
  71819. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  71820. /**
  71821. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71822. */
  71823. get: function () {
  71824. return this._elevationReturnWaitTime;
  71825. },
  71826. /**
  71827. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  71828. */
  71829. set: function (time) {
  71830. this._elevationReturnWaitTime = time;
  71831. },
  71832. enumerable: true,
  71833. configurable: true
  71834. });
  71835. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  71836. /**
  71837. * Gets the flag that indicates if user zooming should stop animation.
  71838. */
  71839. get: function () {
  71840. return this._zoomStopsAnimation;
  71841. },
  71842. /**
  71843. * Sets the flag that indicates if user zooming should stop animation.
  71844. */
  71845. set: function (flag) {
  71846. this._zoomStopsAnimation = flag;
  71847. },
  71848. enumerable: true,
  71849. configurable: true
  71850. });
  71851. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  71852. /**
  71853. * Gets the transition time when framing the mesh, in milliseconds
  71854. */
  71855. get: function () {
  71856. return this._framingTime;
  71857. },
  71858. /**
  71859. * Sets the transition time when framing the mesh, in milliseconds
  71860. */
  71861. set: function (time) {
  71862. this._framingTime = time;
  71863. },
  71864. enumerable: true,
  71865. configurable: true
  71866. });
  71867. FramingBehavior.prototype.attach = function (camera) {
  71868. var _this = this;
  71869. this._attachedCamera = camera;
  71870. var scene = this._attachedCamera.getScene();
  71871. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  71872. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71873. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71874. _this._isPointerDown = true;
  71875. return;
  71876. }
  71877. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71878. _this._isPointerDown = false;
  71879. }
  71880. });
  71881. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  71882. if (mesh) {
  71883. _this.zoomOnMesh(mesh);
  71884. }
  71885. });
  71886. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71887. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71888. _this._applyUserInteraction();
  71889. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  71890. // back to the default position after a given timeout
  71891. _this._maintainCameraAboveGround();
  71892. });
  71893. };
  71894. FramingBehavior.prototype.detach = function () {
  71895. var scene = this._attachedCamera.getScene();
  71896. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71897. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71898. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71899. this._attachedCamera = null;
  71900. };
  71901. /**
  71902. * Targets the given mesh and updates zoom level accordingly.
  71903. * @param mesh The mesh to target.
  71904. * @param radius Optional. If a cached radius position already exists, overrides default.
  71905. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71906. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71907. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71908. */
  71909. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  71910. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71911. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71912. mesh.computeWorldMatrix(true);
  71913. var boundingBox = mesh.getBoundingInfo().boundingBox;
  71914. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  71915. };
  71916. /**
  71917. * Targets the given mesh and updates zoom level accordingly.
  71918. * @param mesh The mesh to target.
  71919. * @param radius Optional. If a cached radius position already exists, overrides default.
  71920. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  71921. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  71922. * @param onAnimationEnd Callback triggered at the end of the framing animation
  71923. */
  71924. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  71925. var _this = this;
  71926. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  71927. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  71928. var zoomTarget;
  71929. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  71930. var bottom = minimumWorld.y;
  71931. var top = maximumWorld.y;
  71932. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  71933. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  71934. if (focusOnOriginXZ) {
  71935. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  71936. }
  71937. else {
  71938. var centerWorld = minimumWorld.add(radiusWorld);
  71939. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  71940. }
  71941. if (!this._vectorTransition) {
  71942. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  71943. }
  71944. this._betaIsAnimating = true;
  71945. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  71946. // sets the radius and lower radius bounds
  71947. // Small delta ensures camera is not always at lower zoom limit.
  71948. var delta = 0.1;
  71949. var radius = 0;
  71950. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  71951. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71952. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  71953. radius = position;
  71954. }
  71955. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71956. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  71957. if (this._attachedCamera.lowerRadiusLimit === null) {
  71958. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  71959. }
  71960. }
  71961. // Set sensibilities
  71962. var extend = maximumWorld.subtract(minimumWorld).length();
  71963. this._attachedCamera.panningSensibility = 5000 / extend;
  71964. this._attachedCamera.wheelPrecision = 100 / radius;
  71965. // transition to new radius
  71966. if (!this._radiusTransition) {
  71967. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  71968. }
  71969. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  71970. if (onAnimationEnd) {
  71971. onAnimationEnd();
  71972. }
  71973. _this._attachedCamera.storeState();
  71974. }));
  71975. };
  71976. /**
  71977. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  71978. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  71979. * frustum width.
  71980. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  71981. * to fully enclose the mesh in the viewing frustum.
  71982. */
  71983. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  71984. var size = maximumWorld.subtract(minimumWorld);
  71985. var boxVectorGlobalDiagonal = size.length();
  71986. var frustumSlope = this._getFrustumSlope();
  71987. // Formula for setting distance
  71988. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  71989. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  71990. // Horizon distance
  71991. var radius = radiusWithoutFraming * this._radiusScale;
  71992. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  71993. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  71994. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  71995. var camera = this._attachedCamera;
  71996. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  71997. // Don't exceed the requested limit
  71998. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  71999. }
  72000. // Don't exceed the upper radius limit
  72001. if (camera.upperRadiusLimit) {
  72002. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  72003. }
  72004. return distance;
  72005. };
  72006. /**
  72007. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  72008. * is automatically returned to its default position (expected to be above ground plane).
  72009. */
  72010. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  72011. var _this = this;
  72012. if (this._elevationReturnTime < 0) {
  72013. return;
  72014. }
  72015. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  72016. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  72017. var limitBeta = Math.PI * 0.5;
  72018. // Bring the camera back up if below the ground plane
  72019. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  72020. this._betaIsAnimating = true;
  72021. //Transition to new position
  72022. this.stopAllAnimations();
  72023. if (!this._betaTransition) {
  72024. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  72025. }
  72026. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  72027. _this._clearAnimationLocks();
  72028. _this.stopAllAnimations();
  72029. }));
  72030. }
  72031. };
  72032. /**
  72033. * Returns the frustum slope based on the canvas ratio and camera FOV
  72034. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  72035. */
  72036. FramingBehavior.prototype._getFrustumSlope = function () {
  72037. // Calculate the viewport ratio
  72038. // Aspect Ratio is Height/Width.
  72039. var camera = this._attachedCamera;
  72040. var engine = camera.getScene().getEngine();
  72041. var aspectRatio = engine.getAspectRatio(camera);
  72042. // Camera FOV is the vertical field of view (top-bottom) in radians.
  72043. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  72044. var frustumSlopeY = Math.tan(camera.fov / 2);
  72045. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  72046. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  72047. // along the forward vector.
  72048. var frustumSlopeX = frustumSlopeY * aspectRatio;
  72049. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  72050. };
  72051. /**
  72052. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  72053. */
  72054. FramingBehavior.prototype._clearAnimationLocks = function () {
  72055. this._betaIsAnimating = false;
  72056. };
  72057. /**
  72058. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72059. */
  72060. FramingBehavior.prototype._applyUserInteraction = function () {
  72061. if (this.isUserIsMoving) {
  72062. this._lastInteractionTime = BABYLON.Tools.Now;
  72063. this.stopAllAnimations();
  72064. this._clearAnimationLocks();
  72065. }
  72066. };
  72067. /**
  72068. * Stops and removes all animations that have been applied to the camera
  72069. */
  72070. FramingBehavior.prototype.stopAllAnimations = function () {
  72071. this._attachedCamera.animations = [];
  72072. while (this._animatables.length) {
  72073. if (this._animatables[0]) {
  72074. this._animatables[0].onAnimationEnd = null;
  72075. this._animatables[0].stop();
  72076. }
  72077. this._animatables.shift();
  72078. }
  72079. };
  72080. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  72081. /**
  72082. * Gets a value indicating if the user is moving the camera
  72083. */
  72084. get: function () {
  72085. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72086. this._attachedCamera.inertialBetaOffset !== 0 ||
  72087. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72088. this._attachedCamera.inertialPanningX !== 0 ||
  72089. this._attachedCamera.inertialPanningY !== 0 ||
  72090. this._isPointerDown;
  72091. },
  72092. enumerable: true,
  72093. configurable: true
  72094. });
  72095. /**
  72096. * The easing function used by animations
  72097. */
  72098. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  72099. /**
  72100. * The easing mode used by animations
  72101. */
  72102. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  72103. // Statics
  72104. /**
  72105. * The camera can move all the way towards the mesh.
  72106. */
  72107. FramingBehavior.IgnoreBoundsSizeMode = 0;
  72108. /**
  72109. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  72110. */
  72111. FramingBehavior.FitFrustumSidesMode = 1;
  72112. return FramingBehavior;
  72113. }());
  72114. BABYLON.FramingBehavior = FramingBehavior;
  72115. })(BABYLON || (BABYLON = {}));
  72116. //# sourceMappingURL=babylon.framingBehavior.js.map
  72117. var BABYLON;
  72118. (function (BABYLON) {
  72119. /**
  72120. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  72121. */
  72122. var BouncingBehavior = (function () {
  72123. function BouncingBehavior() {
  72124. /**
  72125. * The duration of the animation, in milliseconds
  72126. */
  72127. this.transitionDuration = 450;
  72128. /**
  72129. * Length of the distance animated by the transition when lower radius is reached
  72130. */
  72131. this.lowerRadiusTransitionRange = 2;
  72132. /**
  72133. * Length of the distance animated by the transition when upper radius is reached
  72134. */
  72135. this.upperRadiusTransitionRange = -2;
  72136. this._autoTransitionRange = false;
  72137. // Animations
  72138. this._radiusIsAnimating = false;
  72139. this._radiusBounceTransition = null;
  72140. this._animatables = new Array();
  72141. }
  72142. Object.defineProperty(BouncingBehavior.prototype, "name", {
  72143. get: function () {
  72144. return "Bouncing";
  72145. },
  72146. enumerable: true,
  72147. configurable: true
  72148. });
  72149. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  72150. /**
  72151. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72152. */
  72153. get: function () {
  72154. return this._autoTransitionRange;
  72155. },
  72156. /**
  72157. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72158. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  72159. */
  72160. set: function (value) {
  72161. var _this = this;
  72162. if (this._autoTransitionRange === value) {
  72163. return;
  72164. }
  72165. this._autoTransitionRange = value;
  72166. var camera = this._attachedCamera;
  72167. if (value) {
  72168. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72169. if (!mesh) {
  72170. return;
  72171. }
  72172. mesh.computeWorldMatrix(true);
  72173. var diagonal = mesh.getBoundingInfo().diagonalLength;
  72174. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  72175. _this.upperRadiusTransitionRange = diagonal * 0.05;
  72176. });
  72177. }
  72178. else if (this._onMeshTargetChangedObserver) {
  72179. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72180. }
  72181. },
  72182. enumerable: true,
  72183. configurable: true
  72184. });
  72185. BouncingBehavior.prototype.attach = function (camera) {
  72186. var _this = this;
  72187. this._attachedCamera = camera;
  72188. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72189. // Add the bounce animation to the lower radius limit
  72190. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  72191. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  72192. }
  72193. // Add the bounce animation to the upper radius limit
  72194. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  72195. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  72196. }
  72197. });
  72198. };
  72199. BouncingBehavior.prototype.detach = function () {
  72200. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72201. if (this._onMeshTargetChangedObserver) {
  72202. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72203. }
  72204. this._attachedCamera = null;
  72205. };
  72206. /**
  72207. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  72208. * @param radiusLimit The limit to check against.
  72209. * @return Bool to indicate if at limit.
  72210. */
  72211. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  72212. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  72213. return true;
  72214. }
  72215. return false;
  72216. };
  72217. /**
  72218. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  72219. * @param radiusDelta The delta by which to animate to. Can be negative.
  72220. */
  72221. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  72222. var _this = this;
  72223. if (!this._radiusBounceTransition) {
  72224. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  72225. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  72226. }
  72227. // Prevent zoom until bounce has completed
  72228. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  72229. this._attachedCamera.wheelPrecision = Infinity;
  72230. this._attachedCamera.inertialRadiusOffset = 0;
  72231. // Animate to the radius limit
  72232. this.stopAllAnimations();
  72233. this._radiusIsAnimating = true;
  72234. 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(); }));
  72235. };
  72236. /**
  72237. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  72238. */
  72239. BouncingBehavior.prototype._clearAnimationLocks = function () {
  72240. this._radiusIsAnimating = false;
  72241. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  72242. };
  72243. /**
  72244. * Stops and removes all animations that have been applied to the camera
  72245. */
  72246. BouncingBehavior.prototype.stopAllAnimations = function () {
  72247. this._attachedCamera.animations = [];
  72248. while (this._animatables.length) {
  72249. this._animatables[0].onAnimationEnd = null;
  72250. this._animatables[0].stop();
  72251. this._animatables.shift();
  72252. }
  72253. };
  72254. /**
  72255. * The easing function used by animations
  72256. */
  72257. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  72258. /**
  72259. * The easing mode used by animations
  72260. */
  72261. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  72262. return BouncingBehavior;
  72263. }());
  72264. BABYLON.BouncingBehavior = BouncingBehavior;
  72265. })(BABYLON || (BABYLON = {}));
  72266. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  72267. var BABYLON;
  72268. (function (BABYLON) {
  72269. var AutoRotationBehavior = (function () {
  72270. function AutoRotationBehavior() {
  72271. this._zoomStopsAnimation = false;
  72272. this._idleRotationSpeed = 0.05;
  72273. this._idleRotationWaitTime = 2000;
  72274. this._idleRotationSpinupTime = 2000;
  72275. this._isPointerDown = false;
  72276. this._lastFrameTime = null;
  72277. this._lastInteractionTime = -Infinity;
  72278. this._cameraRotationSpeed = 0;
  72279. this._lastFrameRadius = 0;
  72280. }
  72281. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  72282. get: function () {
  72283. return "AutoRotation";
  72284. },
  72285. enumerable: true,
  72286. configurable: true
  72287. });
  72288. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  72289. /**
  72290. * Gets the flag that indicates if user zooming should stop animation.
  72291. */
  72292. get: function () {
  72293. return this._zoomStopsAnimation;
  72294. },
  72295. /**
  72296. * Sets the flag that indicates if user zooming should stop animation.
  72297. */
  72298. set: function (flag) {
  72299. this._zoomStopsAnimation = flag;
  72300. },
  72301. enumerable: true,
  72302. configurable: true
  72303. });
  72304. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  72305. /**
  72306. * Gets the default speed at which the camera rotates around the model.
  72307. */
  72308. get: function () {
  72309. return this._idleRotationSpeed;
  72310. },
  72311. /**
  72312. * Sets the default speed at which the camera rotates around the model.
  72313. */
  72314. set: function (speed) {
  72315. this._idleRotationSpeed = speed;
  72316. },
  72317. enumerable: true,
  72318. configurable: true
  72319. });
  72320. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  72321. /**
  72322. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  72323. */
  72324. get: function () {
  72325. return this._idleRotationWaitTime;
  72326. },
  72327. /**
  72328. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  72329. */
  72330. set: function (time) {
  72331. this._idleRotationWaitTime = time;
  72332. },
  72333. enumerable: true,
  72334. configurable: true
  72335. });
  72336. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  72337. /**
  72338. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72339. */
  72340. get: function () {
  72341. return this._idleRotationSpinupTime;
  72342. },
  72343. /**
  72344. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72345. */
  72346. set: function (time) {
  72347. this._idleRotationSpinupTime = time;
  72348. },
  72349. enumerable: true,
  72350. configurable: true
  72351. });
  72352. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  72353. /**
  72354. * Gets a value indicating if the camera is currently rotating because of this behavior
  72355. */
  72356. get: function () {
  72357. return Math.abs(this._cameraRotationSpeed) > 0;
  72358. },
  72359. enumerable: true,
  72360. configurable: true
  72361. });
  72362. AutoRotationBehavior.prototype.attach = function (camera) {
  72363. var _this = this;
  72364. this._attachedCamera = camera;
  72365. var scene = this._attachedCamera.getScene();
  72366. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  72367. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72368. _this._isPointerDown = true;
  72369. return;
  72370. }
  72371. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  72372. _this._isPointerDown = false;
  72373. }
  72374. });
  72375. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72376. var now = BABYLON.Tools.Now;
  72377. var dt = 0;
  72378. if (_this._lastFrameTime != null) {
  72379. dt = now - _this._lastFrameTime;
  72380. }
  72381. _this._lastFrameTime = now;
  72382. // Stop the animation if there is user interaction and the animation should stop for this interaction
  72383. _this._applyUserInteraction();
  72384. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  72385. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  72386. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  72387. // Step camera rotation by rotation speed
  72388. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  72389. });
  72390. };
  72391. AutoRotationBehavior.prototype.detach = function () {
  72392. var scene = this._attachedCamera.getScene();
  72393. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  72394. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72395. this._attachedCamera = null;
  72396. };
  72397. /**
  72398. * Returns true if user is scrolling.
  72399. * @return true if user is scrolling.
  72400. */
  72401. AutoRotationBehavior.prototype._userIsZooming = function () {
  72402. return this._attachedCamera.inertialRadiusOffset !== 0;
  72403. };
  72404. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  72405. var zoomHasHitLimit = false;
  72406. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  72407. zoomHasHitLimit = true;
  72408. }
  72409. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  72410. this._lastFrameRadius = this._attachedCamera.radius;
  72411. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  72412. };
  72413. /**
  72414. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72415. */
  72416. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  72417. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  72418. this._lastInteractionTime = BABYLON.Tools.Now;
  72419. }
  72420. };
  72421. // Tools
  72422. AutoRotationBehavior.prototype._userIsMoving = function () {
  72423. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72424. this._attachedCamera.inertialBetaOffset !== 0 ||
  72425. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72426. this._attachedCamera.inertialPanningX !== 0 ||
  72427. this._attachedCamera.inertialPanningY !== 0 ||
  72428. this._isPointerDown;
  72429. };
  72430. return AutoRotationBehavior;
  72431. }());
  72432. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  72433. })(BABYLON || (BABYLON = {}));
  72434. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  72435. 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#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\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\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  72436. 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 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\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 vec2 vTangentSpaceParams;\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 vTangentSpaceParams;\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 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\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 vec2 vTangentSpaceParams;\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 vec2 vTangentSpaceParams;\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};"};
  72437. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72438. var BABYLON;
  72439. (function (BABYLON) {
  72440. var GridMaterialDefines = (function (_super) {
  72441. __extends(GridMaterialDefines, _super);
  72442. function GridMaterialDefines() {
  72443. var _this = _super.call(this) || this;
  72444. _this.TRANSPARENT = false;
  72445. _this.FOG = false;
  72446. _this.PREMULTIPLYALPHA = false;
  72447. _this.rebuild();
  72448. return _this;
  72449. }
  72450. return GridMaterialDefines;
  72451. }(BABYLON.MaterialDefines));
  72452. /**
  72453. * The grid materials allows you to wrap any shape with a grid.
  72454. * Colors are customizable.
  72455. */
  72456. var GridMaterial = (function (_super) {
  72457. __extends(GridMaterial, _super);
  72458. /**
  72459. * constructor
  72460. * @param name The name given to the material in order to identify it afterwards.
  72461. * @param scene The scene the material is used in.
  72462. */
  72463. function GridMaterial(name, scene) {
  72464. var _this = _super.call(this, name, scene) || this;
  72465. /**
  72466. * Main color of the grid (e.g. between lines)
  72467. */
  72468. _this.mainColor = BABYLON.Color3.Black();
  72469. /**
  72470. * Color of the grid lines.
  72471. */
  72472. _this.lineColor = BABYLON.Color3.Teal();
  72473. /**
  72474. * The scale of the grid compared to unit.
  72475. */
  72476. _this.gridRatio = 1.0;
  72477. /**
  72478. * Allows setting an offset for the grid lines.
  72479. */
  72480. _this.gridOffset = BABYLON.Vector3.Zero();
  72481. /**
  72482. * The frequency of thicker lines.
  72483. */
  72484. _this.majorUnitFrequency = 10;
  72485. /**
  72486. * The visibility of minor units in the grid.
  72487. */
  72488. _this.minorUnitVisibility = 0.33;
  72489. /**
  72490. * The grid opacity outside of the lines.
  72491. */
  72492. _this.opacity = 1.0;
  72493. /**
  72494. * Determine RBG output is premultiplied by alpha value.
  72495. */
  72496. _this.preMultiplyAlpha = false;
  72497. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  72498. return _this;
  72499. }
  72500. /**
  72501. * Returns wehter or not the grid requires alpha blending.
  72502. */
  72503. GridMaterial.prototype.needAlphaBlending = function () {
  72504. return this.opacity < 1.0;
  72505. };
  72506. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72507. if (this.isFrozen) {
  72508. if (this._wasPreviouslyReady && subMesh.effect) {
  72509. return true;
  72510. }
  72511. }
  72512. if (!subMesh._materialDefines) {
  72513. subMesh._materialDefines = new GridMaterialDefines();
  72514. }
  72515. var defines = subMesh._materialDefines;
  72516. var scene = this.getScene();
  72517. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  72518. if (this._renderId === scene.getRenderId()) {
  72519. return true;
  72520. }
  72521. }
  72522. var engine = scene.getEngine();
  72523. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  72524. defines.TRANSPARENT = !defines.TRANSPARENT;
  72525. defines.markAsUnprocessed();
  72526. }
  72527. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  72528. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  72529. defines.markAsUnprocessed();
  72530. }
  72531. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  72532. // Get correct effect
  72533. if (defines.isDirty) {
  72534. defines.markAsProcessed();
  72535. scene.resetCachedMaterial();
  72536. // Attributes
  72537. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  72538. // Defines
  72539. var join = defines.toString();
  72540. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  72541. }
  72542. if (!subMesh.effect.isReady()) {
  72543. return false;
  72544. }
  72545. this._renderId = scene.getRenderId();
  72546. this._wasPreviouslyReady = true;
  72547. return true;
  72548. };
  72549. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  72550. var scene = this.getScene();
  72551. var defines = subMesh._materialDefines;
  72552. if (!defines) {
  72553. return;
  72554. }
  72555. var effect = subMesh.effect;
  72556. this._activeEffect = effect;
  72557. // Matrices
  72558. this.bindOnlyWorldMatrix(world);
  72559. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  72560. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  72561. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  72562. // Uniforms
  72563. if (this._mustRebind(scene, effect)) {
  72564. this._activeEffect.setColor3("mainColor", this.mainColor);
  72565. this._activeEffect.setColor3("lineColor", this.lineColor);
  72566. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  72567. this._gridControl.x = this.gridRatio;
  72568. this._gridControl.y = Math.round(this.majorUnitFrequency);
  72569. this._gridControl.z = this.minorUnitVisibility;
  72570. this._gridControl.w = this.opacity;
  72571. this._activeEffect.setVector4("gridControl", this._gridControl);
  72572. }
  72573. // Fog
  72574. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  72575. this._afterBind(mesh, this._activeEffect);
  72576. };
  72577. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  72578. _super.prototype.dispose.call(this, forceDisposeEffect);
  72579. };
  72580. GridMaterial.prototype.clone = function (name) {
  72581. var _this = this;
  72582. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  72583. };
  72584. GridMaterial.prototype.serialize = function () {
  72585. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72586. serializationObject.customType = "BABYLON.GridMaterial";
  72587. return serializationObject;
  72588. };
  72589. GridMaterial.prototype.getClassName = function () {
  72590. return "GridMaterial";
  72591. };
  72592. GridMaterial.Parse = function (source, scene, rootUrl) {
  72593. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  72594. };
  72595. __decorate([
  72596. BABYLON.serializeAsColor3()
  72597. ], GridMaterial.prototype, "mainColor", void 0);
  72598. __decorate([
  72599. BABYLON.serializeAsColor3()
  72600. ], GridMaterial.prototype, "lineColor", void 0);
  72601. __decorate([
  72602. BABYLON.serialize()
  72603. ], GridMaterial.prototype, "gridRatio", void 0);
  72604. __decorate([
  72605. BABYLON.serializeAsColor3()
  72606. ], GridMaterial.prototype, "gridOffset", void 0);
  72607. __decorate([
  72608. BABYLON.serialize()
  72609. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  72610. __decorate([
  72611. BABYLON.serialize()
  72612. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  72613. __decorate([
  72614. BABYLON.serialize()
  72615. ], GridMaterial.prototype, "opacity", void 0);
  72616. __decorate([
  72617. BABYLON.serialize()
  72618. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  72619. return GridMaterial;
  72620. }(BABYLON.PushMaterial));
  72621. BABYLON.GridMaterial = GridMaterial;
  72622. })(BABYLON || (BABYLON = {}));
  72623. //# sourceMappingURL=babylon.gridmaterial.js.map
  72624. 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}";
  72625. 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;\nuniform vec3 gridOffset;\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+gridOffset)/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}";
  72626. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72627. var BABYLON;
  72628. (function (BABYLON) {
  72629. var GLTFLoaderCoordinateSystemMode;
  72630. (function (GLTFLoaderCoordinateSystemMode) {
  72631. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  72632. // 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.
  72633. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  72634. // The glTF right-handed data is not transformed in any form and is loaded directly.
  72635. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  72636. // Sets the useRightHandedSystem flag on the scene.
  72637. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  72638. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  72639. var GLTFFileLoader = (function () {
  72640. function GLTFFileLoader() {
  72641. // V2 options
  72642. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  72643. this.name = "gltf";
  72644. this.extensions = {
  72645. ".gltf": { isBinary: false },
  72646. ".glb": { isBinary: true }
  72647. };
  72648. }
  72649. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  72650. var loaderData = GLTFFileLoader._parse(data, onError);
  72651. if (!loaderData) {
  72652. return;
  72653. }
  72654. if (this.onParsed) {
  72655. this.onParsed(loaderData);
  72656. }
  72657. var loader = this._getLoader(loaderData, onError);
  72658. if (!loader) {
  72659. return;
  72660. }
  72661. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72662. };
  72663. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  72664. var loaderData = GLTFFileLoader._parse(data, onError);
  72665. if (!loaderData) {
  72666. return;
  72667. }
  72668. if (this.onParsed) {
  72669. this.onParsed(loaderData);
  72670. }
  72671. var loader = this._getLoader(loaderData, onError);
  72672. if (!loader) {
  72673. return;
  72674. }
  72675. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72676. };
  72677. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  72678. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  72679. };
  72680. GLTFFileLoader._parse = function (data, onError) {
  72681. try {
  72682. if (data instanceof ArrayBuffer) {
  72683. return GLTFFileLoader._parseBinary(data, onError);
  72684. }
  72685. return {
  72686. json: JSON.parse(data),
  72687. bin: null
  72688. };
  72689. }
  72690. catch (e) {
  72691. onError(e.message);
  72692. return null;
  72693. }
  72694. };
  72695. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  72696. var loaderVersion = { major: 2, minor: 0 };
  72697. var asset = loaderData.json.asset || {};
  72698. var version = GLTFFileLoader._parseVersion(asset.version);
  72699. if (!version) {
  72700. onError("Invalid version: " + asset.version);
  72701. return null;
  72702. }
  72703. if (asset.minVersion !== undefined) {
  72704. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  72705. if (!minVersion) {
  72706. onError("Invalid minimum version: " + asset.minVersion);
  72707. return null;
  72708. }
  72709. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  72710. onError("Incompatible minimum version: " + asset.minVersion);
  72711. return null;
  72712. }
  72713. }
  72714. var createLoaders = {
  72715. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  72716. 2: GLTFFileLoader.CreateGLTFLoaderV2
  72717. };
  72718. var createLoader = createLoaders[version.major];
  72719. if (!createLoader) {
  72720. onError("Unsupported version: " + asset.version);
  72721. return null;
  72722. }
  72723. return createLoader(this);
  72724. };
  72725. GLTFFileLoader._parseBinary = function (data, onError) {
  72726. var Binary = {
  72727. Magic: 0x46546C67
  72728. };
  72729. var binaryReader = new BinaryReader(data);
  72730. var magic = binaryReader.readUint32();
  72731. if (magic !== Binary.Magic) {
  72732. onError("Unexpected magic: " + magic);
  72733. return null;
  72734. }
  72735. var version = binaryReader.readUint32();
  72736. switch (version) {
  72737. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  72738. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  72739. }
  72740. onError("Unsupported version: " + version);
  72741. return null;
  72742. };
  72743. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  72744. var ContentFormat = {
  72745. JSON: 0
  72746. };
  72747. var length = binaryReader.readUint32();
  72748. if (length != binaryReader.getLength()) {
  72749. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72750. return null;
  72751. }
  72752. var contentLength = binaryReader.readUint32();
  72753. var contentFormat = binaryReader.readUint32();
  72754. var content;
  72755. switch (contentFormat) {
  72756. case ContentFormat.JSON:
  72757. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  72758. break;
  72759. default:
  72760. onError("Unexpected content format: " + contentFormat);
  72761. return null;
  72762. }
  72763. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  72764. var body = binaryReader.readUint8Array(bytesRemaining);
  72765. return {
  72766. json: content,
  72767. bin: body
  72768. };
  72769. };
  72770. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  72771. var ChunkFormat = {
  72772. JSON: 0x4E4F534A,
  72773. BIN: 0x004E4942
  72774. };
  72775. var length = binaryReader.readUint32();
  72776. if (length !== binaryReader.getLength()) {
  72777. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72778. return null;
  72779. }
  72780. // JSON chunk
  72781. var chunkLength = binaryReader.readUint32();
  72782. var chunkFormat = binaryReader.readUint32();
  72783. if (chunkFormat !== ChunkFormat.JSON) {
  72784. onError("First chunk format is not JSON");
  72785. return null;
  72786. }
  72787. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  72788. // Look for BIN chunk
  72789. var bin = null;
  72790. while (binaryReader.getPosition() < binaryReader.getLength()) {
  72791. chunkLength = binaryReader.readUint32();
  72792. chunkFormat = binaryReader.readUint32();
  72793. switch (chunkFormat) {
  72794. case ChunkFormat.JSON:
  72795. onError("Unexpected JSON chunk");
  72796. return null;
  72797. case ChunkFormat.BIN:
  72798. bin = binaryReader.readUint8Array(chunkLength);
  72799. break;
  72800. default:
  72801. // ignore unrecognized chunkFormat
  72802. binaryReader.skipBytes(chunkLength);
  72803. break;
  72804. }
  72805. }
  72806. return {
  72807. json: json,
  72808. bin: bin
  72809. };
  72810. };
  72811. GLTFFileLoader._parseVersion = function (version) {
  72812. if (!version) {
  72813. return null;
  72814. }
  72815. var parts = version.split(".");
  72816. if (parts.length != 2) {
  72817. return null;
  72818. }
  72819. var major = +parts[0];
  72820. if (isNaN(major)) {
  72821. return null;
  72822. }
  72823. var minor = +parts[1];
  72824. if (isNaN(minor)) {
  72825. return null;
  72826. }
  72827. return {
  72828. major: major,
  72829. minor: minor
  72830. };
  72831. };
  72832. GLTFFileLoader._compareVersion = function (a, b) {
  72833. if (a.major > b.major)
  72834. return 1;
  72835. if (a.major < b.major)
  72836. return -1;
  72837. if (a.minor > b.minor)
  72838. return 1;
  72839. if (a.minor < b.minor)
  72840. return -1;
  72841. return 0;
  72842. };
  72843. GLTFFileLoader._decodeBufferToText = function (view) {
  72844. var result = "";
  72845. var length = view.byteLength;
  72846. for (var i = 0; i < length; ++i) {
  72847. result += String.fromCharCode(view[i]);
  72848. }
  72849. return result;
  72850. };
  72851. // V1 options
  72852. GLTFFileLoader.HomogeneousCoordinates = false;
  72853. GLTFFileLoader.IncrementalLoading = true;
  72854. return GLTFFileLoader;
  72855. }());
  72856. BABYLON.GLTFFileLoader = GLTFFileLoader;
  72857. var BinaryReader = (function () {
  72858. function BinaryReader(arrayBuffer) {
  72859. this._arrayBuffer = arrayBuffer;
  72860. this._dataView = new DataView(arrayBuffer);
  72861. this._byteOffset = 0;
  72862. }
  72863. BinaryReader.prototype.getPosition = function () {
  72864. return this._byteOffset;
  72865. };
  72866. BinaryReader.prototype.getLength = function () {
  72867. return this._arrayBuffer.byteLength;
  72868. };
  72869. BinaryReader.prototype.readUint32 = function () {
  72870. var value = this._dataView.getUint32(this._byteOffset, true);
  72871. this._byteOffset += 4;
  72872. return value;
  72873. };
  72874. BinaryReader.prototype.readUint8Array = function (length) {
  72875. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  72876. this._byteOffset += length;
  72877. return value;
  72878. };
  72879. BinaryReader.prototype.skipBytes = function (length) {
  72880. this._byteOffset += length;
  72881. };
  72882. return BinaryReader;
  72883. }());
  72884. if (BABYLON.SceneLoader) {
  72885. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  72886. }
  72887. })(BABYLON || (BABYLON = {}));
  72888. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  72889. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72890. var BABYLON;
  72891. (function (BABYLON) {
  72892. var GLTF1;
  72893. (function (GLTF1) {
  72894. /**
  72895. * Enums
  72896. */
  72897. var EComponentType;
  72898. (function (EComponentType) {
  72899. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  72900. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72901. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  72902. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72903. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  72904. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  72905. var EShaderType;
  72906. (function (EShaderType) {
  72907. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  72908. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  72909. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  72910. var EParameterType;
  72911. (function (EParameterType) {
  72912. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  72913. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  72914. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  72915. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  72916. EParameterType[EParameterType["INT"] = 5124] = "INT";
  72917. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  72918. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  72919. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  72920. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  72921. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  72922. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  72923. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  72924. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  72925. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  72926. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  72927. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  72928. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  72929. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  72930. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  72931. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  72932. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  72933. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  72934. var ETextureWrapMode;
  72935. (function (ETextureWrapMode) {
  72936. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  72937. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  72938. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  72939. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  72940. var ETextureFilterType;
  72941. (function (ETextureFilterType) {
  72942. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  72943. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  72944. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  72945. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  72946. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  72947. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  72948. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  72949. var ETextureFormat;
  72950. (function (ETextureFormat) {
  72951. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  72952. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  72953. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  72954. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  72955. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  72956. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  72957. var ECullingType;
  72958. (function (ECullingType) {
  72959. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  72960. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  72961. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  72962. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  72963. var EBlendingFunction;
  72964. (function (EBlendingFunction) {
  72965. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  72966. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  72967. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  72968. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  72969. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  72970. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  72971. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  72972. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  72973. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  72974. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  72975. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  72976. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  72977. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  72978. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  72979. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  72980. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  72981. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  72982. })(BABYLON || (BABYLON = {}));
  72983. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  72984. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  72985. var BABYLON;
  72986. (function (BABYLON) {
  72987. var GLTF1;
  72988. (function (GLTF1) {
  72989. /**
  72990. * Tokenizer. Used for shaders compatibility
  72991. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  72992. */
  72993. var ETokenType;
  72994. (function (ETokenType) {
  72995. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  72996. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  72997. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  72998. })(ETokenType || (ETokenType = {}));
  72999. var Tokenizer = (function () {
  73000. function Tokenizer(toParse) {
  73001. this._pos = 0;
  73002. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  73003. this._toParse = toParse;
  73004. this._maxPos = toParse.length;
  73005. }
  73006. Tokenizer.prototype.getNextToken = function () {
  73007. if (this.isEnd())
  73008. return ETokenType.END_OF_INPUT;
  73009. this.currentString = this.read();
  73010. this.currentToken = ETokenType.UNKNOWN;
  73011. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  73012. this.currentToken = ETokenType.IDENTIFIER;
  73013. this.currentIdentifier = this.currentString;
  73014. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  73015. this.currentIdentifier += this.currentString;
  73016. this.forward();
  73017. }
  73018. }
  73019. return this.currentToken;
  73020. };
  73021. Tokenizer.prototype.peek = function () {
  73022. return this._toParse[this._pos];
  73023. };
  73024. Tokenizer.prototype.read = function () {
  73025. return this._toParse[this._pos++];
  73026. };
  73027. Tokenizer.prototype.forward = function () {
  73028. this._pos++;
  73029. };
  73030. Tokenizer.prototype.isEnd = function () {
  73031. return this._pos >= this._maxPos;
  73032. };
  73033. return Tokenizer;
  73034. }());
  73035. /**
  73036. * Values
  73037. */
  73038. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  73039. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  73040. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  73041. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  73042. /**
  73043. * Parse
  73044. */
  73045. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  73046. for (var buf in parsedBuffers) {
  73047. var parsedBuffer = parsedBuffers[buf];
  73048. gltfRuntime.buffers[buf] = parsedBuffer;
  73049. gltfRuntime.buffersCount++;
  73050. }
  73051. };
  73052. var parseShaders = function (parsedShaders, gltfRuntime) {
  73053. for (var sha in parsedShaders) {
  73054. var parsedShader = parsedShaders[sha];
  73055. gltfRuntime.shaders[sha] = parsedShader;
  73056. gltfRuntime.shaderscount++;
  73057. }
  73058. };
  73059. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  73060. for (var object in parsedObjects) {
  73061. var parsedObject = parsedObjects[object];
  73062. gltfRuntime[runtimeProperty][object] = parsedObject;
  73063. }
  73064. };
  73065. /**
  73066. * Utils
  73067. */
  73068. var normalizeUVs = function (buffer) {
  73069. if (!buffer) {
  73070. return;
  73071. }
  73072. for (var i = 0; i < buffer.length / 2; i++) {
  73073. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  73074. }
  73075. };
  73076. var replaceInString = function (str, searchValue, replaceValue) {
  73077. while (str.indexOf(searchValue) !== -1) {
  73078. str = str.replace(searchValue, replaceValue);
  73079. }
  73080. return str;
  73081. };
  73082. var getAttribute = function (attributeParameter) {
  73083. if (attributeParameter.semantic === "NORMAL") {
  73084. return "normal";
  73085. }
  73086. else if (attributeParameter.semantic === "POSITION") {
  73087. return "position";
  73088. }
  73089. else if (attributeParameter.semantic === "JOINT") {
  73090. return "matricesIndices";
  73091. }
  73092. else if (attributeParameter.semantic === "WEIGHT") {
  73093. return "matricesWeights";
  73094. }
  73095. else if (attributeParameter.semantic === "COLOR") {
  73096. return "color";
  73097. }
  73098. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  73099. var channel = Number(attributeParameter.semantic.split("_")[1]);
  73100. return "uv" + (channel === 0 ? "" : channel + 1);
  73101. }
  73102. };
  73103. /**
  73104. * Returns the animation path (glTF -> Babylon)
  73105. */
  73106. var getAnimationPath = function (path) {
  73107. var index = glTFAnimationPaths.indexOf(path);
  73108. if (index !== -1) {
  73109. return babylonAnimationPaths[index];
  73110. }
  73111. return path;
  73112. };
  73113. /**
  73114. * Loads and creates animations
  73115. */
  73116. var loadAnimations = function (gltfRuntime) {
  73117. for (var anim in gltfRuntime.animations) {
  73118. var animation = gltfRuntime.animations[anim];
  73119. var lastAnimation = null;
  73120. for (var i = 0; i < animation.channels.length; i++) {
  73121. // Get parameters and load buffers
  73122. var channel = animation.channels[i];
  73123. var sampler = animation.samplers[channel.sampler];
  73124. if (!sampler) {
  73125. continue;
  73126. }
  73127. var inputData = null;
  73128. var outputData = null;
  73129. if (animation.parameters) {
  73130. inputData = animation.parameters[sampler.input];
  73131. outputData = animation.parameters[sampler.output];
  73132. }
  73133. else {
  73134. inputData = sampler.input;
  73135. outputData = sampler.output;
  73136. }
  73137. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  73138. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  73139. var targetID = channel.target.id;
  73140. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  73141. if (targetNode === null) {
  73142. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  73143. }
  73144. if (targetNode === null) {
  73145. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  73146. continue;
  73147. }
  73148. var isBone = targetNode instanceof BABYLON.Bone;
  73149. // Get target path (position, rotation or scaling)
  73150. var targetPath = channel.target.path;
  73151. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  73152. if (targetPathIndex !== -1) {
  73153. targetPath = babylonAnimationPaths[targetPathIndex];
  73154. }
  73155. // Determine animation type
  73156. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  73157. if (!isBone) {
  73158. if (targetPath === "rotationQuaternion") {
  73159. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  73160. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  73161. }
  73162. else {
  73163. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  73164. }
  73165. }
  73166. // Create animation and key frames
  73167. var babylonAnimation = null;
  73168. var keys = [];
  73169. var arrayOffset = 0;
  73170. var modifyKey = false;
  73171. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  73172. babylonAnimation = lastAnimation;
  73173. modifyKey = true;
  73174. }
  73175. if (!modifyKey) {
  73176. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  73177. }
  73178. // For each frame
  73179. for (var j = 0; j < bufferInput.length; j++) {
  73180. var value = null;
  73181. if (targetPath === "rotationQuaternion") {
  73182. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  73183. arrayOffset += 4;
  73184. }
  73185. else {
  73186. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  73187. arrayOffset += 3;
  73188. }
  73189. if (isBone) {
  73190. var bone = targetNode;
  73191. var translation = BABYLON.Vector3.Zero();
  73192. var rotationQuaternion = new BABYLON.Quaternion();
  73193. var scaling = BABYLON.Vector3.Zero();
  73194. // Warning on decompose
  73195. var mat = bone.getBaseMatrix();
  73196. if (modifyKey) {
  73197. mat = lastAnimation.getKeys()[j].value;
  73198. }
  73199. mat.decompose(scaling, rotationQuaternion, translation);
  73200. if (targetPath === "position") {
  73201. translation = value;
  73202. }
  73203. else if (targetPath === "rotationQuaternion") {
  73204. rotationQuaternion = value;
  73205. }
  73206. else {
  73207. scaling = value;
  73208. }
  73209. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  73210. }
  73211. if (!modifyKey) {
  73212. keys.push({
  73213. frame: bufferInput[j],
  73214. value: value
  73215. });
  73216. }
  73217. else {
  73218. lastAnimation.getKeys()[j].value = value;
  73219. }
  73220. }
  73221. // Finish
  73222. if (!modifyKey) {
  73223. babylonAnimation.setKeys(keys);
  73224. targetNode.animations.push(babylonAnimation);
  73225. }
  73226. lastAnimation = babylonAnimation;
  73227. gltfRuntime.scene.stopAnimation(targetNode);
  73228. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  73229. }
  73230. }
  73231. };
  73232. /**
  73233. * Returns the bones transformation matrix
  73234. */
  73235. var configureBoneTransformation = function (node) {
  73236. var mat = null;
  73237. if (node.translation || node.rotation || node.scale) {
  73238. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  73239. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  73240. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  73241. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  73242. }
  73243. else {
  73244. mat = BABYLON.Matrix.FromArray(node.matrix);
  73245. }
  73246. return mat;
  73247. };
  73248. /**
  73249. * Returns the parent bone
  73250. */
  73251. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  73252. // Try to find
  73253. for (var i = 0; i < newSkeleton.bones.length; i++) {
  73254. if (newSkeleton.bones[i].name === jointName) {
  73255. return newSkeleton.bones[i];
  73256. }
  73257. }
  73258. // Not found, search in gltf nodes
  73259. var nodes = gltfRuntime.nodes;
  73260. for (var nde in nodes) {
  73261. var node = nodes[nde];
  73262. if (!node.jointName) {
  73263. continue;
  73264. }
  73265. var children = node.children;
  73266. for (var i = 0; i < children.length; i++) {
  73267. var child = gltfRuntime.nodes[children[i]];
  73268. if (!child.jointName) {
  73269. continue;
  73270. }
  73271. if (child.jointName === jointName) {
  73272. var mat = configureBoneTransformation(node);
  73273. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  73274. bone.id = nde;
  73275. return bone;
  73276. }
  73277. }
  73278. }
  73279. return null;
  73280. };
  73281. /**
  73282. * Returns the appropriate root node
  73283. */
  73284. var getNodeToRoot = function (nodesToRoot, id) {
  73285. for (var i = 0; i < nodesToRoot.length; i++) {
  73286. var nodeToRoot = nodesToRoot[i];
  73287. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  73288. var child = nodeToRoot.node.children[j];
  73289. if (child === id) {
  73290. return nodeToRoot.bone;
  73291. }
  73292. }
  73293. }
  73294. return null;
  73295. };
  73296. /**
  73297. * Returns the node with the joint name
  73298. */
  73299. var getJointNode = function (gltfRuntime, jointName) {
  73300. var nodes = gltfRuntime.nodes;
  73301. var node = nodes[jointName];
  73302. if (node) {
  73303. return {
  73304. node: node,
  73305. id: jointName
  73306. };
  73307. }
  73308. for (var nde in nodes) {
  73309. node = nodes[nde];
  73310. if (node.jointName === jointName) {
  73311. return {
  73312. node: node,
  73313. id: nde
  73314. };
  73315. }
  73316. }
  73317. return null;
  73318. };
  73319. /**
  73320. * Checks if a nodes is in joints
  73321. */
  73322. var nodeIsInJoints = function (skins, id) {
  73323. for (var i = 0; i < skins.jointNames.length; i++) {
  73324. if (skins.jointNames[i] === id) {
  73325. return true;
  73326. }
  73327. }
  73328. return false;
  73329. };
  73330. /**
  73331. * Fills the nodes to root for bones and builds hierarchy
  73332. */
  73333. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  73334. // Creates nodes for root
  73335. for (var nde in gltfRuntime.nodes) {
  73336. var node = gltfRuntime.nodes[nde];
  73337. var id = nde;
  73338. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  73339. continue;
  73340. }
  73341. // Create node to root bone
  73342. var mat = configureBoneTransformation(node);
  73343. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  73344. bone.id = id;
  73345. nodesToRoot.push({ bone: bone, node: node, id: id });
  73346. }
  73347. // Parenting
  73348. for (var i = 0; i < nodesToRoot.length; i++) {
  73349. var nodeToRoot = nodesToRoot[i];
  73350. var children = nodeToRoot.node.children;
  73351. for (var j = 0; j < children.length; j++) {
  73352. var child = null;
  73353. for (var k = 0; k < nodesToRoot.length; k++) {
  73354. if (nodesToRoot[k].id === children[j]) {
  73355. child = nodesToRoot[k];
  73356. break;
  73357. }
  73358. }
  73359. if (child) {
  73360. child.bone._parent = nodeToRoot.bone;
  73361. nodeToRoot.bone.children.push(child.bone);
  73362. }
  73363. }
  73364. }
  73365. };
  73366. var printMat = function (m) {
  73367. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  73368. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  73369. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  73370. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  73371. };
  73372. /**
  73373. * Imports a skeleton
  73374. */
  73375. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  73376. if (!newSkeleton) {
  73377. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  73378. }
  73379. if (!skins.babylonSkeleton) {
  73380. return newSkeleton;
  73381. }
  73382. // Matrices
  73383. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  73384. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73385. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  73386. // Find the root bones
  73387. var nodesToRoot = [];
  73388. var nodesToRootToAdd = [];
  73389. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  73390. newSkeleton.bones = [];
  73391. // Joints
  73392. for (var i = 0; i < skins.jointNames.length; i++) {
  73393. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  73394. var node = jointNode.node;
  73395. if (!node) {
  73396. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  73397. continue;
  73398. }
  73399. var id = jointNode.id;
  73400. // Optimize, if the bone already exists...
  73401. var existingBone = gltfRuntime.scene.getBoneByID(id);
  73402. if (existingBone) {
  73403. newSkeleton.bones.push(existingBone);
  73404. continue;
  73405. }
  73406. // Search for parent bone
  73407. var foundBone = false;
  73408. var parentBone = null;
  73409. for (var j = 0; j < i; j++) {
  73410. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  73411. if (!joint) {
  73412. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  73413. continue;
  73414. }
  73415. var children = joint.children;
  73416. if (!children) {
  73417. continue;
  73418. }
  73419. foundBone = false;
  73420. for (var k = 0; k < children.length; k++) {
  73421. if (children[k] === id) {
  73422. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  73423. foundBone = true;
  73424. break;
  73425. }
  73426. }
  73427. if (foundBone) {
  73428. break;
  73429. }
  73430. }
  73431. // Create bone
  73432. var mat = configureBoneTransformation(node);
  73433. if (!parentBone && nodesToRoot.length > 0) {
  73434. parentBone = getNodeToRoot(nodesToRoot, id);
  73435. if (parentBone) {
  73436. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  73437. nodesToRootToAdd.push(parentBone);
  73438. }
  73439. }
  73440. }
  73441. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  73442. bone.id = id;
  73443. }
  73444. // Polish
  73445. var bones = newSkeleton.bones;
  73446. newSkeleton.bones = [];
  73447. for (var i = 0; i < skins.jointNames.length; i++) {
  73448. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  73449. if (!jointNode) {
  73450. continue;
  73451. }
  73452. for (var j = 0; j < bones.length; j++) {
  73453. if (bones[j].id === jointNode.id) {
  73454. newSkeleton.bones.push(bones[j]);
  73455. break;
  73456. }
  73457. }
  73458. }
  73459. newSkeleton.prepare();
  73460. // Finish
  73461. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  73462. newSkeleton.bones.push(nodesToRootToAdd[i]);
  73463. }
  73464. return newSkeleton;
  73465. };
  73466. /**
  73467. * Imports a mesh and its geometries
  73468. */
  73469. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  73470. if (!newMesh) {
  73471. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73472. newMesh.id = id;
  73473. }
  73474. if (!node.babylonNode) {
  73475. return newMesh;
  73476. }
  73477. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  73478. if (!newMesh.material) {
  73479. newMesh.material = multiMat;
  73480. }
  73481. var vertexData = new BABYLON.VertexData();
  73482. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  73483. var verticesStarts = [];
  73484. var verticesCounts = [];
  73485. var indexStarts = [];
  73486. var indexCounts = [];
  73487. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73488. var meshID = meshes[meshIndex];
  73489. var mesh = gltfRuntime.meshes[meshID];
  73490. if (!mesh) {
  73491. continue;
  73492. }
  73493. // Positions, normals and UVs
  73494. for (var i = 0; i < mesh.primitives.length; i++) {
  73495. // Temporary vertex data
  73496. var tempVertexData = new BABYLON.VertexData();
  73497. var primitive = mesh.primitives[i];
  73498. if (primitive.mode !== 4) {
  73499. // continue;
  73500. }
  73501. var attributes = primitive.attributes;
  73502. var accessor = null;
  73503. var buffer = null;
  73504. // Set positions, normal and uvs
  73505. for (var semantic in attributes) {
  73506. // Link accessor and buffer view
  73507. accessor = gltfRuntime.accessors[attributes[semantic]];
  73508. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73509. if (semantic === "NORMAL") {
  73510. tempVertexData.normals = new Float32Array(buffer.length);
  73511. tempVertexData.normals.set(buffer);
  73512. }
  73513. else if (semantic === "POSITION") {
  73514. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  73515. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  73516. for (var j = 0; j < buffer.length; j += 4) {
  73517. tempVertexData.positions[j] = buffer[j];
  73518. tempVertexData.positions[j + 1] = buffer[j + 1];
  73519. tempVertexData.positions[j + 2] = buffer[j + 2];
  73520. }
  73521. }
  73522. else {
  73523. tempVertexData.positions = new Float32Array(buffer.length);
  73524. tempVertexData.positions.set(buffer);
  73525. }
  73526. verticesCounts.push(tempVertexData.positions.length);
  73527. }
  73528. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  73529. var channel = Number(semantic.split("_")[1]);
  73530. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  73531. var uvs = new Float32Array(buffer.length);
  73532. uvs.set(buffer);
  73533. normalizeUVs(uvs);
  73534. tempVertexData.set(uvs, uvKind);
  73535. }
  73536. else if (semantic === "JOINT") {
  73537. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  73538. tempVertexData.matricesIndices.set(buffer);
  73539. }
  73540. else if (semantic === "WEIGHT") {
  73541. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  73542. tempVertexData.matricesWeights.set(buffer);
  73543. }
  73544. else if (semantic === "COLOR") {
  73545. tempVertexData.colors = new Float32Array(buffer.length);
  73546. tempVertexData.colors.set(buffer);
  73547. }
  73548. }
  73549. // Indices
  73550. accessor = gltfRuntime.accessors[primitive.indices];
  73551. if (accessor) {
  73552. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73553. tempVertexData.indices = new Int32Array(buffer.length);
  73554. tempVertexData.indices.set(buffer);
  73555. indexCounts.push(tempVertexData.indices.length);
  73556. }
  73557. else {
  73558. // Set indices on the fly
  73559. var indices = [];
  73560. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  73561. indices.push(j);
  73562. }
  73563. tempVertexData.indices = new Int32Array(indices);
  73564. indexCounts.push(tempVertexData.indices.length);
  73565. }
  73566. vertexData.merge(tempVertexData);
  73567. tempVertexData = undefined;
  73568. // Sub material
  73569. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  73570. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  73571. // Update vertices start and index start
  73572. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  73573. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  73574. }
  73575. }
  73576. // Apply geometry
  73577. geometry.setAllVerticesData(vertexData, false);
  73578. newMesh.computeWorldMatrix(true);
  73579. // Apply submeshes
  73580. newMesh.subMeshes = [];
  73581. var index = 0;
  73582. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73583. var meshID = meshes[meshIndex];
  73584. var mesh = gltfRuntime.meshes[meshID];
  73585. if (!mesh) {
  73586. continue;
  73587. }
  73588. for (var i = 0; i < mesh.primitives.length; i++) {
  73589. if (mesh.primitives[i].mode !== 4) {
  73590. //continue;
  73591. }
  73592. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  73593. index++;
  73594. }
  73595. }
  73596. // Finish
  73597. return newMesh;
  73598. };
  73599. /**
  73600. * Configure node transformation from position, rotation and scaling
  73601. */
  73602. var configureNode = function (newNode, position, rotation, scaling) {
  73603. if (newNode.position) {
  73604. newNode.position = position;
  73605. }
  73606. if (newNode.rotationQuaternion || newNode.rotation) {
  73607. newNode.rotationQuaternion = rotation;
  73608. }
  73609. if (newNode.scaling) {
  73610. newNode.scaling = scaling;
  73611. }
  73612. };
  73613. /**
  73614. * Configures node from transformation matrix
  73615. */
  73616. var configureNodeFromMatrix = function (newNode, node, parent) {
  73617. if (node.matrix) {
  73618. var position = new BABYLON.Vector3(0, 0, 0);
  73619. var rotation = new BABYLON.Quaternion();
  73620. var scaling = new BABYLON.Vector3(0, 0, 0);
  73621. var mat = BABYLON.Matrix.FromArray(node.matrix);
  73622. mat.decompose(scaling, rotation, position);
  73623. configureNode(newNode, position, rotation, scaling);
  73624. }
  73625. else {
  73626. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  73627. }
  73628. newNode.computeWorldMatrix(true);
  73629. };
  73630. /**
  73631. * Imports a node
  73632. */
  73633. var importNode = function (gltfRuntime, node, id, parent) {
  73634. var lastNode = null;
  73635. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  73636. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  73637. return null;
  73638. }
  73639. }
  73640. // Meshes
  73641. if (node.skin) {
  73642. if (node.meshes) {
  73643. var skin = gltfRuntime.skins[node.skin];
  73644. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  73645. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  73646. if (newMesh.skeleton === null) {
  73647. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  73648. if (!skin.babylonSkeleton) {
  73649. skin.babylonSkeleton = newMesh.skeleton;
  73650. }
  73651. }
  73652. lastNode = newMesh;
  73653. }
  73654. }
  73655. else if (node.meshes) {
  73656. /**
  73657. * Improve meshes property
  73658. */
  73659. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  73660. lastNode = newMesh;
  73661. }
  73662. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73663. var light = gltfRuntime.lights[node.light];
  73664. if (light) {
  73665. if (light.type === "ambient") {
  73666. var ambienLight = light[light.type];
  73667. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73668. hemiLight.name = node.name;
  73669. if (ambienLight.color) {
  73670. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  73671. }
  73672. lastNode = hemiLight;
  73673. }
  73674. else if (light.type === "directional") {
  73675. var directionalLight = light[light.type];
  73676. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73677. dirLight.name = node.name;
  73678. if (directionalLight.color) {
  73679. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  73680. }
  73681. lastNode = dirLight;
  73682. }
  73683. else if (light.type === "point") {
  73684. var pointLight = light[light.type];
  73685. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73686. ptLight.name = node.name;
  73687. if (pointLight.color) {
  73688. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  73689. }
  73690. lastNode = ptLight;
  73691. }
  73692. else if (light.type === "spot") {
  73693. var spotLight = light[light.type];
  73694. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  73695. spLight.name = node.name;
  73696. if (spotLight.color) {
  73697. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  73698. }
  73699. if (spotLight.fallOfAngle) {
  73700. spLight.angle = spotLight.fallOfAngle;
  73701. }
  73702. if (spotLight.fallOffExponent) {
  73703. spLight.exponent = spotLight.fallOffExponent;
  73704. }
  73705. lastNode = spLight;
  73706. }
  73707. }
  73708. }
  73709. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73710. var camera = gltfRuntime.cameras[node.camera];
  73711. if (camera) {
  73712. if (camera.type === "orthographic") {
  73713. var orthographicCamera = camera[camera.type];
  73714. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73715. orthoCamera.name = node.name;
  73716. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  73717. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73718. lastNode = orthoCamera;
  73719. }
  73720. else if (camera.type === "perspective") {
  73721. var perspectiveCamera = camera[camera.type];
  73722. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73723. persCamera.name = node.name;
  73724. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73725. if (!perspectiveCamera.aspectRatio) {
  73726. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  73727. }
  73728. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  73729. persCamera.maxZ = perspectiveCamera.zfar;
  73730. persCamera.minZ = perspectiveCamera.znear;
  73731. }
  73732. lastNode = persCamera;
  73733. }
  73734. }
  73735. }
  73736. // Empty node
  73737. if (!node.jointName) {
  73738. if (node.babylonNode) {
  73739. return node.babylonNode;
  73740. }
  73741. else if (lastNode === null) {
  73742. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73743. node.babylonNode = dummy;
  73744. lastNode = dummy;
  73745. }
  73746. }
  73747. if (lastNode !== null) {
  73748. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  73749. configureNodeFromMatrix(lastNode, node, parent);
  73750. }
  73751. else {
  73752. var translation = node.translation || [0, 0, 0];
  73753. var rotation = node.rotation || [0, 0, 0, 1];
  73754. var scale = node.scale || [1, 1, 1];
  73755. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  73756. }
  73757. lastNode.updateCache(true);
  73758. node.babylonNode = lastNode;
  73759. }
  73760. return lastNode;
  73761. };
  73762. /**
  73763. * Traverses nodes and creates them
  73764. */
  73765. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  73766. var node = gltfRuntime.nodes[id];
  73767. var newNode = null;
  73768. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  73769. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  73770. meshIncluded = true;
  73771. }
  73772. else {
  73773. meshIncluded = false;
  73774. }
  73775. }
  73776. else {
  73777. meshIncluded = true;
  73778. }
  73779. if (!node.jointName && meshIncluded) {
  73780. newNode = importNode(gltfRuntime, node, id, parent);
  73781. if (newNode !== null) {
  73782. newNode.id = id;
  73783. newNode.parent = parent;
  73784. }
  73785. }
  73786. if (node.children) {
  73787. for (var i = 0; i < node.children.length; i++) {
  73788. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  73789. }
  73790. }
  73791. };
  73792. /**
  73793. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  73794. */
  73795. var postLoad = function (gltfRuntime) {
  73796. // Nodes
  73797. var currentScene = gltfRuntime.currentScene;
  73798. if (currentScene) {
  73799. for (var i = 0; i < currentScene.nodes.length; i++) {
  73800. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73801. }
  73802. }
  73803. else {
  73804. for (var thing in gltfRuntime.scenes) {
  73805. currentScene = gltfRuntime.scenes[thing];
  73806. for (var i = 0; i < currentScene.nodes.length; i++) {
  73807. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  73808. }
  73809. }
  73810. }
  73811. // Set animations
  73812. loadAnimations(gltfRuntime);
  73813. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  73814. var skeleton = gltfRuntime.scene.skeletons[i];
  73815. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  73816. }
  73817. };
  73818. /**
  73819. * onBind shaderrs callback to set uniforms and matrices
  73820. */
  73821. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  73822. var materialValues = material.values || technique.parameters;
  73823. for (var unif in unTreatedUniforms) {
  73824. var uniform = unTreatedUniforms[unif];
  73825. var type = uniform.type;
  73826. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  73827. if (uniform.semantic && !uniform.source && !uniform.node) {
  73828. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  73829. }
  73830. else if (uniform.semantic && (uniform.source || uniform.node)) {
  73831. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  73832. if (source === null) {
  73833. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  73834. }
  73835. if (source === null) {
  73836. continue;
  73837. }
  73838. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  73839. }
  73840. }
  73841. else {
  73842. var value = materialValues[technique.uniforms[unif]];
  73843. if (!value) {
  73844. continue;
  73845. }
  73846. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73847. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  73848. if (texture === null || texture === undefined) {
  73849. continue;
  73850. }
  73851. shaderMaterial.getEffect().setTexture(unif, texture);
  73852. }
  73853. else {
  73854. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  73855. }
  73856. }
  73857. }
  73858. onSuccess(shaderMaterial);
  73859. };
  73860. /**
  73861. * Prepare uniforms to send the only one time
  73862. * Loads the appropriate textures
  73863. */
  73864. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  73865. var materialValues = material.values || technique.parameters;
  73866. var techniqueUniforms = technique.uniforms;
  73867. /**
  73868. * Prepare values here (not matrices)
  73869. */
  73870. for (var unif in unTreatedUniforms) {
  73871. var uniform = unTreatedUniforms[unif];
  73872. var type = uniform.type;
  73873. var value = materialValues[techniqueUniforms[unif]];
  73874. if (value === undefined) {
  73875. // In case the value is the same for all materials
  73876. value = uniform.value;
  73877. }
  73878. if (!value) {
  73879. continue;
  73880. }
  73881. var onLoadTexture = function (uniformName) {
  73882. return function (texture) {
  73883. if (uniform.value) {
  73884. // Static uniform
  73885. shaderMaterial.setTexture(uniformName, texture);
  73886. delete unTreatedUniforms[uniformName];
  73887. }
  73888. };
  73889. };
  73890. // Texture (sampler2D)
  73891. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  73892. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  73893. }
  73894. else {
  73895. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  73896. // Static uniform
  73897. delete unTreatedUniforms[unif];
  73898. }
  73899. }
  73900. }
  73901. };
  73902. /**
  73903. * Shader compilation failed
  73904. */
  73905. var onShaderCompileError = function (program, shaderMaterial, onError) {
  73906. return function (effect, error) {
  73907. shaderMaterial.dispose(true);
  73908. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  73909. };
  73910. };
  73911. /**
  73912. * Shader compilation success
  73913. */
  73914. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  73915. return function (_) {
  73916. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  73917. shaderMaterial.onBind = function (mesh) {
  73918. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  73919. };
  73920. };
  73921. };
  73922. /**
  73923. * Returns the appropriate uniform if already handled by babylon
  73924. */
  73925. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  73926. for (var unif in technique.uniforms) {
  73927. var uniform = technique.uniforms[unif];
  73928. var uniformParameter = technique.parameters[uniform];
  73929. if (tokenizer.currentIdentifier === unif) {
  73930. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  73931. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  73932. if (transformIndex !== -1) {
  73933. delete unTreatedUniforms[unif];
  73934. return babylonTransforms[transformIndex];
  73935. }
  73936. }
  73937. }
  73938. }
  73939. return tokenizer.currentIdentifier;
  73940. };
  73941. /**
  73942. * All shaders loaded. Create materials one by one
  73943. */
  73944. var importMaterials = function (gltfRuntime) {
  73945. // Create materials
  73946. for (var mat in gltfRuntime.materials) {
  73947. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  73948. }
  73949. };
  73950. /**
  73951. * Implementation of the base glTF spec
  73952. */
  73953. var GLTFLoaderBase = (function () {
  73954. function GLTFLoaderBase() {
  73955. }
  73956. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  73957. var gltfRuntime = {
  73958. extensions: {},
  73959. accessors: {},
  73960. buffers: {},
  73961. bufferViews: {},
  73962. meshes: {},
  73963. lights: {},
  73964. cameras: {},
  73965. nodes: {},
  73966. images: {},
  73967. textures: {},
  73968. shaders: {},
  73969. programs: {},
  73970. samplers: {},
  73971. techniques: {},
  73972. materials: {},
  73973. animations: {},
  73974. skins: {},
  73975. extensionsUsed: [],
  73976. scenes: {},
  73977. buffersCount: 0,
  73978. shaderscount: 0,
  73979. scene: scene,
  73980. rootUrl: rootUrl,
  73981. loadedBufferCount: 0,
  73982. loadedBufferViews: {},
  73983. loadedShaderCount: 0,
  73984. importOnlyMeshes: false,
  73985. dummyNodes: []
  73986. };
  73987. // Parse
  73988. if (parsedData.extensions) {
  73989. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  73990. }
  73991. if (parsedData.extensionsUsed) {
  73992. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  73993. }
  73994. if (parsedData.buffers) {
  73995. parseBuffers(parsedData.buffers, gltfRuntime);
  73996. }
  73997. if (parsedData.bufferViews) {
  73998. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  73999. }
  74000. if (parsedData.accessors) {
  74001. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  74002. }
  74003. if (parsedData.meshes) {
  74004. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  74005. }
  74006. if (parsedData.lights) {
  74007. parseObject(parsedData.lights, "lights", gltfRuntime);
  74008. }
  74009. if (parsedData.cameras) {
  74010. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  74011. }
  74012. if (parsedData.nodes) {
  74013. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  74014. }
  74015. if (parsedData.images) {
  74016. parseObject(parsedData.images, "images", gltfRuntime);
  74017. }
  74018. if (parsedData.textures) {
  74019. parseObject(parsedData.textures, "textures", gltfRuntime);
  74020. }
  74021. if (parsedData.shaders) {
  74022. parseShaders(parsedData.shaders, gltfRuntime);
  74023. }
  74024. if (parsedData.programs) {
  74025. parseObject(parsedData.programs, "programs", gltfRuntime);
  74026. }
  74027. if (parsedData.samplers) {
  74028. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  74029. }
  74030. if (parsedData.techniques) {
  74031. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  74032. }
  74033. if (parsedData.materials) {
  74034. parseObject(parsedData.materials, "materials", gltfRuntime);
  74035. }
  74036. if (parsedData.animations) {
  74037. parseObject(parsedData.animations, "animations", gltfRuntime);
  74038. }
  74039. if (parsedData.skins) {
  74040. parseObject(parsedData.skins, "skins", gltfRuntime);
  74041. }
  74042. if (parsedData.scenes) {
  74043. gltfRuntime.scenes = parsedData.scenes;
  74044. }
  74045. if (parsedData.scene && parsedData.scenes) {
  74046. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  74047. }
  74048. return gltfRuntime;
  74049. };
  74050. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74051. var buffer = gltfRuntime.buffers[id];
  74052. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  74053. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  74054. }
  74055. else {
  74056. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  74057. onError(request.status + " " + request.statusText);
  74058. });
  74059. }
  74060. };
  74061. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74062. var texture = gltfRuntime.textures[id];
  74063. if (!texture || !texture.source) {
  74064. onError(null);
  74065. return;
  74066. }
  74067. if (texture.babylonTexture) {
  74068. onSuccess(null);
  74069. return;
  74070. }
  74071. var source = gltfRuntime.images[texture.source];
  74072. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  74073. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  74074. }
  74075. else {
  74076. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  74077. onError(request.status + " " + request.statusText);
  74078. });
  74079. }
  74080. };
  74081. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74082. var texture = gltfRuntime.textures[id];
  74083. if (texture.babylonTexture) {
  74084. onSuccess(texture.babylonTexture);
  74085. return;
  74086. }
  74087. var sampler = gltfRuntime.samplers[texture.sampler];
  74088. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  74089. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  74090. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  74091. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  74092. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  74093. var blob = new Blob([buffer]);
  74094. var blobURL = URL.createObjectURL(blob);
  74095. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  74096. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  74097. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  74098. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  74099. newTexture.name = id;
  74100. texture.babylonTexture = newTexture;
  74101. onSuccess(newTexture);
  74102. };
  74103. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74104. var shader = gltfRuntime.shaders[id];
  74105. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  74106. var shaderString = atob(shader.uri.split(",")[1]);
  74107. onSuccess(shaderString);
  74108. }
  74109. else {
  74110. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  74111. onError(request.status + " " + request.statusText);
  74112. });
  74113. }
  74114. };
  74115. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74116. var material = gltfRuntime.materials[id];
  74117. var technique = gltfRuntime.techniques[material.technique];
  74118. if (!technique) {
  74119. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  74120. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  74121. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74122. onSuccess(defaultMaterial);
  74123. return;
  74124. }
  74125. var program = gltfRuntime.programs[technique.program];
  74126. var states = technique.states;
  74127. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  74128. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  74129. var newVertexShader = "";
  74130. var newPixelShader = "";
  74131. var vertexTokenizer = new Tokenizer(vertexShader);
  74132. var pixelTokenizer = new Tokenizer(pixelShader);
  74133. var unTreatedUniforms = {};
  74134. var uniforms = [];
  74135. var attributes = [];
  74136. var samplers = [];
  74137. // Fill uniform, sampler2D and attributes
  74138. for (var unif in technique.uniforms) {
  74139. var uniform = technique.uniforms[unif];
  74140. var uniformParameter = technique.parameters[uniform];
  74141. unTreatedUniforms[unif] = uniformParameter;
  74142. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  74143. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  74144. if (transformIndex !== -1) {
  74145. uniforms.push(babylonTransforms[transformIndex]);
  74146. delete unTreatedUniforms[unif];
  74147. }
  74148. else {
  74149. uniforms.push(unif);
  74150. }
  74151. }
  74152. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  74153. samplers.push(unif);
  74154. }
  74155. else {
  74156. uniforms.push(unif);
  74157. }
  74158. }
  74159. for (var attr in technique.attributes) {
  74160. var attribute = technique.attributes[attr];
  74161. var attributeParameter = technique.parameters[attribute];
  74162. if (attributeParameter.semantic) {
  74163. attributes.push(getAttribute(attributeParameter));
  74164. }
  74165. }
  74166. // Configure vertex shader
  74167. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  74168. var tokenType = vertexTokenizer.currentToken;
  74169. if (tokenType !== ETokenType.IDENTIFIER) {
  74170. newVertexShader += vertexTokenizer.currentString;
  74171. continue;
  74172. }
  74173. var foundAttribute = false;
  74174. for (var attr in technique.attributes) {
  74175. var attribute = technique.attributes[attr];
  74176. var attributeParameter = technique.parameters[attribute];
  74177. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  74178. newVertexShader += getAttribute(attributeParameter);
  74179. foundAttribute = true;
  74180. break;
  74181. }
  74182. }
  74183. if (foundAttribute) {
  74184. continue;
  74185. }
  74186. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  74187. }
  74188. // Configure pixel shader
  74189. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  74190. var tokenType = pixelTokenizer.currentToken;
  74191. if (tokenType !== ETokenType.IDENTIFIER) {
  74192. newPixelShader += pixelTokenizer.currentString;
  74193. continue;
  74194. }
  74195. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  74196. }
  74197. // Create shader material
  74198. var shaderPath = {
  74199. vertex: program.vertexShader + id,
  74200. fragment: program.fragmentShader + id
  74201. };
  74202. var options = {
  74203. attributes: attributes,
  74204. uniforms: uniforms,
  74205. samplers: samplers,
  74206. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  74207. };
  74208. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  74209. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  74210. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  74211. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  74212. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  74213. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74214. if (states && states.functions) {
  74215. var functions = states.functions;
  74216. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  74217. shaderMaterial.backFaceCulling = false;
  74218. }
  74219. var blendFunc = functions.blendFuncSeparate;
  74220. if (blendFunc) {
  74221. 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) {
  74222. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  74223. }
  74224. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74225. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74226. }
  74227. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74228. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  74229. }
  74230. 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) {
  74231. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  74232. }
  74233. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74234. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  74235. }
  74236. 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) {
  74237. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  74238. }
  74239. }
  74240. }
  74241. };
  74242. return GLTFLoaderBase;
  74243. }());
  74244. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  74245. /**
  74246. * glTF V1 Loader
  74247. */
  74248. var GLTFLoader = (function () {
  74249. function GLTFLoader() {
  74250. }
  74251. GLTFLoader.RegisterExtension = function (extension) {
  74252. if (GLTFLoader.Extensions[extension.name]) {
  74253. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  74254. return;
  74255. }
  74256. GLTFLoader.Extensions[extension.name] = extension;
  74257. };
  74258. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74259. var _this = this;
  74260. scene.useRightHandedSystem = true;
  74261. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  74262. gltfRuntime.importOnlyMeshes = true;
  74263. if (meshesNames === "") {
  74264. gltfRuntime.importMeshesNames = [];
  74265. }
  74266. else if (typeof meshesNames === "string") {
  74267. gltfRuntime.importMeshesNames = [meshesNames];
  74268. }
  74269. else if (meshesNames && !(meshesNames instanceof Array)) {
  74270. gltfRuntime.importMeshesNames = [meshesNames];
  74271. }
  74272. else {
  74273. gltfRuntime.importMeshesNames = [];
  74274. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  74275. }
  74276. // Create nodes
  74277. _this._createNodes(gltfRuntime);
  74278. var meshes = [];
  74279. var skeletons = [];
  74280. // Fill arrays of meshes and skeletons
  74281. for (var nde in gltfRuntime.nodes) {
  74282. var node = gltfRuntime.nodes[nde];
  74283. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  74284. meshes.push(node.babylonNode);
  74285. }
  74286. }
  74287. for (var skl in gltfRuntime.skins) {
  74288. var skin = gltfRuntime.skins[skl];
  74289. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  74290. skeletons.push(skin.babylonSkeleton);
  74291. }
  74292. }
  74293. // Load buffers, shaders, materials, etc.
  74294. _this._loadBuffersAsync(gltfRuntime, function () {
  74295. _this._loadShadersAsync(gltfRuntime, function () {
  74296. importMaterials(gltfRuntime);
  74297. postLoad(gltfRuntime);
  74298. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  74299. onSuccess(meshes, null, skeletons);
  74300. }
  74301. });
  74302. }, onProgress);
  74303. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  74304. onSuccess(meshes, null, skeletons);
  74305. }
  74306. }, onError);
  74307. return true;
  74308. };
  74309. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  74310. var _this = this;
  74311. scene.useRightHandedSystem = true;
  74312. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  74313. // Load runtime extensios
  74314. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  74315. // Create nodes
  74316. _this._createNodes(gltfRuntime);
  74317. // Load buffers, shaders, materials, etc.
  74318. _this._loadBuffersAsync(gltfRuntime, function () {
  74319. _this._loadShadersAsync(gltfRuntime, function () {
  74320. importMaterials(gltfRuntime);
  74321. postLoad(gltfRuntime);
  74322. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  74323. onSuccess();
  74324. }
  74325. });
  74326. });
  74327. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  74328. onSuccess();
  74329. }
  74330. }, onError);
  74331. }, onError);
  74332. };
  74333. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  74334. var hasShaders = false;
  74335. var processShader = function (sha, shader) {
  74336. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  74337. gltfRuntime.loadedShaderCount++;
  74338. if (shaderString) {
  74339. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  74340. }
  74341. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  74342. onload();
  74343. }
  74344. }, function () {
  74345. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  74346. });
  74347. };
  74348. for (var sha in gltfRuntime.shaders) {
  74349. hasShaders = true;
  74350. var shader = gltfRuntime.shaders[sha];
  74351. if (shader) {
  74352. processShader.bind(this, sha, shader)();
  74353. }
  74354. else {
  74355. BABYLON.Tools.Error("No shader named: " + sha);
  74356. }
  74357. }
  74358. if (!hasShaders) {
  74359. onload();
  74360. }
  74361. };
  74362. ;
  74363. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  74364. var hasBuffers = false;
  74365. var processBuffer = function (buf, buffer) {
  74366. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  74367. gltfRuntime.loadedBufferCount++;
  74368. if (bufferView) {
  74369. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  74370. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  74371. }
  74372. gltfRuntime.loadedBufferViews[buf] = bufferView;
  74373. }
  74374. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  74375. onLoad();
  74376. }
  74377. }, function () {
  74378. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  74379. });
  74380. };
  74381. for (var buf in gltfRuntime.buffers) {
  74382. hasBuffers = true;
  74383. var buffer = gltfRuntime.buffers[buf];
  74384. if (buffer) {
  74385. processBuffer.bind(this, buf, buffer)();
  74386. }
  74387. else {
  74388. BABYLON.Tools.Error("No buffer named: " + buf);
  74389. }
  74390. }
  74391. if (!hasBuffers) {
  74392. onLoad();
  74393. }
  74394. };
  74395. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  74396. var currentScene = gltfRuntime.currentScene;
  74397. if (currentScene) {
  74398. // Only one scene even if multiple scenes are defined
  74399. for (var i = 0; i < currentScene.nodes.length; i++) {
  74400. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74401. }
  74402. }
  74403. else {
  74404. // Load all scenes
  74405. for (var thing in gltfRuntime.scenes) {
  74406. currentScene = gltfRuntime.scenes[thing];
  74407. for (var i = 0; i < currentScene.nodes.length; i++) {
  74408. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74409. }
  74410. }
  74411. }
  74412. };
  74413. GLTFLoader.Extensions = {};
  74414. return GLTFLoader;
  74415. }());
  74416. GLTF1.GLTFLoader = GLTFLoader;
  74417. ;
  74418. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  74419. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74420. })(BABYLON || (BABYLON = {}));
  74421. //# sourceMappingURL=babylon.glTFLoader.js.map
  74422. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74423. var BABYLON;
  74424. (function (BABYLON) {
  74425. var GLTF1;
  74426. (function (GLTF1) {
  74427. /**
  74428. * Utils functions for GLTF
  74429. */
  74430. var GLTFUtils = (function () {
  74431. function GLTFUtils() {
  74432. }
  74433. /**
  74434. * Sets the given "parameter" matrix
  74435. * @param scene: the {BABYLON.Scene} object
  74436. * @param source: the source node where to pick the matrix
  74437. * @param parameter: the GLTF technique parameter
  74438. * @param uniformName: the name of the shader's uniform
  74439. * @param shaderMaterial: the shader material
  74440. */
  74441. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  74442. var mat = null;
  74443. if (parameter.semantic === "MODEL") {
  74444. mat = source.getWorldMatrix();
  74445. }
  74446. else if (parameter.semantic === "PROJECTION") {
  74447. mat = scene.getProjectionMatrix();
  74448. }
  74449. else if (parameter.semantic === "VIEW") {
  74450. mat = scene.getViewMatrix();
  74451. }
  74452. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  74453. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  74454. }
  74455. else if (parameter.semantic === "MODELVIEW") {
  74456. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  74457. }
  74458. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  74459. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  74460. }
  74461. else if (parameter.semantic === "MODELINVERSE") {
  74462. mat = source.getWorldMatrix().invert();
  74463. }
  74464. else if (parameter.semantic === "VIEWINVERSE") {
  74465. mat = scene.getViewMatrix().invert();
  74466. }
  74467. else if (parameter.semantic === "PROJECTIONINVERSE") {
  74468. mat = scene.getProjectionMatrix().invert();
  74469. }
  74470. else if (parameter.semantic === "MODELVIEWINVERSE") {
  74471. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  74472. }
  74473. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  74474. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  74475. }
  74476. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  74477. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  74478. }
  74479. else {
  74480. debugger;
  74481. }
  74482. switch (parameter.type) {
  74483. case GLTF1.EParameterType.FLOAT_MAT2:
  74484. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  74485. break;
  74486. case GLTF1.EParameterType.FLOAT_MAT3:
  74487. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  74488. break;
  74489. case GLTF1.EParameterType.FLOAT_MAT4:
  74490. shaderMaterial.setMatrix(uniformName, mat);
  74491. break;
  74492. default: break;
  74493. }
  74494. };
  74495. /**
  74496. * Sets the given "parameter" matrix
  74497. * @param shaderMaterial: the shader material
  74498. * @param uniform: the name of the shader's uniform
  74499. * @param value: the value of the uniform
  74500. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  74501. */
  74502. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  74503. switch (type) {
  74504. case GLTF1.EParameterType.FLOAT:
  74505. shaderMaterial.setFloat(uniform, value);
  74506. return true;
  74507. case GLTF1.EParameterType.FLOAT_VEC2:
  74508. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  74509. return true;
  74510. case GLTF1.EParameterType.FLOAT_VEC3:
  74511. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  74512. return true;
  74513. case GLTF1.EParameterType.FLOAT_VEC4:
  74514. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  74515. return true;
  74516. default: return false;
  74517. }
  74518. };
  74519. /**
  74520. * If the uri is a base64 string
  74521. * @param uri: the uri to test
  74522. */
  74523. GLTFUtils.IsBase64 = function (uri) {
  74524. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  74525. };
  74526. /**
  74527. * Decode the base64 uri
  74528. * @param uri: the uri to decode
  74529. */
  74530. GLTFUtils.DecodeBase64 = function (uri) {
  74531. var decodedString = atob(uri.split(",")[1]);
  74532. var bufferLength = decodedString.length;
  74533. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  74534. for (var i = 0; i < bufferLength; i++) {
  74535. bufferView[i] = decodedString.charCodeAt(i);
  74536. }
  74537. return bufferView.buffer;
  74538. };
  74539. /**
  74540. * Returns the wrap mode of the texture
  74541. * @param mode: the mode value
  74542. */
  74543. GLTFUtils.GetWrapMode = function (mode) {
  74544. switch (mode) {
  74545. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  74546. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  74547. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74548. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74549. }
  74550. };
  74551. /**
  74552. * Returns the byte stride giving an accessor
  74553. * @param accessor: the GLTF accessor objet
  74554. */
  74555. GLTFUtils.GetByteStrideFromType = function (accessor) {
  74556. // Needs this function since "byteStride" isn't requiered in glTF format
  74557. var type = accessor.type;
  74558. switch (type) {
  74559. case "VEC2": return 2;
  74560. case "VEC3": return 3;
  74561. case "VEC4": return 4;
  74562. case "MAT2": return 4;
  74563. case "MAT3": return 9;
  74564. case "MAT4": return 16;
  74565. default: return 1;
  74566. }
  74567. };
  74568. /**
  74569. * Returns the texture filter mode giving a mode value
  74570. * @param mode: the filter mode value
  74571. */
  74572. GLTFUtils.GetTextureFilterMode = function (mode) {
  74573. switch (mode) {
  74574. case GLTF1.ETextureFilterType.LINEAR:
  74575. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  74576. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  74577. case GLTF1.ETextureFilterType.NEAREST:
  74578. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74579. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  74580. }
  74581. };
  74582. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  74583. var byteOffset = bufferView.byteOffset + byteOffset;
  74584. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  74585. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  74586. throw new Error("Buffer access is out of range");
  74587. }
  74588. var buffer = loadedBufferView.buffer;
  74589. byteOffset += loadedBufferView.byteOffset;
  74590. switch (componentType) {
  74591. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  74592. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  74593. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  74594. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  74595. default: return new Float32Array(buffer, byteOffset, byteLength);
  74596. }
  74597. };
  74598. /**
  74599. * Returns a buffer from its accessor
  74600. * @param gltfRuntime: the GLTF runtime
  74601. * @param accessor: the GLTF accessor
  74602. */
  74603. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  74604. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  74605. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  74606. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  74607. };
  74608. /**
  74609. * Decodes a buffer view into a string
  74610. * @param view: the buffer view
  74611. */
  74612. GLTFUtils.DecodeBufferToText = function (view) {
  74613. var result = "";
  74614. var length = view.byteLength;
  74615. for (var i = 0; i < length; ++i) {
  74616. result += String.fromCharCode(view[i]);
  74617. }
  74618. return result;
  74619. };
  74620. /**
  74621. * Returns the default material of gltf. Related to
  74622. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  74623. * @param scene: the Babylon.js scene
  74624. */
  74625. GLTFUtils.GetDefaultMaterial = function (scene) {
  74626. if (!GLTFUtils._DefaultMaterial) {
  74627. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  74628. "precision highp float;",
  74629. "",
  74630. "uniform mat4 worldView;",
  74631. "uniform mat4 projection;",
  74632. "",
  74633. "attribute vec3 position;",
  74634. "",
  74635. "void main(void)",
  74636. "{",
  74637. " gl_Position = projection * worldView * vec4(position, 1.0);",
  74638. "}"
  74639. ].join("\n");
  74640. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  74641. "precision highp float;",
  74642. "",
  74643. "uniform vec4 u_emission;",
  74644. "",
  74645. "void main(void)",
  74646. "{",
  74647. " gl_FragColor = u_emission;",
  74648. "}"
  74649. ].join("\n");
  74650. var shaderPath = {
  74651. vertex: "GLTFDefaultMaterial",
  74652. fragment: "GLTFDefaultMaterial"
  74653. };
  74654. var options = {
  74655. attributes: ["position"],
  74656. uniforms: ["worldView", "projection", "u_emission"],
  74657. samplers: [],
  74658. needAlphaBlending: false
  74659. };
  74660. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  74661. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  74662. }
  74663. return GLTFUtils._DefaultMaterial;
  74664. };
  74665. // The GLTF default material
  74666. GLTFUtils._DefaultMaterial = null;
  74667. return GLTFUtils;
  74668. }());
  74669. GLTF1.GLTFUtils = GLTFUtils;
  74670. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74671. })(BABYLON || (BABYLON = {}));
  74672. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  74673. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74674. var BABYLON;
  74675. (function (BABYLON) {
  74676. var GLTF1;
  74677. (function (GLTF1) {
  74678. var GLTFLoaderExtension = (function () {
  74679. function GLTFLoaderExtension(name) {
  74680. this._name = name;
  74681. }
  74682. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  74683. get: function () {
  74684. return this._name;
  74685. },
  74686. enumerable: true,
  74687. configurable: true
  74688. });
  74689. /**
  74690. * Defines an override for loading the runtime
  74691. * Return true to stop further extensions from loading the runtime
  74692. */
  74693. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74694. return false;
  74695. };
  74696. /**
  74697. * Defines an onverride for creating gltf runtime
  74698. * Return true to stop further extensions from creating the runtime
  74699. */
  74700. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74701. return false;
  74702. };
  74703. /**
  74704. * Defines an override for loading buffers
  74705. * Return true to stop further extensions from loading this buffer
  74706. */
  74707. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74708. return false;
  74709. };
  74710. /**
  74711. * Defines an override for loading texture buffers
  74712. * Return true to stop further extensions from loading this texture data
  74713. */
  74714. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74715. return false;
  74716. };
  74717. /**
  74718. * Defines an override for creating textures
  74719. * Return true to stop further extensions from loading this texture
  74720. */
  74721. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74722. return false;
  74723. };
  74724. /**
  74725. * Defines an override for loading shader strings
  74726. * Return true to stop further extensions from loading this shader data
  74727. */
  74728. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74729. return false;
  74730. };
  74731. /**
  74732. * Defines an override for loading materials
  74733. * Return true to stop further extensions from loading this material
  74734. */
  74735. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74736. return false;
  74737. };
  74738. // ---------
  74739. // Utilities
  74740. // ---------
  74741. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74742. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74743. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  74744. }, function () {
  74745. setTimeout(function () {
  74746. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74747. });
  74748. });
  74749. };
  74750. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74751. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74752. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  74753. }, function () {
  74754. setTimeout(function () {
  74755. onSuccess();
  74756. });
  74757. });
  74758. };
  74759. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74760. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74761. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74762. }, function () {
  74763. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74764. });
  74765. };
  74766. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  74767. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  74768. };
  74769. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74770. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74771. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74772. }, function () {
  74773. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74774. });
  74775. };
  74776. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74777. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74778. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74779. }, function () {
  74780. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74781. });
  74782. };
  74783. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74784. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74785. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74786. }, function () {
  74787. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  74788. });
  74789. };
  74790. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74791. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74792. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74793. }, function () {
  74794. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  74795. });
  74796. };
  74797. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  74798. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  74799. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  74800. if (func(loaderExtension)) {
  74801. return;
  74802. }
  74803. }
  74804. defaultFunc();
  74805. };
  74806. return GLTFLoaderExtension;
  74807. }());
  74808. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  74809. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74810. })(BABYLON || (BABYLON = {}));
  74811. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  74812. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74813. var BABYLON;
  74814. (function (BABYLON) {
  74815. var GLTF1;
  74816. (function (GLTF1) {
  74817. var BinaryExtensionBufferName = "binary_glTF";
  74818. var EContentFormat;
  74819. (function (EContentFormat) {
  74820. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  74821. })(EContentFormat || (EContentFormat = {}));
  74822. ;
  74823. ;
  74824. ;
  74825. var GLTFBinaryExtension = (function (_super) {
  74826. __extends(GLTFBinaryExtension, _super);
  74827. function GLTFBinaryExtension() {
  74828. return _super.call(this, "KHR_binary_glTF") || this;
  74829. }
  74830. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74831. var extensionsUsed = data.json.extensionsUsed;
  74832. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  74833. return false;
  74834. }
  74835. this._bin = data.bin;
  74836. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74837. return true;
  74838. };
  74839. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74840. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  74841. return false;
  74842. }
  74843. if (id !== BinaryExtensionBufferName) {
  74844. return false;
  74845. }
  74846. onSuccess(this._bin);
  74847. return true;
  74848. };
  74849. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74850. var texture = gltfRuntime.textures[id];
  74851. var source = gltfRuntime.images[texture.source];
  74852. if (!source.extensions || !(this.name in source.extensions)) {
  74853. return false;
  74854. }
  74855. var sourceExt = source.extensions[this.name];
  74856. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  74857. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74858. onSuccess(buffer);
  74859. return true;
  74860. };
  74861. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74862. var shader = gltfRuntime.shaders[id];
  74863. if (!shader.extensions || !(this.name in shader.extensions)) {
  74864. return false;
  74865. }
  74866. var binaryExtensionShader = shader.extensions[this.name];
  74867. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  74868. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  74869. setTimeout(function () {
  74870. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  74871. onSuccess(shaderString);
  74872. });
  74873. return true;
  74874. };
  74875. return GLTFBinaryExtension;
  74876. }(GLTF1.GLTFLoaderExtension));
  74877. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  74878. var BinaryReader = (function () {
  74879. function BinaryReader(arrayBuffer) {
  74880. this._arrayBuffer = arrayBuffer;
  74881. this._dataView = new DataView(arrayBuffer);
  74882. this._byteOffset = 0;
  74883. }
  74884. BinaryReader.prototype.getUint32 = function () {
  74885. var value = this._dataView.getUint32(this._byteOffset, true);
  74886. this._byteOffset += 4;
  74887. return value;
  74888. };
  74889. BinaryReader.prototype.getUint8Array = function (length) {
  74890. if (!length) {
  74891. length = this._arrayBuffer.byteLength - this._byteOffset;
  74892. }
  74893. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  74894. this._byteOffset += length;
  74895. return value;
  74896. };
  74897. return BinaryReader;
  74898. }());
  74899. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  74900. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74901. })(BABYLON || (BABYLON = {}));
  74902. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  74903. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74904. var BABYLON;
  74905. (function (BABYLON) {
  74906. var GLTF1;
  74907. (function (GLTF1) {
  74908. ;
  74909. ;
  74910. ;
  74911. var GLTFMaterialsCommonExtension = (function (_super) {
  74912. __extends(GLTFMaterialsCommonExtension, _super);
  74913. function GLTFMaterialsCommonExtension() {
  74914. return _super.call(this, "KHR_materials_common") || this;
  74915. }
  74916. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74917. if (!gltfRuntime.extensions)
  74918. return false;
  74919. var extension = gltfRuntime.extensions[this.name];
  74920. if (!extension)
  74921. return false;
  74922. // Create lights
  74923. var lights = extension.lights;
  74924. if (lights) {
  74925. for (var thing in lights) {
  74926. var light = lights[thing];
  74927. switch (light.type) {
  74928. case "ambient":
  74929. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  74930. var ambient = light.ambient;
  74931. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  74932. break;
  74933. case "point":
  74934. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  74935. var point = light.point;
  74936. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  74937. break;
  74938. case "directional":
  74939. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  74940. var directional = light.directional;
  74941. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  74942. break;
  74943. case "spot":
  74944. var spot = light.spot;
  74945. 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);
  74946. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  74947. break;
  74948. default:
  74949. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  74950. break;
  74951. }
  74952. }
  74953. }
  74954. return false;
  74955. };
  74956. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74957. var material = gltfRuntime.materials[id];
  74958. if (!material || !material.extensions)
  74959. return false;
  74960. var extension = material.extensions[this.name];
  74961. if (!extension)
  74962. return false;
  74963. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  74964. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74965. if (extension.technique === "CONSTANT") {
  74966. standardMaterial.disableLighting = true;
  74967. }
  74968. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  74969. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  74970. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  74971. // Ambient
  74972. if (typeof extension.values.ambient === "string") {
  74973. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  74974. }
  74975. else {
  74976. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  74977. }
  74978. // Diffuse
  74979. if (typeof extension.values.diffuse === "string") {
  74980. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  74981. }
  74982. else {
  74983. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  74984. }
  74985. // Emission
  74986. if (typeof extension.values.emission === "string") {
  74987. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  74988. }
  74989. else {
  74990. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  74991. }
  74992. // Specular
  74993. if (typeof extension.values.specular === "string") {
  74994. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  74995. }
  74996. else {
  74997. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  74998. }
  74999. return true;
  75000. };
  75001. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  75002. // Create buffer from texture url
  75003. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  75004. // Create texture from buffer
  75005. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  75006. }, onError);
  75007. };
  75008. return GLTFMaterialsCommonExtension;
  75009. }(GLTF1.GLTFLoaderExtension));
  75010. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  75011. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  75012. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75013. })(BABYLON || (BABYLON = {}));
  75014. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  75015. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75016. var BABYLON;
  75017. (function (BABYLON) {
  75018. var GLTF2;
  75019. (function (GLTF2) {
  75020. /**
  75021. * Enums
  75022. */
  75023. var EComponentType;
  75024. (function (EComponentType) {
  75025. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  75026. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75027. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  75028. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75029. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  75030. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  75031. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  75032. var EMeshPrimitiveMode;
  75033. (function (EMeshPrimitiveMode) {
  75034. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  75035. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  75036. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  75037. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  75038. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  75039. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  75040. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  75041. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  75042. var ETextureMagFilter;
  75043. (function (ETextureMagFilter) {
  75044. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  75045. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  75046. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  75047. var ETextureMinFilter;
  75048. (function (ETextureMinFilter) {
  75049. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  75050. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  75051. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  75052. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  75053. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  75054. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  75055. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  75056. var ETextureWrapMode;
  75057. (function (ETextureWrapMode) {
  75058. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  75059. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  75060. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  75061. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  75062. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75063. })(BABYLON || (BABYLON = {}));
  75064. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  75065. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75066. var BABYLON;
  75067. (function (BABYLON) {
  75068. var GLTF2;
  75069. (function (GLTF2) {
  75070. var GLTFLoaderTracker = (function () {
  75071. function GLTFLoaderTracker(onComplete) {
  75072. this._pendingCount = 0;
  75073. this._callback = onComplete;
  75074. }
  75075. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  75076. this._pendingCount++;
  75077. };
  75078. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  75079. if (--this._pendingCount === 0) {
  75080. this._callback();
  75081. }
  75082. };
  75083. return GLTFLoaderTracker;
  75084. }());
  75085. var GLTFLoader = (function () {
  75086. function GLTFLoader(parent) {
  75087. this._renderReady = false;
  75088. this._disposed = false;
  75089. this._renderReadyObservable = new BABYLON.Observable();
  75090. // Count of pending work that needs to complete before the asset is rendered.
  75091. this._renderPendingCount = 0;
  75092. // Count of pending work that needs to complete before the loader is disposed.
  75093. this._loaderPendingCount = 0;
  75094. this._loaderTrackers = new Array();
  75095. this._parent = parent;
  75096. }
  75097. GLTFLoader.RegisterExtension = function (extension) {
  75098. if (GLTFLoader.Extensions[extension.name]) {
  75099. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  75100. return;
  75101. }
  75102. GLTFLoader.Extensions[extension.name] = extension;
  75103. // Keep the order of registration so that extensions registered first are called first.
  75104. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  75105. };
  75106. GLTFLoader.prototype.dispose = function () {
  75107. if (this._disposed) {
  75108. return;
  75109. }
  75110. this._disposed = true;
  75111. // Revoke object urls created during load
  75112. if (this._gltf.textures) {
  75113. this._gltf.textures.forEach(function (texture) {
  75114. if (texture.url) {
  75115. URL.revokeObjectURL(texture.url);
  75116. }
  75117. });
  75118. }
  75119. this._gltf = undefined;
  75120. this._babylonScene = undefined;
  75121. this._rootUrl = undefined;
  75122. this._defaultMaterial = undefined;
  75123. this._successCallback = undefined;
  75124. this._errorCallback = undefined;
  75125. this._renderReady = false;
  75126. this._renderReadyObservable.clear();
  75127. this._renderPendingCount = 0;
  75128. this._loaderPendingCount = 0;
  75129. };
  75130. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75131. var _this = this;
  75132. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  75133. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  75134. }, onProgress, onError);
  75135. };
  75136. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75137. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  75138. };
  75139. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75140. var _this = this;
  75141. this._tryCatchOnError(function () {
  75142. _this._loadData(data);
  75143. _this._babylonScene = scene;
  75144. _this._rootUrl = rootUrl;
  75145. _this._successCallback = onSuccess;
  75146. _this._progressCallback = onProgress;
  75147. _this._errorCallback = onError;
  75148. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  75149. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  75150. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  75151. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  75152. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  75153. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  75154. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  75155. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  75156. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  75157. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  75158. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  75159. _this._addPendingData(_this);
  75160. _this._loadDefaultScene(nodeNames);
  75161. _this._loadAnimations();
  75162. _this._removePendingData(_this);
  75163. });
  75164. };
  75165. GLTFLoader.prototype._onError = function (message) {
  75166. if (this._disposed) {
  75167. return;
  75168. }
  75169. BABYLON.Tools.Error("glTF Loader: " + message);
  75170. if (this._errorCallback) {
  75171. this._errorCallback(message);
  75172. }
  75173. this.dispose();
  75174. };
  75175. GLTFLoader.prototype._onProgress = function (event) {
  75176. if (this._disposed) {
  75177. return;
  75178. }
  75179. if (this._progressCallback) {
  75180. this._progressCallback(event);
  75181. }
  75182. };
  75183. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  75184. if (this._renderReady) {
  75185. func();
  75186. }
  75187. else {
  75188. this._renderReadyObservable.add(func);
  75189. }
  75190. };
  75191. GLTFLoader.prototype._onRenderReady = function () {
  75192. this._rootNode.babylonMesh.setEnabled(true);
  75193. this._startAnimations();
  75194. this._successCallback();
  75195. this._renderReadyObservable.notifyObservers(this);
  75196. if (this._parent.onReady) {
  75197. this._parent.onReady();
  75198. }
  75199. };
  75200. GLTFLoader.prototype._onComplete = function () {
  75201. if (this._parent.onComplete) {
  75202. this._parent.onComplete();
  75203. }
  75204. this.dispose();
  75205. };
  75206. GLTFLoader.prototype._loadData = function (data) {
  75207. this._gltf = data.json;
  75208. if (data.bin) {
  75209. var buffers = this._gltf.buffers;
  75210. if (buffers && buffers[0] && !buffers[0].uri) {
  75211. var binaryBuffer = buffers[0];
  75212. if (binaryBuffer.byteLength != data.bin.byteLength) {
  75213. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  75214. }
  75215. binaryBuffer.loadedData = data.bin;
  75216. }
  75217. else {
  75218. BABYLON.Tools.Warn("Unexpected BIN chunk");
  75219. }
  75220. }
  75221. };
  75222. GLTFLoader.prototype._getMeshes = function () {
  75223. var meshes = [this._rootNode.babylonMesh];
  75224. var nodes = this._gltf.nodes;
  75225. if (nodes) {
  75226. nodes.forEach(function (node) {
  75227. if (node.babylonMesh) {
  75228. meshes.push(node.babylonMesh);
  75229. }
  75230. });
  75231. }
  75232. return meshes;
  75233. };
  75234. GLTFLoader.prototype._getSkeletons = function () {
  75235. var skeletons = [];
  75236. var skins = this._gltf.skins;
  75237. if (skins) {
  75238. skins.forEach(function (skin) {
  75239. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  75240. skeletons.push(skin.babylonSkeleton);
  75241. }
  75242. });
  75243. }
  75244. return skeletons;
  75245. };
  75246. GLTFLoader.prototype._getAnimationTargets = function () {
  75247. var targets = [];
  75248. var animations = this._gltf.animations;
  75249. if (animations) {
  75250. animations.forEach(function (animation) {
  75251. targets.push.apply(targets, animation.targets);
  75252. });
  75253. }
  75254. return targets;
  75255. };
  75256. GLTFLoader.prototype._startAnimations = function () {
  75257. var _this = this;
  75258. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  75259. };
  75260. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  75261. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  75262. if (!scene) {
  75263. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  75264. }
  75265. this._loadScene("scenes[" + scene.index + "]", scene, nodeNames);
  75266. };
  75267. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  75268. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  75269. switch (this._parent.coordinateSystemMode) {
  75270. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  75271. if (!this._babylonScene.useRightHandedSystem) {
  75272. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  75273. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  75274. }
  75275. break;
  75276. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  75277. // do nothing
  75278. break;
  75279. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  75280. this._babylonScene.useRightHandedSystem = true;
  75281. break;
  75282. default:
  75283. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  75284. return;
  75285. }
  75286. var nodeIndices = scene.nodes;
  75287. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  75288. node.parent = parentNode;
  75289. return true;
  75290. }, this._rootNode);
  75291. if (nodeNames) {
  75292. if (!(nodeNames instanceof Array)) {
  75293. nodeNames = [nodeNames];
  75294. }
  75295. var filteredNodeIndices = new Array();
  75296. this._traverseNodes(context, nodeIndices, function (node) {
  75297. if (nodeNames.indexOf(node.name) !== -1) {
  75298. filteredNodeIndices.push(node.index);
  75299. return false;
  75300. }
  75301. return true;
  75302. }, this._rootNode);
  75303. nodeIndices = filteredNodeIndices;
  75304. }
  75305. for (var i = 0; i < nodeIndices.length; i++) {
  75306. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, nodeIndices[i]);
  75307. if (!node) {
  75308. throw new Error(context + ": Failed to find node " + nodeIndices[i]);
  75309. }
  75310. this._loadNode("nodes[" + nodeIndices[i] + "]", node);
  75311. }
  75312. // Disable the root mesh until the asset is ready to render.
  75313. this._rootNode.babylonMesh.setEnabled(false);
  75314. };
  75315. GLTFLoader.prototype._loadNode = function (context, node) {
  75316. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  75317. return;
  75318. }
  75319. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  75320. this._loadTransform(node);
  75321. if (node.mesh != null) {
  75322. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  75323. if (!mesh) {
  75324. throw new Error(context + ": Failed to find mesh " + node.mesh);
  75325. }
  75326. this._loadMesh("meshes[" + node.mesh + "]", node, mesh);
  75327. }
  75328. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  75329. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  75330. node.babylonAnimationTargets.push(node.babylonMesh);
  75331. if (node.skin != null) {
  75332. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  75333. if (!skin) {
  75334. throw new Error(context + ": Failed to find skin " + node.skin);
  75335. }
  75336. node.babylonMesh.skeleton = this._loadSkin("skins[" + node.skin + "]", skin);
  75337. }
  75338. if (node.camera != null) {
  75339. // TODO: handle cameras
  75340. }
  75341. if (node.children) {
  75342. for (var i = 0; i < node.children.length; i++) {
  75343. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, node.children[i]);
  75344. if (!childNode) {
  75345. throw new Error(context + ": Failed to find child node " + node.children[i]);
  75346. }
  75347. this._loadNode("nodes[" + node.children[i] + "]", childNode);
  75348. }
  75349. }
  75350. };
  75351. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  75352. node.babylonMesh.name = mesh.name || node.babylonMesh.name;
  75353. var babylonMultiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  75354. node.babylonMesh.material = babylonMultiMaterial;
  75355. var geometry = new BABYLON.Geometry(node.babylonMesh.name, this._babylonScene, null, false, node.babylonMesh);
  75356. var vertexData = new BABYLON.VertexData();
  75357. vertexData.positions = [];
  75358. vertexData.indices = [];
  75359. var subMeshInfos = [];
  75360. var numRemainingPrimitives = mesh.primitives.length;
  75361. for (var index = 0; index < mesh.primitives.length; index++) {
  75362. var primitive = mesh.primitives[index];
  75363. this._loadPrimitive(context + "/primitives[" + index + "]", node, mesh, primitive, function (subVertexData, loadMaterial) {
  75364. subMeshInfos.push({
  75365. verticesStart: vertexData.positions.length,
  75366. verticesCount: subVertexData.positions.length,
  75367. indicesStart: vertexData.indices.length,
  75368. indicesCount: subVertexData.indices.length,
  75369. loadMaterial: loadMaterial
  75370. });
  75371. vertexData.merge(subVertexData);
  75372. if (--numRemainingPrimitives === 0) {
  75373. geometry.setAllVerticesData(vertexData, false);
  75374. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  75375. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  75376. node.babylonMesh.subMeshes = [];
  75377. for (var index = 0; index < subMeshInfos.length; index++) {
  75378. var info = subMeshInfos[index];
  75379. new BABYLON.SubMesh(index, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, node.babylonMesh);
  75380. info.loadMaterial(index);
  75381. }
  75382. }
  75383. });
  75384. }
  75385. };
  75386. GLTFLoader.prototype._loadPrimitive = function (context, node, mesh, primitive, onSuccess) {
  75387. var _this = this;
  75388. var subMaterials = node.babylonMesh.material.subMaterials;
  75389. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  75390. // TODO: handle other primitive modes
  75391. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  75392. }
  75393. this._createMorphTargets(node, mesh, primitive);
  75394. this._loadVertexDataAsync(context, mesh, primitive, function (vertexData) {
  75395. _this._loadMorphTargetsData(context, mesh, primitive, vertexData, node.babylonMesh);
  75396. var loadMaterial = function (index) {
  75397. if (primitive.material == null) {
  75398. subMaterials[index] = _this._getDefaultMaterial();
  75399. }
  75400. else {
  75401. var material = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.materials, primitive.material);
  75402. if (!material) {
  75403. throw new Error(context + ": Failed to find material " + primitive.material);
  75404. }
  75405. _this._loadMaterial("materials[" + material.index + "]", material, function (babylonMaterial, isNew) {
  75406. if (isNew && _this._parent.onMaterialLoaded) {
  75407. _this._parent.onMaterialLoaded(babylonMaterial);
  75408. }
  75409. if (_this._parent.onBeforeMaterialReadyAsync) {
  75410. _this._addLoaderPendingData(material);
  75411. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  75412. subMaterials[index] = babylonMaterial;
  75413. _this._removeLoaderPendingData(material);
  75414. });
  75415. }
  75416. else {
  75417. subMaterials[index] = babylonMaterial;
  75418. }
  75419. });
  75420. }
  75421. };
  75422. onSuccess(vertexData, loadMaterial);
  75423. });
  75424. };
  75425. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  75426. var _this = this;
  75427. var attributes = primitive.attributes;
  75428. if (!attributes) {
  75429. throw new Error(context + ": Attributes are missing");
  75430. }
  75431. var vertexData = new BABYLON.VertexData();
  75432. var numRemainingAttributes = Object.keys(attributes).length;
  75433. var _loop_1 = function (attribute) {
  75434. accessor = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.accessors, attributes[attribute]);
  75435. if (!accessor) {
  75436. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  75437. }
  75438. this_1._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  75439. switch (attribute) {
  75440. case "NORMAL":
  75441. vertexData.normals = data;
  75442. break;
  75443. case "POSITION":
  75444. vertexData.positions = data;
  75445. break;
  75446. case "TANGENT":
  75447. vertexData.tangents = data;
  75448. break;
  75449. case "TEXCOORD_0":
  75450. vertexData.uvs = data;
  75451. break;
  75452. case "TEXCOORD_1":
  75453. vertexData.uvs2 = data;
  75454. break;
  75455. case "JOINTS_0":
  75456. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  75457. break;
  75458. case "WEIGHTS_0":
  75459. vertexData.matricesWeights = data;
  75460. break;
  75461. case "COLOR_0":
  75462. vertexData.colors = data;
  75463. break;
  75464. default:
  75465. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  75466. break;
  75467. }
  75468. if (--numRemainingAttributes === 0) {
  75469. if (primitive.indices == null) {
  75470. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  75471. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  75472. onSuccess(vertexData);
  75473. }
  75474. else {
  75475. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  75476. if (!indicesAccessor) {
  75477. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  75478. }
  75479. _this._loadAccessorAsync("accessors[" + indicesAccessor.index + "]", indicesAccessor, function (data) {
  75480. vertexData.indices = data;
  75481. onSuccess(vertexData);
  75482. });
  75483. }
  75484. }
  75485. });
  75486. };
  75487. var this_1 = this, accessor;
  75488. for (var attribute in attributes) {
  75489. _loop_1(attribute);
  75490. }
  75491. };
  75492. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive) {
  75493. var targets = primitive.targets;
  75494. if (!targets) {
  75495. return;
  75496. }
  75497. if (!node.babylonMesh.morphTargetManager) {
  75498. node.babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  75499. }
  75500. for (var index = 0; index < targets.length; index++) {
  75501. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  75502. node.babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  75503. }
  75504. };
  75505. GLTFLoader.prototype._loadMorphTargetsData = function (context, mesh, primitive, vertexData, babylonMesh) {
  75506. var targets = primitive.targets;
  75507. if (!targets) {
  75508. return;
  75509. }
  75510. var _loop_2 = function () {
  75511. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  75512. attributes = targets[index];
  75513. var _loop_3 = function (attribute) {
  75514. accessor = GLTF2.GLTFUtils.GetArrayItem(this_2._gltf.accessors, attributes[attribute]);
  75515. if (!accessor) {
  75516. throw new Error(context + "/targets[" + index + "]: Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  75517. }
  75518. this_2._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  75519. if (accessor.name) {
  75520. babylonMorphTarget.name = accessor.name;
  75521. }
  75522. // glTF stores morph target information as deltas while babylon.js expects the final data.
  75523. // As a result we have to add the original data to the delta to calculate the final data.
  75524. var values = data;
  75525. switch (attribute) {
  75526. case "NORMAL":
  75527. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  75528. babylonMorphTarget.setNormals(values);
  75529. break;
  75530. case "POSITION":
  75531. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  75532. babylonMorphTarget.setPositions(values);
  75533. break;
  75534. case "TANGENT":
  75535. // Tangent data for morph targets is stored as xyz delta.
  75536. // The vertexData.tangent is stored as xyzw.
  75537. // So we need to skip every fourth vertexData.tangent.
  75538. for (var i = 0, j = 0; i < values.length; i++, j++) {
  75539. values[i] += vertexData.tangents[j];
  75540. if ((i + 1) % 3 == 0) {
  75541. j++;
  75542. }
  75543. }
  75544. babylonMorphTarget.setTangents(values);
  75545. break;
  75546. default:
  75547. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  75548. break;
  75549. }
  75550. });
  75551. };
  75552. for (var attribute in attributes) {
  75553. _loop_3(attribute);
  75554. }
  75555. };
  75556. var this_2 = this, attributes, accessor;
  75557. for (var index = 0; index < targets.length; index++) {
  75558. _loop_2();
  75559. }
  75560. };
  75561. GLTFLoader.prototype._loadTransform = function (node) {
  75562. var position = BABYLON.Vector3.Zero();
  75563. var rotation = BABYLON.Quaternion.Identity();
  75564. var scaling = BABYLON.Vector3.One();
  75565. if (node.matrix) {
  75566. var mat = BABYLON.Matrix.FromArray(node.matrix);
  75567. mat.decompose(scaling, rotation, position);
  75568. }
  75569. else {
  75570. if (node.translation)
  75571. position = BABYLON.Vector3.FromArray(node.translation);
  75572. if (node.rotation)
  75573. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  75574. if (node.scale)
  75575. scaling = BABYLON.Vector3.FromArray(node.scale);
  75576. }
  75577. node.babylonMesh.position = position;
  75578. node.babylonMesh.rotationQuaternion = rotation;
  75579. node.babylonMesh.scaling = scaling;
  75580. };
  75581. GLTFLoader.prototype._loadSkin = function (context, skin) {
  75582. var _this = this;
  75583. var skeletonId = "skeleton" + skin.index;
  75584. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  75585. if (skin.inverseBindMatrices == null) {
  75586. this._loadBones(context, skin, null);
  75587. }
  75588. else {
  75589. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  75590. if (!accessor) {
  75591. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  75592. }
  75593. this._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  75594. _this._loadBones(context, skin, data);
  75595. });
  75596. }
  75597. return skin.babylonSkeleton;
  75598. };
  75599. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  75600. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  75601. node.babylonBones = node.babylonBones || {};
  75602. node.babylonBones[skin.index] = babylonBone;
  75603. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  75604. node.babylonAnimationTargets.push(babylonBone);
  75605. return babylonBone;
  75606. };
  75607. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  75608. var babylonBones = {};
  75609. for (var i = 0; i < skin.joints.length; i++) {
  75610. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, skin.joints[i]);
  75611. if (!node) {
  75612. throw new Error(context + ": Failed to find joint " + skin.joints[i]);
  75613. }
  75614. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  75615. }
  75616. };
  75617. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  75618. var babylonBone = babylonBones[node.index];
  75619. if (babylonBone) {
  75620. return babylonBone;
  75621. }
  75622. var boneIndex = skin.joints.indexOf(node.index);
  75623. var baseMatrix = BABYLON.Matrix.Identity();
  75624. if (inverseBindMatrixData && boneIndex !== -1) {
  75625. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  75626. baseMatrix.invertToRef(baseMatrix);
  75627. }
  75628. var babylonParentBone;
  75629. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  75630. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  75631. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  75632. }
  75633. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  75634. babylonBones[node.index] = babylonBone;
  75635. return babylonBone;
  75636. };
  75637. GLTFLoader.prototype._getNodeMatrix = function (node) {
  75638. return node.matrix ?
  75639. BABYLON.Matrix.FromArray(node.matrix) :
  75640. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  75641. };
  75642. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  75643. if (parentNode === void 0) { parentNode = null; }
  75644. for (var i = 0; i < indices.length; i++) {
  75645. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, indices[i]);
  75646. if (!node) {
  75647. throw new Error(context + ": Failed to find node " + indices[i]);
  75648. }
  75649. this._traverseNode(context, node, action, parentNode);
  75650. }
  75651. };
  75652. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  75653. if (parentNode === void 0) { parentNode = null; }
  75654. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  75655. return;
  75656. }
  75657. if (!action(node, parentNode)) {
  75658. return;
  75659. }
  75660. if (node.children) {
  75661. this._traverseNodes(context, node.children, action, node);
  75662. }
  75663. };
  75664. GLTFLoader.prototype._loadAnimations = function () {
  75665. var animations = this._gltf.animations;
  75666. if (!animations) {
  75667. return;
  75668. }
  75669. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  75670. var animation = animations[animationIndex];
  75671. var context = "animations[" + animationIndex + "]";
  75672. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  75673. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  75674. if (!channel) {
  75675. throw new Error(context + ": Failed to find channel " + channelIndex);
  75676. }
  75677. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  75678. if (!sampler) {
  75679. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  75680. }
  75681. this._loadAnimationChannel(animation, context + "/channels[" + channelIndex + "]", channel, context + "/samplers[" + channel.sampler + "]", sampler);
  75682. }
  75683. }
  75684. };
  75685. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  75686. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  75687. if (!targetNode) {
  75688. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  75689. }
  75690. var targetPath = {
  75691. "translation": "position",
  75692. "rotation": "rotationQuaternion",
  75693. "scale": "scaling",
  75694. "weights": "influence"
  75695. }[channel.target.path];
  75696. if (!targetPath) {
  75697. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  75698. }
  75699. var animationType = {
  75700. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75701. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  75702. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75703. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  75704. }[targetPath];
  75705. var inputData;
  75706. var outputData;
  75707. var checkSuccess = function () {
  75708. if (!inputData || !outputData) {
  75709. return;
  75710. }
  75711. var outputBufferOffset = 0;
  75712. var getNextOutputValue = {
  75713. "position": function () {
  75714. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75715. outputBufferOffset += 3;
  75716. return value;
  75717. },
  75718. "rotationQuaternion": function () {
  75719. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  75720. outputBufferOffset += 4;
  75721. return value;
  75722. },
  75723. "scaling": function () {
  75724. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75725. outputBufferOffset += 3;
  75726. return value;
  75727. },
  75728. "influence": function () {
  75729. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  75730. var value = new Array(numTargets);
  75731. for (var i = 0; i < numTargets; i++) {
  75732. value[i] = outputData[outputBufferOffset++];
  75733. }
  75734. return value;
  75735. },
  75736. }[targetPath];
  75737. var getNextKey = {
  75738. "LINEAR": function (frameIndex) { return ({
  75739. frame: inputData[frameIndex],
  75740. value: getNextOutputValue()
  75741. }); },
  75742. "CUBICSPLINE": function (frameIndex) { return ({
  75743. frame: inputData[frameIndex],
  75744. inTangent: getNextOutputValue(),
  75745. value: getNextOutputValue(),
  75746. outTangent: getNextOutputValue()
  75747. }); },
  75748. }[sampler.interpolation];
  75749. if (!getNextKey) {
  75750. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  75751. }
  75752. var keys = new Array(inputData.length);
  75753. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  75754. keys[frameIndex] = getNextKey(frameIndex);
  75755. }
  75756. animation.targets = animation.targets || [];
  75757. if (targetPath === "influence") {
  75758. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  75759. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  75760. var morphTarget = morphTargetManager.getTarget(targetIndex);
  75761. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  75762. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  75763. babylonAnimation.setKeys(keys.map(function (key) { return ({
  75764. frame: key.frame,
  75765. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  75766. value: key.value[targetIndex],
  75767. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  75768. }); }));
  75769. morphTarget.animations.push(babylonAnimation);
  75770. animation.targets.push(morphTarget);
  75771. }
  75772. }
  75773. else {
  75774. var animationName = animation.name || "anim" + animation.index;
  75775. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  75776. babylonAnimation.setKeys(keys);
  75777. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  75778. var target = targetNode.babylonAnimationTargets[i];
  75779. target.animations.push(babylonAnimation.clone());
  75780. animation.targets.push(target);
  75781. }
  75782. }
  75783. };
  75784. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  75785. if (!inputAccessor) {
  75786. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  75787. }
  75788. this._loadAccessorAsync("accessors[" + inputAccessor.index + "]", inputAccessor, function (data) {
  75789. inputData = data;
  75790. checkSuccess();
  75791. });
  75792. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  75793. if (!outputAccessor) {
  75794. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  75795. }
  75796. this._loadAccessorAsync("accessors[" + outputAccessor.index + "]", outputAccessor, function (data) {
  75797. outputData = data;
  75798. checkSuccess();
  75799. });
  75800. };
  75801. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  75802. var _this = this;
  75803. this._addPendingData(buffer);
  75804. if (buffer.loadedData) {
  75805. onSuccess(buffer.loadedData);
  75806. this._removePendingData(buffer);
  75807. }
  75808. else if (buffer.loadedObservable) {
  75809. buffer.loadedObservable.add(function (buffer) {
  75810. onSuccess(buffer.loadedData);
  75811. _this._removePendingData(buffer);
  75812. });
  75813. }
  75814. else {
  75815. if (!buffer.uri) {
  75816. throw new Error(context + ": Uri is missing");
  75817. }
  75818. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  75819. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  75820. buffer.loadedData = new Uint8Array(data);
  75821. onSuccess(buffer.loadedData);
  75822. this._removePendingData(buffer);
  75823. }
  75824. else {
  75825. if (!GLTF2.GLTFUtils.ValidateUri(buffer.uri)) {
  75826. throw new Error(context + ": Uri '" + buffer.uri + "' is invalid");
  75827. }
  75828. buffer.loadedObservable = new BABYLON.Observable();
  75829. buffer.loadedObservable.add(function (buffer) {
  75830. onSuccess(buffer.loadedData);
  75831. _this._removePendingData(buffer);
  75832. });
  75833. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  75834. _this._tryCatchOnError(function () {
  75835. buffer.loadedData = new Uint8Array(data);
  75836. buffer.loadedObservable.notifyObservers(buffer);
  75837. buffer.loadedObservable = null;
  75838. });
  75839. }, function (event) {
  75840. _this._tryCatchOnError(function () {
  75841. _this._onProgress(event);
  75842. });
  75843. }, this._babylonScene.database, true, function (request) {
  75844. _this._tryCatchOnError(function () {
  75845. throw new Error(context + ": Failed to load '" + buffer.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  75846. });
  75847. });
  75848. }
  75849. }
  75850. };
  75851. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  75852. var _this = this;
  75853. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  75854. if (!buffer) {
  75855. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  75856. }
  75857. this._loadBufferAsync("buffers[" + buffer.index + "]", buffer, function (bufferData) {
  75858. if (_this._disposed) {
  75859. return;
  75860. }
  75861. try {
  75862. var data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  75863. }
  75864. catch (e) {
  75865. throw new Error(context + ": " + e.message);
  75866. }
  75867. onSuccess(data);
  75868. });
  75869. };
  75870. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  75871. var _this = this;
  75872. if (accessor.sparse) {
  75873. throw new Error(context + ": Sparse accessors are not currently supported");
  75874. }
  75875. if (accessor.normalized) {
  75876. throw new Error(context + ": Normalized accessors are not currently supported");
  75877. }
  75878. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  75879. if (!bufferView) {
  75880. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  75881. }
  75882. this._loadBufferViewAsync("bufferViews[" + bufferView.index + "]", bufferView, function (bufferViewData) {
  75883. var numComponents = _this._getNumComponentsOfType(accessor.type);
  75884. if (numComponents === 0) {
  75885. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  75886. }
  75887. var data;
  75888. switch (accessor.componentType) {
  75889. case GLTF2.EComponentType.BYTE:
  75890. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  75891. break;
  75892. case GLTF2.EComponentType.UNSIGNED_BYTE:
  75893. data = _this._buildArrayBuffer(Uint8Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  75894. break;
  75895. case GLTF2.EComponentType.SHORT:
  75896. data = _this._buildArrayBuffer(Int16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  75897. break;
  75898. case GLTF2.EComponentType.UNSIGNED_SHORT:
  75899. data = _this._buildArrayBuffer(Uint16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  75900. break;
  75901. case GLTF2.EComponentType.UNSIGNED_INT:
  75902. data = _this._buildArrayBuffer(Uint32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  75903. break;
  75904. case GLTF2.EComponentType.FLOAT:
  75905. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  75906. break;
  75907. default:
  75908. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  75909. }
  75910. onSuccess(data);
  75911. });
  75912. };
  75913. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  75914. switch (type) {
  75915. case "SCALAR": return 1;
  75916. case "VEC2": return 2;
  75917. case "VEC3": return 3;
  75918. case "VEC4": return 4;
  75919. case "MAT2": return 4;
  75920. case "MAT3": return 9;
  75921. case "MAT4": return 16;
  75922. }
  75923. return 0;
  75924. };
  75925. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, context, data, byteOffset, count, numComponents, byteStride) {
  75926. try {
  75927. var byteOffset = data.byteOffset + (byteOffset || 0);
  75928. var targetLength = count * numComponents;
  75929. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  75930. return new typedArray(data.buffer, byteOffset, targetLength);
  75931. }
  75932. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  75933. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  75934. var targetBuffer = new typedArray(targetLength);
  75935. var sourceIndex = 0;
  75936. var targetIndex = 0;
  75937. while (targetIndex < targetLength) {
  75938. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  75939. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  75940. targetIndex++;
  75941. }
  75942. sourceIndex += elementStride;
  75943. }
  75944. return targetBuffer;
  75945. }
  75946. catch (e) {
  75947. throw new Error(context + ": " + e);
  75948. }
  75949. };
  75950. GLTFLoader.prototype._addPendingData = function (data) {
  75951. if (!this._renderReady) {
  75952. this._renderPendingCount++;
  75953. }
  75954. this._addLoaderPendingData(data);
  75955. };
  75956. GLTFLoader.prototype._removePendingData = function (data) {
  75957. if (!this._renderReady) {
  75958. if (--this._renderPendingCount === 0) {
  75959. this._renderReady = true;
  75960. this._onRenderReady();
  75961. }
  75962. }
  75963. this._removeLoaderPendingData(data);
  75964. };
  75965. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  75966. this._loaderPendingCount++;
  75967. this._loaderTrackers.forEach(function (tracker) { return tracker._addPendingData(data); });
  75968. };
  75969. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  75970. this._loaderTrackers.forEach(function (tracker) { return tracker._removePendingData(data); });
  75971. if (--this._loaderPendingCount === 0) {
  75972. this._onComplete();
  75973. }
  75974. };
  75975. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  75976. var _this = this;
  75977. var tracker = new GLTFLoaderTracker(function () {
  75978. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker));
  75979. onComplete();
  75980. });
  75981. this._loaderTrackers.push(tracker);
  75982. this._addLoaderPendingData(tracker);
  75983. action();
  75984. this._removeLoaderPendingData(tracker);
  75985. };
  75986. GLTFLoader.prototype._getDefaultMaterial = function () {
  75987. if (!this._defaultMaterial) {
  75988. var id = "__gltf_default";
  75989. var material = this._babylonScene.getMaterialByName(id);
  75990. if (!material) {
  75991. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  75992. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75993. material.metallic = 1;
  75994. material.roughness = 1;
  75995. }
  75996. this._defaultMaterial = material;
  75997. }
  75998. return this._defaultMaterial;
  75999. };
  76000. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  76001. var babylonMaterial = material.babylonMaterial;
  76002. // Ensure metallic workflow
  76003. babylonMaterial.metallic = 1;
  76004. babylonMaterial.roughness = 1;
  76005. var properties = material.pbrMetallicRoughness;
  76006. if (!properties) {
  76007. return;
  76008. }
  76009. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  76010. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  76011. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  76012. if (properties.baseColorTexture) {
  76013. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  76014. if (!texture) {
  76015. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  76016. }
  76017. babylonMaterial.albedoTexture = this._loadTexture("textures[" + texture.index + "]", texture, properties.baseColorTexture.texCoord);
  76018. }
  76019. if (properties.metallicRoughnessTexture) {
  76020. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  76021. if (!texture) {
  76022. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  76023. }
  76024. babylonMaterial.metallicTexture = this._loadTexture("textures[" + texture.index + "]", texture, properties.metallicRoughnessTexture.texCoord);
  76025. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  76026. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  76027. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  76028. }
  76029. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  76030. };
  76031. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  76032. if (material.babylonMaterial) {
  76033. assign(material.babylonMaterial, false);
  76034. return;
  76035. }
  76036. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  76037. return;
  76038. }
  76039. this._createPbrMaterial(material);
  76040. this._loadMaterialBaseProperties(context, material);
  76041. this._loadMaterialMetallicRoughnessProperties(context, material);
  76042. assign(material.babylonMaterial, true);
  76043. };
  76044. GLTFLoader.prototype._createPbrMaterial = function (material) {
  76045. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  76046. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76047. material.babylonMaterial = babylonMaterial;
  76048. };
  76049. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  76050. var babylonMaterial = material.babylonMaterial;
  76051. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  76052. if (material.doubleSided) {
  76053. babylonMaterial.backFaceCulling = false;
  76054. babylonMaterial.twoSidedLighting = true;
  76055. }
  76056. if (material.normalTexture) {
  76057. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  76058. if (!texture) {
  76059. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  76060. }
  76061. babylonMaterial.bumpTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.normalTexture.texCoord);
  76062. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  76063. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  76064. if (material.normalTexture.scale != null) {
  76065. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  76066. }
  76067. }
  76068. if (material.occlusionTexture) {
  76069. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  76070. if (!texture) {
  76071. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  76072. }
  76073. babylonMaterial.ambientTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.occlusionTexture.texCoord);
  76074. babylonMaterial.useAmbientInGrayScale = true;
  76075. if (material.occlusionTexture.strength != null) {
  76076. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  76077. }
  76078. }
  76079. if (material.emissiveTexture) {
  76080. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  76081. if (!texture) {
  76082. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  76083. }
  76084. babylonMaterial.emissiveTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.emissiveTexture.texCoord);
  76085. }
  76086. };
  76087. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  76088. var babylonMaterial = material.babylonMaterial;
  76089. var alphaMode = material.alphaMode || "OPAQUE";
  76090. switch (alphaMode) {
  76091. case "OPAQUE":
  76092. // default is opaque
  76093. break;
  76094. case "MASK":
  76095. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  76096. if (colorFactor) {
  76097. if (colorFactor[3] == 0) {
  76098. babylonMaterial.alphaCutOff = 1;
  76099. }
  76100. else {
  76101. babylonMaterial.alphaCutOff /= colorFactor[3];
  76102. }
  76103. }
  76104. if (babylonMaterial.albedoTexture) {
  76105. babylonMaterial.albedoTexture.hasAlpha = true;
  76106. }
  76107. break;
  76108. case "BLEND":
  76109. if (colorFactor) {
  76110. babylonMaterial.alpha = colorFactor[3];
  76111. }
  76112. if (babylonMaterial.albedoTexture) {
  76113. babylonMaterial.albedoTexture.hasAlpha = true;
  76114. babylonMaterial.useAlphaFromAlbedoTexture = true;
  76115. }
  76116. break;
  76117. default:
  76118. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  76119. }
  76120. };
  76121. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  76122. var _this = this;
  76123. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  76124. if (!sampler) {
  76125. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  76126. }
  76127. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  76128. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  76129. this._addPendingData(texture);
  76130. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  76131. _this._tryCatchOnError(function () {
  76132. _this._removePendingData(texture);
  76133. });
  76134. }, function (message) {
  76135. _this._tryCatchOnError(function () {
  76136. throw new Error(context + ": " + message);
  76137. });
  76138. });
  76139. if (texture.url) {
  76140. babylonTexture.updateURL(texture.url);
  76141. }
  76142. else if (texture.dataReadyObservable) {
  76143. texture.dataReadyObservable.add(function (texture) {
  76144. babylonTexture.updateURL(texture.url);
  76145. });
  76146. }
  76147. else {
  76148. texture.dataReadyObservable = new BABYLON.Observable();
  76149. texture.dataReadyObservable.add(function (texture) {
  76150. babylonTexture.updateURL(texture.url);
  76151. });
  76152. var image = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  76153. if (!image) {
  76154. throw new Error(context + ": Failed to find source " + texture.source);
  76155. }
  76156. this._loadImage("images[" + image.index + "]", image, function (data) {
  76157. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  76158. texture.dataReadyObservable.notifyObservers(texture);
  76159. });
  76160. }
  76161. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  76162. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  76163. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  76164. babylonTexture.name = texture.name || "texture" + texture.index;
  76165. if (this._parent.onTextureLoaded) {
  76166. this._parent.onTextureLoaded(babylonTexture);
  76167. }
  76168. return babylonTexture;
  76169. };
  76170. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  76171. var _this = this;
  76172. if (image.uri) {
  76173. if (!GLTF2.GLTFUtils.ValidateUri(image.uri)) {
  76174. throw new Error(context + ": Uri '" + image.uri + "' is invalid");
  76175. }
  76176. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  76177. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  76178. }
  76179. else {
  76180. BABYLON.Tools.LoadFile(this._rootUrl + image.uri, function (data) {
  76181. _this._tryCatchOnError(function () {
  76182. onSuccess(data);
  76183. });
  76184. }, function (event) {
  76185. _this._tryCatchOnError(function () {
  76186. _this._onProgress(event);
  76187. });
  76188. }, this._babylonScene.database, true, function (request) {
  76189. _this._tryCatchOnError(function () {
  76190. throw new Error(context + ": Failed to load '" + image.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  76191. });
  76192. });
  76193. }
  76194. }
  76195. else {
  76196. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  76197. if (!bufferView) {
  76198. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  76199. }
  76200. this._loadBufferViewAsync("bufferViews[" + bufferView.index + "]", bufferView, onSuccess);
  76201. }
  76202. };
  76203. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  76204. try {
  76205. handler();
  76206. }
  76207. catch (e) {
  76208. this._onError(e.message);
  76209. }
  76210. };
  76211. GLTFLoader.Extensions = {};
  76212. return GLTFLoader;
  76213. }());
  76214. GLTF2.GLTFLoader = GLTFLoader;
  76215. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  76216. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76217. })(BABYLON || (BABYLON = {}));
  76218. //# sourceMappingURL=babylon.glTFLoader.js.map
  76219. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76220. var BABYLON;
  76221. (function (BABYLON) {
  76222. var GLTF2;
  76223. (function (GLTF2) {
  76224. /**
  76225. * Utils functions for GLTF
  76226. */
  76227. var GLTFUtils = (function () {
  76228. function GLTFUtils() {
  76229. }
  76230. /**
  76231. * If the uri is a base64 string
  76232. * @param uri: the uri to test
  76233. */
  76234. GLTFUtils.IsBase64 = function (uri) {
  76235. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  76236. };
  76237. /**
  76238. * Decode the base64 uri
  76239. * @param uri: the uri to decode
  76240. */
  76241. GLTFUtils.DecodeBase64 = function (uri) {
  76242. var decodedString = atob(uri.split(",")[1]);
  76243. var bufferLength = decodedString.length;
  76244. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  76245. for (var i = 0; i < bufferLength; i++) {
  76246. bufferView[i] = decodedString.charCodeAt(i);
  76247. }
  76248. return bufferView.buffer;
  76249. };
  76250. GLTFUtils.ForEach = function (view, func) {
  76251. for (var index = 0; index < view.length; index++) {
  76252. func(view[index], index);
  76253. }
  76254. };
  76255. GLTFUtils.ValidateUri = function (uri) {
  76256. return (uri.indexOf("..") === -1);
  76257. };
  76258. GLTFUtils.AssignIndices = function (array) {
  76259. if (array) {
  76260. for (var index = 0; index < array.length; index++) {
  76261. array[index].index = index;
  76262. }
  76263. }
  76264. };
  76265. GLTFUtils.GetArrayItem = function (array, index) {
  76266. if (!array || !array[index]) {
  76267. return null;
  76268. }
  76269. return array[index];
  76270. };
  76271. GLTFUtils.GetTextureWrapMode = function (mode) {
  76272. // Set defaults if undefined
  76273. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  76274. switch (mode) {
  76275. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  76276. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  76277. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  76278. default:
  76279. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  76280. return BABYLON.Texture.WRAP_ADDRESSMODE;
  76281. }
  76282. };
  76283. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  76284. // Set defaults if undefined
  76285. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  76286. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  76287. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  76288. switch (minFilter) {
  76289. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  76290. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  76291. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  76292. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  76293. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  76294. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  76295. default:
  76296. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  76297. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  76298. }
  76299. }
  76300. else {
  76301. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  76302. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  76303. }
  76304. switch (minFilter) {
  76305. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  76306. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  76307. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  76308. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  76309. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  76310. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  76311. default:
  76312. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  76313. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  76314. }
  76315. }
  76316. };
  76317. /**
  76318. * Decodes a buffer view into a string
  76319. * @param view: the buffer view
  76320. */
  76321. GLTFUtils.DecodeBufferToText = function (view) {
  76322. var result = "";
  76323. var length = view.byteLength;
  76324. for (var i = 0; i < length; ++i) {
  76325. result += String.fromCharCode(view[i]);
  76326. }
  76327. return result;
  76328. };
  76329. return GLTFUtils;
  76330. }());
  76331. GLTF2.GLTFUtils = GLTFUtils;
  76332. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76333. })(BABYLON || (BABYLON = {}));
  76334. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  76335. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76336. var BABYLON;
  76337. (function (BABYLON) {
  76338. var GLTF2;
  76339. (function (GLTF2) {
  76340. var GLTFLoaderExtension = (function () {
  76341. function GLTFLoaderExtension() {
  76342. this.enabled = true;
  76343. }
  76344. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  76345. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  76346. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  76347. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  76348. var _this = this;
  76349. if (!property.extensions) {
  76350. return false;
  76351. }
  76352. var extension = property.extensions[this.name];
  76353. if (!extension) {
  76354. return false;
  76355. }
  76356. // Clear out the extension before executing the action to avoid recursing into the same property.
  76357. property.extensions[this.name] = undefined;
  76358. action(extension, function () {
  76359. // Restore the extension after completing the action.
  76360. property.extensions[_this.name] = extension;
  76361. });
  76362. return true;
  76363. };
  76364. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  76365. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  76366. };
  76367. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  76368. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  76369. };
  76370. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  76371. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  76372. };
  76373. GLTFLoaderExtension._ApplyExtensions = function (action) {
  76374. var extensions = GLTFLoaderExtension._Extensions;
  76375. if (!extensions) {
  76376. return;
  76377. }
  76378. for (var i = 0; i < extensions.length; i++) {
  76379. var extension = extensions[i];
  76380. if (extension.enabled && action(extension)) {
  76381. return true;
  76382. }
  76383. }
  76384. return false;
  76385. };
  76386. //
  76387. // Utilities
  76388. //
  76389. GLTFLoaderExtension._Extensions = [];
  76390. return GLTFLoaderExtension;
  76391. }());
  76392. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  76393. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76394. })(BABYLON || (BABYLON = {}));
  76395. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  76396. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  76397. var BABYLON;
  76398. (function (BABYLON) {
  76399. var GLTF2;
  76400. (function (GLTF2) {
  76401. var Extensions;
  76402. (function (Extensions) {
  76403. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  76404. var MSFTLOD = (function (_super) {
  76405. __extends(MSFTLOD, _super);
  76406. function MSFTLOD() {
  76407. return _super !== null && _super.apply(this, arguments) || this;
  76408. }
  76409. Object.defineProperty(MSFTLOD.prototype, "name", {
  76410. get: function () {
  76411. return "MSFT_lod";
  76412. },
  76413. enumerable: true,
  76414. configurable: true
  76415. });
  76416. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  76417. return this._loadExtension(node, function (extension, onComplete) {
  76418. for (var i = extension.ids.length - 1; i >= 0; i--) {
  76419. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  76420. if (!lodNode) {
  76421. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  76422. }
  76423. loader._traverseNode(context, lodNode, action, parentNode);
  76424. }
  76425. loader._traverseNode(context, node, action, parentNode);
  76426. onComplete();
  76427. });
  76428. };
  76429. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  76430. var _this = this;
  76431. return this._loadExtension(node, function (extension, onComplete) {
  76432. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  76433. loader._addLoaderPendingData(node);
  76434. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  76435. loader._removeLoaderPendingData(node);
  76436. onComplete();
  76437. });
  76438. });
  76439. };
  76440. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  76441. var _this = this;
  76442. loader._whenAction(function () {
  76443. loader._loadNode(context, nodes[index]);
  76444. }, function () {
  76445. if (index !== nodes.length - 1) {
  76446. var previousNode = nodes[index + 1];
  76447. previousNode.babylonMesh.setEnabled(false);
  76448. }
  76449. if (index === 0) {
  76450. onComplete();
  76451. return;
  76452. }
  76453. setTimeout(function () {
  76454. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  76455. }, MSFTLOD.MinimalLODDelay);
  76456. });
  76457. };
  76458. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  76459. var _this = this;
  76460. return this._loadExtension(material, function (extension, onComplete) {
  76461. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  76462. loader._addLoaderPendingData(material);
  76463. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  76464. material.extensions[_this.name] = extension;
  76465. loader._removeLoaderPendingData(material);
  76466. onComplete();
  76467. });
  76468. });
  76469. };
  76470. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  76471. var _this = this;
  76472. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  76473. assign(babylonMaterial, isNew);
  76474. if (index === 0) {
  76475. onComplete();
  76476. return;
  76477. }
  76478. // Load the next LOD when the loader is ready to render and
  76479. // all active material textures of the current LOD are loaded.
  76480. loader._executeWhenRenderReady(function () {
  76481. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  76482. setTimeout(function () {
  76483. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  76484. }, MSFTLOD.MinimalLODDelay);
  76485. });
  76486. });
  76487. });
  76488. };
  76489. /**
  76490. * Specify the minimal delay between LODs in ms (default = 250)
  76491. */
  76492. MSFTLOD.MinimalLODDelay = 250;
  76493. return MSFTLOD;
  76494. }(GLTF2.GLTFLoaderExtension));
  76495. Extensions.MSFTLOD = MSFTLOD;
  76496. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  76497. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  76498. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76499. })(BABYLON || (BABYLON = {}));
  76500. //# sourceMappingURL=MSFT_lod.js.map
  76501. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  76502. var BABYLON;
  76503. (function (BABYLON) {
  76504. var GLTF2;
  76505. (function (GLTF2) {
  76506. var Extensions;
  76507. (function (Extensions) {
  76508. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  76509. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  76510. function KHRMaterialsPbrSpecularGlossiness() {
  76511. return _super !== null && _super.apply(this, arguments) || this;
  76512. }
  76513. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  76514. get: function () {
  76515. return "KHR_materials_pbrSpecularGlossiness";
  76516. },
  76517. enumerable: true,
  76518. configurable: true
  76519. });
  76520. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  76521. var _this = this;
  76522. return this._loadExtension(material, function (extension, onComplete) {
  76523. loader._createPbrMaterial(material);
  76524. loader._loadMaterialBaseProperties(context, material);
  76525. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  76526. assign(material.babylonMaterial, true);
  76527. });
  76528. };
  76529. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  76530. var babylonMaterial = material.babylonMaterial;
  76531. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  76532. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  76533. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  76534. if (properties.diffuseTexture) {
  76535. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  76536. if (!texture) {
  76537. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  76538. }
  76539. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  76540. }
  76541. if (properties.specularGlossinessTexture) {
  76542. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  76543. if (!texture) {
  76544. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  76545. }
  76546. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  76547. babylonMaterial.reflectivityTexture.hasAlpha = true;
  76548. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  76549. }
  76550. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  76551. };
  76552. return KHRMaterialsPbrSpecularGlossiness;
  76553. }(GLTF2.GLTFLoaderExtension));
  76554. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  76555. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  76556. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  76557. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76558. })(BABYLON || (BABYLON = {}));
  76559. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  76560. (function universalModuleDefinition(root, factory) {
  76561. if (root && root["BABYLON"]) {
  76562. return;
  76563. }
  76564. if(typeof exports === 'object' && typeof module === 'object')
  76565. module.exports = factory();
  76566. else if(typeof define === 'function' && define.amd)
  76567. define([], factory);
  76568. else if(typeof exports === 'object')
  76569. exports["BABYLON"] = factory();
  76570. else {
  76571. root["BABYLON"] = factory();
  76572. }
  76573. })(this, function() {
  76574. return BABYLON;
  76575. });